Next.js SSR Slow at Peak? Fix It with Caching and ISR

Turn per-request rendering into Next.js ISR caching with a cache that every replica shares, so peak traffic reads cached pages instead of rendering each one.

Published

Applies to Next.js 15 and 16 with the App Router, self-hosted with next start or output standalone; Cache Components need Next.js 16

Next.js SSR slow at peak tends to mean the server renders a page for every request that a cache could have answered. One cookies() call, one uncached fetch or one searchParams read is enough to turn a route dynamic. Then each visitor costs a full React render on a single event loop. Find those routes first, cache them, and make every pod share the same cache.

What breaks at peak

Rendering is CPU work. next start runs one Node.js process, and that process renders one page at a time on its event loop. When requests arrive faster than it can render, they queue. Event loop lag rises, time to first byte rises with it, and the load balancer starts timing out slow requests. Adding pods helps, but each pod repeats the same renders.

Next.js 15 changed the defaults that kept many pages cached. fetch is no longer cached unless you pass cache: 'force-cache'. GET route handlers are no longer cached either. An app with static pages on Next.js 14 can come out of the upgrade with dynamic ones, and no error or warning.

The build output tells you which routes render per request. next build prints a legend like this:

○  (Static)             prerendered as static content
●  (SSG)                prerendered as static HTML (uses generateStaticParams)
ƒ  (Dynamic)            server-rendered on demand

Every ƒ route renders on each request. A Revalidate column appears next to routes that regenerate on a timer, which is Incremental Static Regeneration (ISR).

To find what made a route dynamic, add export const dynamic = 'error' to a page you expect to be static, then build. The build fails and names the API:

Route /products/[id] with `dynamic = "error"` couldn't be rendered statically because it used `cookies()`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering

If your code wraps a request API in try/catch, it can catch the signal Next.js throws for dynamic rendering. Your logs then show this, with the digest DYNAMIC_SERVER_USAGE:

Dynamic server usage: Route /products/[id] couldn't be rendered statically because it used `cookies`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error

Rethrow that error from your catch block instead of logging it and carrying on.

Each pod keeps its own cache. Self-hosted Next.js stores generated pages in memory, 50 MB by default, and on disk. With six replicas, each one regenerates the same page on its own timer. They serve different versions for a while, and an on-demand revalidateTag() reaches only the pod that handled the call.

The Next.js ISR caching setup

Work through the routes from the busiest down. For each one, decide how stale it may be, then pick the cache model your app uses.

Move per-user parts out of the shared page. A product page that reads a cookie for the cart badge renders per visitor. Render the page from shared data, and fetch the cart badge in a client component or in a separate small route. The page then caches once for everyone.

Previous model (Next.js 15, or 16 without Cache Components). Set a revalidate interval on the route segment, and tag the fetches you’ll want to purge:

// app/products/[id]/page.tsx
export const revalidate = 300; // seconds; how stale this page may be

export async function generateStaticParams() {
  return []; // render on first request, then cache
}

export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const res = await fetch(`${process.env.API_URL}/products/${id}`, {
    next: { revalidate: 300, tags: [`product-${id}`] },
  });
  const product = await res.json();
  return <h1>{product.name}</h1>;
}
  • revalidate = 300 serves the cached page for 300 seconds. The first request after that gets the stale page while Next.js renders a fresh one in the background. Set it from how old the data may be when a visitor sees it.
  • generateStaticParams returning an empty list keeps the page out of the build and caches it on first visit. Return your top product ids instead to prerender them at build time.
  • next.tags lets a webhook purge one product without waiting for the timer.
  • Data that doesn’t come from fetch, such as an ORM call, isn’t cached by these options. Wrap it with unstable_cache from next/cache, or with React’s cache() to dedupe it within one render.

Cache Components (Next.js 16). With cacheComponents: true in next.config, pages are dynamic by default and you mark what to cache with 'use cache'. The segment exports above become a compile error, so drop them when you switch:

// app/products/[id]/page.tsx
import { cacheLife, cacheTag } from 'next/cache';

async function getProduct(id: string) {
  'use cache';
  cacheLife('minutes');
  cacheTag(`product-${id}`);
  const res = await fetch(`${process.env.API_URL}/products/${id}`);
  return res.json();
}

export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const product = await getProduct(id);
  return <h1>{product.name}</h1>;
}

The minutes profile revalidates after 1 minute and expires after an hour without traffic. hours, days and max stretch both. I set cacheLife in every cached function, because a missing one falls back to the default profile and hides the real lifetime.

Purge on change. Call revalidateTag from the route handler your CMS or admin tool hits after an edit:

// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache';

export async function POST(request: Request) {
  if (request.headers.get('x-revalidate-secret') !== process.env.REVALIDATE_SECRET) {
    return new Response('forbidden', { status: 403 });
  }
  const { id } = await request.json();
  revalidateTag(`product-${id}`, 'max');
  return Response.json({ revalidated: true });
}

On Next.js 16, revalidateTag takes a profile as its second argument. 'max' marks the entry stale and serves it while a fresh copy renders. A burst of edits then doesn’t turn into a burst of renders. Pass { expire: 0 } when the next visitor must see the change.

Share the cache across replicas. Point every pod at one store with a custom cache handler, and turn off the per-pod memory cache. Changed lines only, in next.config.js:

module.exports = {
  cacheHandler: require.resolve('./cache-handler.js'),
  cacheMaxMemorySize: 0, // no per-pod memory copy; every read goes to the shared store
};

cache-handler.js exports a class with get, set, revalidateTag and resetRequestCache. The cacheHandler docs show the shape with a Map. Back it with Redis for production. Cached entries hold Buffers, so serialize them in a way that survives the round trip. cacheHandler covers ISR pages and route handlers. 'use cache' reads from cacheHandlers, plural, which needs its own handler with a refreshTags() method. Without that, a tag purge clears one pod. Size that Redis with the Redis maxmemory and eviction recipe, on an allkeys-lru instance of its own.

Three more settings matter once you run several replicas:

  • Build once. Build one image and run it everywhere. If you rebuild per environment, set generateBuildId so the cache keys match.
  • Server Actions key. Each next build makes its own key unless you set NEXT_SERVER_ACTIONS_ENCRYPTION_KEY at build time. Pods from different builds then fail with Failed to find Server Action when a request lands on the other build.
  • CDN in front. For ISR pages, Next.js sends Cache-Control: s-maxage=<revalidate>, stale-while-revalidate=..., so a CDN can cache them too. Dynamic pages get private, no-cache, no-store. On the Pages Router, set Cache-Control yourself in getServerSideProps with res.setHeader, and Next.js keeps it.

On Vercel, the platform shares the cache across instances, and you check x-vercel-cache in place of x-nextjs-cache. The route and fetch settings above work the same there.

Fix what’s left on the Node side. The pages that must stay dynamic still render on one event loop per process. Run one process per CPU, as in the Node.js cluster mode recipe. Set next start --keepAliveTimeout above your load balancer’s idle timeout, as the socket hang up recipe explains. A large shared cache in memory raises heap use, so check the heap out of memory recipe before you raise cacheMaxMemorySize.

Test it on your system

Build the app with the change and deploy it to staging with production’s replica count. Check the build output first: the routes you changed should show ○, ● or a Revalidate value in place of ƒ.

Then request a cached page twice and read the header:

curl -s -o /dev/null -D - https://staging.example.com/products/42 | grep -i '^x-nextjs-cache'

The first request after a deploy gives MISS, the next gives HIT, and a request after the revalidate interval gives STALE. Hit the same URL through each pod. With a shared handler, the second pod returns HIT on its first request.

Load test with real URLs, because one hot URL hides cache misses. Export a list of product ids or paths from production traffic into ids.json. This k6 script holds a fixed arrival rate and counts responses by cache status:

import http from 'k6/http';
import { Counter } from 'k6/metrics';

const ids = JSON.parse(open('./ids.json'));
const cacheStatus = new Counter('nextjs_cache_status');

export const options = {
  scenarios: {
    peak: {
      executor: 'constant-arrival-rate',
      rate: 300,            // your peak page views per second
      timeUnit: '1s',
      duration: '15m',
      preAllocatedVUs: 200,
      maxVUs: 1000,
    },
  },
  thresholds: {
    http_req_failed: ['rate<0.01'],
    'http_req_duration{name:product}': ['p(99)<800'], // your TTFB budget
  },
};

export default function () {
  const id = ids[Math.floor(Math.random() * ids.length)];
  const res = http.get(`${__ENV.TARGET}/products/${id}`, { tags: { name: 'product' } });
  cacheStatus.add(1, { status: res.headers['X-Nextjs-Cache'] || 'none' });
}

Run it with k6 run -e TARGET=https://staging.example.com peak.js, once against the current release and once against the change. Partway through, call your revalidate route for a few ids, the way an editor would during a sale.

While it runs, watch these:

  • Cache status counts in the k6 summary. HIT and STALE should dominate after the first minutes. A large none count means the route still renders dynamic.
  • Pod CPU and event loop lag. CPU should sit well below the run against the current release, and lag should stay flat. The event loop monitoring recipe sets up the metric.
  • Redis commands per second and latency, if you added a shared handler.
  • Origin API request rate. It should track page regenerations, not page views.

Pass means your p99 TTFB and error rate hold at peak rate through the revalidation calls. Set both from your SLO before the run.

Keep it healthy

Next.js exposes no Prometheus metrics of its own. Load prom-client from instrumentation.ts and serve it on a side port. Next.js calls register() once when the server starts:

// instrumentation.ts
export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    await import('./instrumentation-node');
  }
}
// instrumentation-node.ts
import http from 'node:http';
import client from 'prom-client';

client.collectDefaultMetrics();
http.createServer(async (_req, res) => {
  res.writeHead(200, { 'Content-Type': client.register.contentType });
  res.end(await client.register.metrics());
}).listen(Number(process.env.METRICS_PORT) || 9100);

These rules use prom-client’s default metrics plus cAdvisor and kube-state-metrics. They assume the container and the scrape job are both named web, and that your scrape config adds namespace and pod labels:

groups:
  - name: nextjs-render
    rules:
      - alert: NextRenderLoopLagHigh
        expr: max by (namespace, pod) (nodejs_eventloop_lag_p99_seconds{job="web"}) > 0.2
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "Next.js event loop p99 lag above 200 ms on {{ $labels.pod }}"
          description: "Renders are queuing. Run next build and look for routes marked as Dynamic that should be cached, then check x-nextjs-cache on the busiest URLs."
      - alert: NextPodCPUSaturated
        expr: |
          sum by (namespace, pod) (rate(container_cpu_usage_seconds_total{container="web"}[5m]))
            / sum by (namespace, pod) (kube_pod_container_resource_limits{resource="cpu", container="web"})
            > 0.9
        for: 15m
        labels:
          severity: warning
        annotations:
          summary: "Next.js pod {{ $labels.pod }} above 90% of its CPU limit"
          description: "The pod spends its CPU on rendering. Check the cache hit share in your CDN or access logs, then cache the hottest dynamic route or add replicas."
      - alert: NextPodsCrashing
        expr: increase(kube_pod_container_status_restarts_total{container="web"}[30m]) > 2
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "Next.js container on {{ $labels.pod }} restarted more than twice in 30 minutes"
          description: "Read the last termination reason with kubectl describe pod. OOMKilled or a heap out of memory error points at cacheMaxMemorySize and the heap limit."

Set the lag and CPU thresholds from a week of your own baseline. I’d also chart the share of x-nextjs-cache: HIT from your access logs, because a deploy that turns a route dynamic shows there first.

Roll back

Keep the previous image tag and next.config.js in version control, and record the build output from the current release with next build > build-before.txt.

  • To undo a route change, revert the commit and redeploy. A page that served stale data in a way users noticed needs that now.
  • To drop the shared cache handler, remove cacheHandler and cacheMaxMemorySize from next.config.js. Each pod falls back to its own memory and disk cache.
  • To leave Cache Components, set cacheComponents: false and restore the segment exports you removed.
  • On Kubernetes, kubectl rollout undo deploy/web returns to the last spec in one step.

If pages show another user’s data or the error rate climbs, roll back now. A per-user value has leaked into a cached page, so find it before you cache that route again. For any other reason, wait for a quiet hour, since the first requests after a rollback all render cold.

More recipes