Backend Development

Database Query Caching with Redis and Prisma: Reducing Latency in High-Traffic Node.js Apps

As Node.js applications grow, database performance often becomes a major bottleneck. An API that responds quickly with a few hundred users may become…

D
DevByteTechnical Author
Published
15 min read0 views
Database Query Caching with Redis and Prisma: Reducing Latency in High-Traffic Node.js Apps

As Node.js applications grow, database performance often becomes a major bottleneck. An API that responds quickly with a few hundred users may become noticeably slower when thousands of users request the same data simultaneously.

One common cause is repeated database queries. Product listings, user profiles, dashboard statistics, and configuration data may be fetched over and over, even when the underlying information rarely changes.

Redis and Prisma can help reduce this overhead by caching frequently requested query results.

In this guide, we'll build a practical caching layer for a Node.js application using Prisma ORM, Redis, and TypeScript. We'll explore cache-aside caching, TTL strategies, cache invalidation, stampede prevention, and production best practices.

1. Why Database Query Caching Matters

Consider an API that retrieves products from a PostgreSQL database.

const products = await prisma.product.findMany({
  where: {
    isPublished: true,
  },
  orderBy: {
    createdAt: "desc",
  },
  take: 20,
});

Every request executes a database query, even if the same 20 products were fetched moments earlier.

As traffic increases, repeated queries consume database connections, CPU, memory, and I/O resources.

For example, imagine a product API receives 1,000 requests per minute. If every request executes the same database query, the database must process that query approximately 1,000 times per minute.

If the result can safely be reused for 30 seconds, a cache may substantially reduce the number of database queries.

Common symptoms of database bottlenecks

  • API response times increase during traffic spikes.

  • Database CPU utilization remains high.

  • Connection pools become exhausted.

  • Dashboard queries repeatedly calculate the same results.

  • Read-heavy endpoints consume database resources unnecessarily.

Database optimization should come first when queries are inefficient. Caching is most useful when repeated requests can reuse the same result without violating freshness or consistency requirements.

2. Understanding Redis and Prisma

Before implementing caching, let's understand the role of each technology.

What is Prisma?

Prisma ORM is an ORM that provides a type-safe interface for working with databases such as PostgreSQL and MySQL.

Instead of manually constructing SQL for every operation, you can query your database using Prisma Client.

Example:

const user = await prisma.user.findUnique({
  where: {
    id: 1,
  },
});

Prisma makes database operations easier to maintain, but repeated queries can still create unnecessary database load.

What is Redis?

Redis is an in-memory data store commonly used for caching, session storage, queues, and real-time application features.

Redis can store serialized query results so that subsequent requests can retrieve them without executing the original database query.

For example:

First request:
Client → Node.js → Prisma → PostgreSQL
                    ↓
                  Redis

Next request:
Client → Node.js → Redis → Cached response

Redis does not replace Prisma or your database. It sits alongside them to reduce repeated work.

3. Understanding the Cache-Aside Pattern

The cache-aside pattern is one of the most common caching strategies for web applications.

The application checks the cache before querying the database.

The workflow is straightforward:

  1. Receive an API request.

  2. Generate a cache key based on the query and its parameters.

  3. Check Redis for the cached result.

  4. If the result exists, return it.

  5. If the result is missing, query the database.

  6. Store the result in Redis with an expiration time.

  7. Return the result to the client.

Here's the flow:

             API Request
                  |
                  v
             Check Redis
                  |
          +-------+-------+
          |               |
       Cache Hit       Cache Miss
          |               |
          v               v
     Return Data      Query Database
                          |
                          v
                     Store in Redis
                          |
                          v
                     Return Data

This pattern is simple, flexible, and works well for read-heavy APIs.

However, it introduces a freshness trade-off: cached data may remain outdated until it expires or is explicitly invalidated.

4. Set Up a Node.js Project

Let's create a small Node.js application using TypeScript, Prisma, PostgreSQL, and Redis.

Step 1: Initialize the project

mkdir prisma-redis-cache
cd prisma-redis-cache

npm init -y
npm install express @prisma/client redis dotenv
npm install -D typescript tsx @types/node @types/express prisma

npx tsc --init
npx prisma init

Configure the dev script in package.json:

{
  "scripts": {
    "dev": "tsx watch src/server.ts",
    "build": "tsc"
  }
}

Adjust the TypeScript configuration to match your preferred Node.js module system and deployment environment.

Step 2: Start Redis locally

If Docker is installed, start a Redis container:

docker run -d \
  --name redis-cache \
  -p 6379:6379 \
  redis:7-alpine

For local development, this is sufficient to demonstrate the caching workflow.

In production, use an appropriately secured Redis deployment. Do not expose Redis directly to the public internet.

Step 3: Configure environment variables

Create a .env file:

DATABASE_URL="postgresql://postgres:password@localhost:5432/appdb"
REDIS_URL="redis://localhost:6379"
PORT=3000

Replace the database credentials with your actual local configuration.

Keep .env out of version control and use a secret manager for production credentials.

5. Define a Prisma Model

Open prisma/schema.prisma and define a basic product model.

model Product {
  id          Int      @id @default(autoincrement())
  name        String
  description String?
  price       Decimal  @db.Decimal(10, 2)
  isPublished Boolean  @default(false)
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  @@index([isPublished, createdAt])
}

The composite index can help queries that filter by publication status and sort by creation time, depending on the database's query plan and ordering requirements.

Run the migration:

npx prisma migrate dev --name create_product
npx prisma generate

Now the application has a database model that can be queried through Prisma Client.

6. Connect Prisma and Redis

Create a file named src/lib/prisma.ts:

import { PrismaClient } from "@prisma/client";

const globalForPrisma = globalThis as unknown as {
  prisma?: PrismaClient;
};

export const prisma =
  globalForPrisma.prisma ?? new PrismaClient();

if (process.env.NODE_ENV !== "production") {
  globalForPrisma.prisma = prisma;
}

This pattern helps prevent repeated Prisma Client instances during local development with hot reloading.

For production, create and reuse a client according to your application's lifecycle and deployment model.

Next, create src/lib/redis.ts:

import { createClient } from "redis";

const redis = createClient({
  url: process.env.REDIS_URL,
});

redis.on("error", (error) => {
  console.error("Redis connection error:", error);
});

export async function connectRedis() {
  if (!redis.isOpen) {
    await redis.connect();
  }
}

export { redis };

The Redis client is created once and reused instead of opening a new connection for every request.

7. Build a Reusable Query Caching Utility

Rather than repeating Redis operations in every route, create a reusable helper.

Create src/utils/cache.ts:

import { redis } from "../lib/redis";

type CacheOptions = {
  ttlSeconds?: number;
};

export async function getOrSetCache<T>(
  key: string,
  fetchData: () => Promise<T>,
  options: CacheOptions = {},
): Promise<T> {
  const ttlSeconds = options.ttlSeconds ?? 60;

  try {
    const cachedValue = await redis.get(key);

    if (cachedValue !== null) {
      return JSON.parse(cachedValue) as T;
    }
  } catch (error) {
    console.error("Redis cache read failed:", error);
  }

  const data = await fetchData();

  try {
    await redis.set(key, JSON.stringify(data), {
      EX: ttlSeconds,
    });
  } catch (error) {
    console.error("Redis cache write failed:", error);
  }

  return data;
}

This utility follows the cache-aside pattern.

How it works

  • key identifies the cached result.

  • fetchData executes the database query when the cache misses.

  • ttlSeconds controls how long the cached value remains available.

  • Redis read failures fall back to the database.

  • Redis write failures do not prevent a successful database result from being returned.

This example intentionally treats Redis as an optional optimization for reads. Production implementations should also add observability, payload limits, appropriate serialization, and protection against repeated concurrent cache misses.

Important: Falling back to the database during a Redis outage can increase database load dramatically. Use timeouts, connection limits, concurrency controls, and an operational plan for cache outages.

8. Cache a Prisma Query in an Express API

Let's implement a product listing endpoint.

Create src/routes/product.routes.ts:

import { Router } from "express";
import { prisma } from "../lib/prisma";
import { getOrSetCache } from "../utils/cache";

const router = Router();

router.get("/", async (_req, res) => {
  try {
    const products = await getOrSetCache(
      "products:published:latest:20",
      () =>
        prisma.product.findMany({
          where: {
            isPublished: true,
          },
          orderBy: {
            createdAt: "desc",
          },
          take: 20,
        }),
      {
        ttlSeconds: 60,
      },
    );

    res.json({
      success: true,
      data: products,
    });
  } catch (error) {
    console.error("Failed to fetch products:", error);

    res.status(500).json({
      success: false,
      message: "Unable to fetch products",
    });
  }
});

export default router;

The first request normally queries PostgreSQL and populates Redis.

Subsequent requests using the same key can reuse the cached result for up to 60 seconds.

Why the cache key matters

This key:

products:published:latest:20

represents a specific query.

If the endpoint later supports search, pagination, sorting, or filters, the key must include those parameters.

For example:

products:published:page:2:limit:20:sort:price_asc

Otherwise, users making different requests might receive the same cached data incorrectly.

Avoid placing sensitive user information directly in cache keys. Use a stable identifier or a carefully designed hashed key when appropriate.

9. Add Query Parameters to Cache Keys

Imagine the API supports pagination.

router.get("/", async (req, res) => {
  try {
    const page = Math.max(
      1,
      Number.parseInt(req.query.page as string, 10) || 1,
    );

    const limit = Math.min(
      50,
      Math.max(
        1,
        Number.parseInt(req.query.limit as string, 10) || 20,
      ),
    );

    const cacheKey =
      `products:published:page:${page}:limit:${limit}`;

    const products = await getOrSetCache(
      cacheKey,
      () =>
        prisma.product.findMany({
          where: {
            isPublished: true,
          },
          orderBy: {
            createdAt: "desc",
          },
          skip: (page - 1) * limit,
          take: limit,
        }),
      {
        ttlSeconds: 60,
      },
    );

    res.json({
      success: true,
      page,
      limit,
      data: products,
    });
  } catch (error) {
    console.error("Product listing error:", error);

    res.status(500).json({
      success: false,
      message: "Unable to fetch products",
    });
  }
});

In production, validate query parameters strictly. For example, reject invalid or excessively large values rather than silently converting them.

For search endpoints, normalize the search term and include relevant filters and sorting parameters in the cache key.

10. Invalidate the Cache After Updates

Caching introduces an important challenge: what happens when the database changes?

Suppose a product's price changes from $79 to $89. Redis may still contain the old price.

One approach is to delete the relevant cache key after a successful database update.

For a simple product listing, you might use:

await prisma.product.update({
  where: {
    id: productId,
  },
  data: {
    price: newPrice,
  },
});

await redis.del("products:published:latest:20");

However, this only invalidates that exact key. If you have many cached pages, search results, or filters, manually deleting every affected key becomes difficult.

Use versioned cache keys

A practical strategy is to maintain a version number for a group of cached data.

For example:

products:version = 12

A cache key could then look like:

products:v12:published:latest:20

When a product changes, increment the version:

await redis.incr("products:version");

The next request reads the new version and creates a different cache key. Old entries expire naturally according to their TTL.

This strategy is simple and can invalidate many related cache entries without scanning Redis for every matching key.

The trade-off is that invalidating a broad version can cause many cache misses at once. For high-traffic applications, combine versioning with suitable TTLs, request coalescing, and controlled cache warming where necessary.

Update the database before invalidating

For ordinary cache-aside updates, a common sequence is:

  1. Commit the database update.

  2. Invalidate the affected cache entries or increment the relevant cache version.

  3. Return the result.

This prevents the cache from being invalidated when the database write fails.

It does not guarantee perfect consistency under all concurrent request patterns. For critical workflows, use a deliberate consistency strategy and consider transactional outbox patterns or event-driven invalidation.

11. Prevent the Cache Stampede Problem

A cache stampede occurs when a popular cache entry expires and many requests try to rebuild it simultaneously.

For example, 500 requests might arrive for the same endpoint immediately after its cache entry expires. If all 500 requests miss Redis, they could issue 500 database queries.

This reduces the benefit of caching and may overload the database.

Strategy 1: Add TTL jitter

Instead of assigning the exact same TTL to many entries, add a small random variation.

const baseTtl = 60;
const jitter = Math.floor(Math.random() * 15);

const ttlSeconds = baseTtl + jitter;

This reduces synchronized expirations across many keys, but it does not fully prevent a stampede for one extremely popular key.

Strategy 2: Coalesce concurrent requests

Within a single Node.js process, concurrent requests for the same cache key can share one pending database operation.

const inFlight = new Map<string, Promise<unknown>>();

export async function coalesce<T>(
  key: string,
  fetchData: () => Promise<T>,
): Promise<T> {
  const existing = inFlight.get(key);

  if (existing) {
    return existing as Promise<T>;
  }

  const pending = fetchData();
  inFlight.set(key, pending);

  try {
    return await pending;
  } finally {
    inFlight.delete(key);
  }
}

You can combine this helper with the cache-miss path so that concurrent requests share the same fetch operation.

This approach only coordinates requests inside one process. It does not prevent simultaneous misses across multiple Node.js instances.

For distributed applications, consider a carefully implemented Redis lock, stale-while-revalidate strategy, or another distributed request-coordination mechanism. Locks need expiration and failure handling so that a crashed worker does not block regeneration indefinitely.

12. Choose the Right TTL for Different Data

Not every query should use the same cache duration.

Data Type

Example TTL

Reason

Public product listing

30–120 seconds

Changes periodically

User profile

30–60 seconds

Updates occasionally

Dashboard analytics

60–300 seconds

Often tolerates small delays

Static configuration

5–30 minutes

Changes infrequently

Inventory availability

Short TTL or explicit invalidation

Stale data may affect purchases

Payment status

Avoid casual caching

Requires careful consistency

These are starting points, not universal recommendations.

Select TTLs based on how frequently the data changes, how expensive the query is, and how stale the application can safely allow the result to become.

For financial, inventory, permission, and payment workflows, a stale cached value can have serious consequences. Do not use a generic caching helper without considering the business requirements.

13. Handle Redis Failures Gracefully

Redis is an optimization for many cache-aside architectures, but it is still an external dependency that can fail.

Possible causes include:

  • Network interruptions

  • Redis server restarts

  • Connection exhaustion

  • Memory pressure

  • Authentication or TLS configuration errors

  • Service-provider outages

Your application should define how it behaves when Redis becomes unavailable.

For non-critical read caching, falling back to the database can preserve functionality. However, an uncontrolled fallback can turn a cache outage into a database outage.

Consider these safeguards:

  • Set connection and command timeouts.

  • Limit concurrent database queries.

  • Monitor Redis error rates and cache hit ratios.

  • Use connection pooling or a shared client appropriately.

  • Avoid retry loops that amplify traffic.

  • Consider a circuit breaker for persistent Redis failures.

  • Define a recovery strategy before enabling aggressive caching.

A local in-memory cache can sometimes serve as a fallback, but it introduces per-instance state and invalidation complexity. Use it only when its consistency behavior is understood.

14. Measure Cache Performance

Caching should be measured rather than assumed to be beneficial.

Track the following metrics:

Cache hit ratio

The percentage of cache lookups that return a valid entry.

Cache Hit Ratio =
Cache Hits / (Cache Hits + Cache Misses) × 100

For example, if 800 lookups hit Redis and 200 miss, the hit ratio is 80%.

API response time

Track p50, p95, and p99 latency. Average response time alone may hide slow requests during traffic spikes.

Database query volume

Compare database query counts before and after caching.

Redis latency and errors

Monitor command latency, connection problems, memory usage, and rejected operations.

Cache invalidation behavior

Measure how often updates cause cache misses and whether users observe stale data.

Example instrumentation

You can add basic metrics around your cache helper:

let cacheHits = 0;
let cacheMisses = 0;

export function getCacheStats() {
  return {
    cacheHits,
    cacheMisses,
    hitRatio:
      cacheHits + cacheMisses === 0
        ? 0
        : cacheHits / (cacheHits + cacheMisses),
  };
}

Increment the appropriate counter after each cache lookup.

This example is suitable only for a simple demonstration. In production, use a metrics system that aggregates across application instances and exports measurements to your monitoring platform.

15. Common Caching Mistakes

Caching every query

Some queries are cheap, highly variable, or rarely repeated. Caching them may add complexity without meaningful performance benefits.

Using incomplete cache keys

If search terms, pagination, permissions, or filters are missing from the key, different requests can receive incorrect results.

Forgetting invalidation

A good TTL reduces how long stale data persists, but it does not guarantee that the cache reflects every database update immediately.

Caching personalized data publicly

User-specific results must not be shared across users. Include appropriate identity and authorization context in the cache design, or avoid caching the result.

Storing enormous payloads

Large cached values increase memory consumption, network transfer time, and serialization costs. Cache only the data needed by the consumer.

Ignoring database indexes

Redis can reduce repeated reads, but it cannot replace efficient database design. Optimize slow queries and indexes before adding caching where practical.

Using Redis as the source of truth unintentionally

For a conventional cache-aside design, the database remains the authoritative source of persistent application data. Redis entries should be safe to expire or rebuild.

16. Production Best Practices

For a reliable high-traffic Node.js application, follow these principles:

  1. Cache selectively: Focus on expensive, frequently repeated reads.

  2. Use meaningful keys: Include all parameters that affect the result.

  3. Set explicit TTLs: Match expiration to data freshness requirements.

  4. Invalidate after successful writes: Prevent avoidable stale reads.

  5. Control cache misses: Use request coalescing or other stampede-prevention techniques.

  6. Protect sensitive information: Never expose private data through shared cache entries.

  7. Limit payload sizes: Keep cache entries small and purposeful.

  8. Monitor performance: Track latency, hit ratio, and database load.

  9. Plan for outages: Ensure Redis failures do not overwhelm the database.

  10. Test concurrency: Validate behavior when many requests arrive simultaneously.

Conclusion

Database query caching with Redis and Prisma is a practical way to reduce repeated database work in high-traffic Node.js applications.

Prisma provides a type-safe database access layer, while Redis stores reusable query results for fast retrieval. The cache-aside pattern makes it straightforward to introduce caching without redesigning your entire backend.

However, a successful caching strategy requires more than adding redis.get() and redis.set(). Cache keys, expiration, invalidation, concurrent misses, data consistency, and failure handling all influence correctness and performance.

Start with a read-heavy endpoint, measure its baseline performance, implement caching, and compare the results under realistic traffic.

The goal is not to cache everything. It is to reduce unnecessary database work while keeping application data correct and reliable.

Frequently Asked Questions

1. Can Prisma cache database queries automatically?

Prisma Client does not automatically cache every query in Redis by default. You can implement application-level caching or evaluate supported caching extensions and managed caching products.

2. Is Redis faster than PostgreSQL?

Redis can serve cached values without executing the original SQL query, which may reduce response time for repeated reads. Actual performance depends on network latency, serialization, query complexity, data size, and workload.

3. What is the best TTL for Redis query caching?

There is no single best TTL. Choose one based on how frequently the data changes, how expensive the query is, and how much staleness the application can tolerate.

4. How do I invalidate Redis cache after a Prisma update?

After a successful database write, delete the affected cache keys, increment a cache-version key, or publish an invalidation event. Choose a strategy that matches your application's consistency requirements.

5. Can Redis caching prevent database overload?

It can reduce repeated queries when cache hit rates are high. However, cache misses, synchronized expiration, Redis outages, and highly variable queries can still generate significant database load. Use monitoring and concurrency controls alongside caching.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘