Skip to content
Redis & Jobs guide

Cache Slow Database Queries in Next.js with Redis

Put Redis in front of a slow Postgres query with a small cache-aside helper. Learn how to clear it on writes, stop stampedes when a hot key expires, measure the hit rate, and when Next.js's own cache is the better tool.

20 min Intermediate Markdown for AI

What you'll build

  • A cached() helper that reads Redis first and falls back to Postgres
  • Every cache key with a TTL, so memory never fills up
  • Cache entries cleared when the data changes
  • A short Redis lock so one expired hot key doesn't flood the database
  • Hit and miss counts per cache, so you know it's working

Before you start

  • Node.js 20 or newer
  • A Next.js 16 app using the App Router
  • A Postgres query that is slow or runs very often
  • A free CloudHike.dev account

Redis or Next.js's built-in cache?

First, make sure the query can't just be made faster. Run it with explain analyze and look for a missing index. A cache hides a slow query, but the first request after every expiry is still slow. On Free, databases on the shared server also have a statement timeout (see the Postgres docs), and a cache won't stop that query from hitting it.

Next.js 16 has its own caching. unstable_cache is replaced by the use cache directive, which works when Cache Components are on (the default in new apps). Here is how the options compare:

OptionWhere entries liveBest for
"use cache" with cacheLife and cacheTagIn memory on each server instance by default. Not shared between instances, and gone after a new deploy.Data that is the same for everyone and mostly feeds rendering: marketing pages, public lists, settings
"use cache: remote"A cache handler your host provides, or one you set up with cacheHandlersThe same as above, shared across instances, if your host supports it
Redis cache-aside (this guide)Your Redis, shared by every instance and every deployPer-user or per-team data, results used by route handlers, jobs and other services, and anything where you want full control of keys and clearing

For public data that changes rarely, try use cache first. It needs no extra service:

lib/public-stats.ts
TypeScript
import { cacheLife, cacheTag } from "next/cache";
import { pool } from "@/lib/db";

export async function getPublicStats() {
  "use cache";
  cacheLife("minutes");
  cacheTag("public-stats"); // clear with updateTag("public-stats") in a Server Action

  const { rows } = await pool.query<{ users: number }>("select count(*)::int as users from users");
  return rows[0];
}

Reach for Redis when the hit rate of an in-memory cache is poor (serverless hosts start many short-lived instances), when the cache must survive deploys, or when code outside rendering needs the same cached result.

Step 1: Connect to Redis and Postgres

  1. Sign in at cloudhike.dev and open your project, or create one.
  2. Click Deploy on the Redis card, and on the Postgres card if you don't have a database yet.
  3. Click Copy as .env on each card and paste the values into .env.local.
.env.local
Shell
REDIS_URL=rediss://default:...@...
DATABASE_URL=postgresql://...
Shell
npm install ioredis pg server-only
npm install -D @types/pg

One Redis client and one Postgres pool per server process, both kept on globalThis in development so hot reloads don't pile up connections:

lib/redis.ts
TypeScript
import "server-only";
import Redis from "ioredis";

function createRedis() {
  const client = new Redis(process.env.REDIS_URL!, {
    // A cache should fail fast. A slow Redis must not make pages slow.
    maxRetriesPerRequest: 1,
    commandTimeout: 500,
  });
  client.on("error", (err) => console.error("Redis error:", err.message));
  return client;
}

const globalForRedis = globalThis as unknown as { redis?: Redis };

export const redis = globalForRedis.redis ?? createRedis();
if (process.env.NODE_ENV !== "production") globalForRedis.redis = redis;
lib/db.ts
TypeScript
import "server-only";
import { Pool } from "pg";

const globalForDb = globalThis as unknown as { pool?: Pool };

export const pool = globalForDb.pool ?? new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
if (process.env.NODE_ENV !== "production") globalForDb.pool = pool;

Step 2: Write a cache-aside helper with a TTL

Cache-aside means your code asks the cache first. On a hit it returns the cached value. On a miss it runs the real query, stores the result with an expiry, and returns it. The database never knows the cache exists.

lib/cache.ts
TypeScript
import "server-only";
import { redis } from "@/lib/redis";

// Bump this when the shape of cached values changes, so old entries are ignored.
const PREFIX = "cache:v1:";

// Values are wrapped, so a cached null or 0 still counts as a hit.
type Entry<T> = { v: T };

async function read<T>(key: string): Promise<Entry<T> | null> {
  try {
    const raw = await redis.get(PREFIX + key);
    return raw ? (JSON.parse(raw) as Entry<T>) : null;
  } catch (err) {
    console.error("Cache read failed", key, err);
    return null; // treat Redis trouble as a miss
  }
}

async function write<T>(key: string, value: T, ttlSec: number) {
  // +/- 10% so keys written together don't all expire in the same second.
  const ttl = Math.max(1, Math.round(ttlSec * (0.9 + Math.random() * 0.2)));
  try {
    await redis.set(PREFIX + key, JSON.stringify({ v: value }), "EX", ttl);
  } catch (err) {
    console.error("Cache write failed", key, err);
  }
}

// Hit and miss counts per cache name ("team-stats" for "team-stats:42"),
// one hash per day, kept for a week. See Step 6.
function count(key: string, kind: "hit" | "miss") {
  const day = new Date().toISOString().slice(0, 10);
  const statsKey = `cache:stats:${day}`;
  const name = key.split(":")[0];
  redis
    .multi()
    .hincrby(statsKey, `${name}:${kind}`, 1)
    .expire(statsKey, 8 * 86_400)
    .exec()
    .catch(() => {}); // stats are best effort
}

export async function cached<T>(key: string, ttlSec: number, load: () => Promise<T>): Promise<T> {
  const hit = await read<T>(key);
  if (hit) {
    count(key, "hit");
    return hit.v;
  }
  count(key, "miss");
  const value = await load();
  await write(key, value, ttlSec);
  return value;
}

export async function invalidate(...keys: string[]) {
  if (keys.length === 0) return;
  try {
    await redis.del(...keys.map((k) => PREFIX + k));
  } catch (err) {
    console.error("Cache invalidate failed", keys, err);
  }
}
  • Every key gets a TTL. CloudHike Redis uses the noeviction policy: when memory is full it refuses writes instead of dropping old keys. A cache without expiries fills up and stays full. See the Redis docs.
  • Redis errors are misses. If Redis is down, pages get slower but keep working.
  • Values are JSON. A Date comes back as a string. Select timestamps as text, or convert them after reading.

Step 3: Cache a slow query

Say a dashboard shows team stats from a few count(*) queries over big tables. Every page view runs them, and the numbers barely change from one minute to the next. Wrap the query in cached() and keep the key builder next to it, so writes can clear exactly the same key:

lib/queries/team-stats.ts
TypeScript
import "server-only";
import { cached } from "@/lib/cache";
import { pool } from "@/lib/db";

export type TeamStats = { projects: number; openTasks: number; doneThisWeek: number };

export const teamStatsKey = (teamId: string) => `team-stats:${teamId}`;

export function getTeamStats(teamId: string): Promise<TeamStats> {
  return cached(teamStatsKey(teamId), 300, async () => {
    const { rows } = await pool.query<{ projects: number; open_tasks: number; done_this_week: number }>(
      `select
         (select count(*) from projects where team_id = $1)::int as projects,
         (select count(*) from tasks where team_id = $1 and not done)::int as open_tasks,
         (select count(*) from tasks
            where team_id = $1 and done_at > now() - interval '7 days')::int as done_this_week`,
      [teamId],
    );
    const r = rows[0];
    return { projects: r.projects, openTasks: r.open_tasks, doneThisWeek: r.done_this_week };
  });
}

Use it anywhere on the server. In a Server Component, put the uncached work inside <Suspense> so the rest of the page can render first:

app/teams/[teamId]/page.tsx
TSX
import { Suspense } from "react";
import { getTeamStats } from "@/lib/queries/team-stats";

async function Stats({ teamId }: { teamId: string }) {
  const stats = await getTeamStats(teamId);
  return (
    <dl className="grid grid-cols-3 gap-4">
      <div><dt>Projects</dt><dd>{stats.projects}</dd></div>
      <div><dt>Open tasks</dt><dd>{stats.openTasks}</dd></div>
      <div><dt>Done this week</dt><dd>{stats.doneThisWeek}</dd></div>
    </dl>
  );
}

export default async function TeamPage({ params }: { params: Promise<{ teamId: string }> }) {
  const { teamId } = await params;
  // ...check that the signed-in user belongs to this team...
  return (
    <main className="p-8">
      <h1 className="text-2xl font-semibold">Team overview</h1>
      <Suspense fallback={<p>Loading stats…</p>}>
        <Stats teamId={teamId} />
      </Suspense>
    </main>
  );
}

Cache keys must include everything the result depends on. If the result differs per user, team or filter, those go in the key. Leaving one out shows one user's data to another.

How long should the TTL be? Ask how stale the data may be if you forget to clear it. Seconds to a few minutes suits counts and feeds. Hours suits data that only changes through your own code, since you clear it on every write anyway (next step).

Step 4: Clear the cache when data changes

A TTL alone means users can see old numbers for up to five minutes. For data your app changes itself, delete the key right after the write:

app/tasks/actions.ts
TypeScript
"use server";

import { refresh } from "next/cache";
import { invalidate } from "@/lib/cache";
import { pool } from "@/lib/db";
import { teamStatsKey } from "@/lib/queries/team-stats";

export async function completeTask(taskId: string) {
  // ...check that the signed-in user may change this task...
  const { rows } = await pool.query<{ team_id: string }>(
    "update tasks set done = true, done_at = now() where id = $1 returning team_id",
    [taskId],
  );
  if (rows.length === 0) return { ok: false as const, error: "Task not found." };

  // After the write has committed, never before.
  await invalidate(teamStatsKey(rows[0].team_id));
  refresh(); // re-render the current page with fresh data
  return { ok: true as const };
}
  • Delete, don't update. Writing the new value into the cache can race with another write. Deleting means the next read loads the truth.
  • Clear after the commit. If you clear first, a reader can load the old row and cache it again before your write lands.
  • Keep the TTL anyway. A rare race can still put an old value back, and writes made outside your app (a SQL console, another service) don't clear anything. The TTL limits how long a mistake lives.

Clearing many keys at once

Sometimes one write affects many keys, such as every page of a team's task list. Don't look them up with KEYS or SCAN. Both walk the whole keyspace and get slower as Redis grows. Put a generation number in the key instead, and bump it to make every old key unreachable. The old keys expire on their own.

lib/cache.ts (add at the end)
TypeScript
// Must outlive every cached value that uses it.
const GENERATION_TTL = 7 * 86_400;

export async function generation(name: string): Promise<string> {
  try {
    return (await redis.get(`cache:gen:${name}`)) ?? "0";
  } catch {
    return "0";
  }
}

export async function bumpGeneration(name: string) {
  const key = `cache:gen:${name}`;
  try {
    await redis.multi().incr(key).expire(key, GENERATION_TTL).exec();
  } catch (err) {
    console.error("Generation bump failed", name, err);
  }
}

// Reading:  const gen = await generation(`tasks:${teamId}`);
//           cached(`tasks:${teamId}:${gen}:page:${page}`, 600, load)
// Writing:  await bumpGeneration(`tasks:${teamId}`);

Step 5: Prevent cache stampedes with a short lock

When a popular key expires, every request that arrives before it is refilled misses at once. A hundred requests in that moment means a hundred copies of your slowest query, all at the same time. That is a cache stampede, and it can take a database down just when traffic peaks.

The fix: on a miss, try to take a short lock with SET key token NX PX 5000. NX means only one caller can get it. PX makes it expire by itself, so a crashed process can't hold it forever. The winner runs the query and fills the cache. Everyone else waits a moment and reads the fresh value.

lib/cache.ts (replace cached() with this)
TypeScript
import { randomUUID } from "node:crypto"; // move to the top of the file

const LOCK_MS = 5000; // a bit longer than the slowest query you cache
const WAIT_STEP_MS = 50;

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

// Deletes the lock only if we still own it. Without the check, a slow
// loader whose lock already expired could delete someone else's lock.
const UNLOCK = `
if redis.call("GET", KEYS[1]) == ARGV[1] then
  return redis.call("DEL", KEYS[1])
end
return 0
`;

async function tryLock(lockKey: string, token: string) {
  try {
    return (await redis.set(lockKey, token, "PX", LOCK_MS, "NX")) === "OK";
  } catch {
    return true; // Redis is down: just load, there is nothing to share anyway
  }
}

async function unlock(lockKey: string, token: string) {
  try {
    await redis.eval(UNLOCK, 1, lockKey, token);
  } catch {
    // The lock expires by itself.
  }
}

export async function cached<T>(key: string, ttlSec: number, load: () => Promise<T>): Promise<T> {
  const hit = await read<T>(key);
  if (hit) {
    count(key, "hit");
    return hit.v;
  }
  count(key, "miss");

  const lockKey = `cache:lock:${key}`;
  const token = randomUUID();

  if (await tryLock(lockKey, token)) {
    try {
      const value = await load();
      await write(key, value, ttlSec);
      return value;
    } finally {
      await unlock(lockKey, token);
    }
  }

  // Someone else is loading it. Wait for their result.
  const deadline = Date.now() + LOCK_MS;
  while (Date.now() < deadline) {
    await sleep(WAIT_STEP_MS);
    const fresh = await read<T>(key);
    if (fresh) return fresh.v;
    // Lock gone but still no value: the other loader failed. Stop waiting.
    if (!(await redis.exists(lockKey).catch(() => 0))) break;
  }
  return load(); // fall back to the database rather than fail the request
}

Now an expired hot key costs one query, not a hundred. The others wait a few tens of milliseconds. If the loader crashes, the lock expires after five seconds, and if it throws, the waiters notice the lock is gone and load the data themselves.

Two more ways to soften stampedes: the random TTL jitter from Step 2 spreads out expiries of keys written together, and a Map of in-flight promises in each process stops one server from running the same load twice at once.

Step 6: Measure your hit rate

A cache that rarely hits only adds a network round trip to every request. The count() function from Step 2 already records hits and misses per cache name, in one hash per day. Read today's numbers from a terminal:

Terminal
Shell
redis-cli -u "$REDIS_URL" hgetall "cache:stats:$(date -u +%F)"
# 1) "team-stats:hit"
# 2) "1824"
# 3) "team-stats:miss"
# 4) "96"

That's 1824 / (1824 + 96), about a 95% hit rate. For an admin page, compute it in code:

lib/cache.ts (add at the end)
TypeScript
export async function cacheHitRates(day = new Date().toISOString().slice(0, 10)) {
  const stats = await redis.hgetall(`cache:stats:${day}`);
  const names = new Set(Object.keys(stats).map((f) => f.slice(0, f.lastIndexOf(":"))));
  return [...names].map((name) => {
    const hits = Number(stats[`${name}:hit`] ?? 0);
    const misses = Number(stats[`${name}:miss`] ?? 0);
    return { name, hits, misses, hitRate: hits + misses ? hits / (hits + misses) : 0 };
  });
}
What you seeWhat it usually means
Hit rate above 80%The cache is doing its job
Low hit rate, many different keysThe key includes something too specific (a timestamp, a full search string). Cache a broader result, or don't cache this query
Low hit rate, few keysThe TTL is shorter than the time between reads, or writes clear the key very often
Hit rate fine, pages still slowThe slow part is somewhere else. Time the query and the render on their own

Also keep an eye on memory. With noeviction, a full Redis refuses new writes, so cache writes start failing (the helper logs them and carries on). The Redis card shows memory use, and redis-cli -u "$REDIS_URL" info memory shows used_memory_human.

Production checklist

  • Add REDIS_URL and DATABASE_URL to your host's environment variables.
  • Give every key a TTL, including locks, stats and generation counters.
  • Put everything the result depends on (user, team, filters, page) in the key, and never cache across users by mistake.
  • Clear keys after writes commit, and keep TTLs short enough that a missed clear is harmless.
  • Bump the cache:v1: prefix when the shape of a cached value changes.
  • Check the hit rate after a week. Remove caches that don't help.
  • Size Redis for your cache plus anything else it holds, such as rate limits and job queues. Sizes are on the pricing page and in the Redis docs.

Frequently asked questions

How do I cache database queries in Next.js?

Wrap the query in a cache-aside helper: read the key from Redis, return it on a hit, otherwise run the query and store the result with an expiry. For data that is the same for every user, the use cache directive with cacheLife and cacheTag is a built-in alternative in Next.js 16.

Should I use Redis or the Next.js use cache directive?

Use use cache for shared data that mostly feeds rendering. Its default store is in memory per server instance and starts empty after each deploy. Use Redis when many instances should share one cache, when it must survive deploys, or when route handlers, jobs and other services need the same cached data.

Is unstable_cache deprecated in Next.js 16?

It has been replaced by the use cache directive. The Next.js docs recommend turning on Cache Components and moving from unstable_cache to use cache with cacheLife and cacheTag.

How do I invalidate a Redis cache when data changes?

Delete the affected keys right after the database write commits, and keep a TTL on every key as a safety net. To clear many related keys at once, put a generation number in the keys and increment it, instead of scanning for keys.

What is a cache stampede and how do I prevent it?

It happens when a popular key expires and many requests run the same slow query at once. Prevent it with a short lock: the first request takes it with SET NX PX and refills the cache, and the others wait briefly and read the new value.

What TTL should I use for a Redis cache?

Pick the longest time the data may be out of date if a clear is missed. Seconds to minutes suits counts and feeds. Hours suits data that only changes through your own code, since you clear it on every write. Add a little random jitter so keys don't all expire together.