Mustlist

Caching for a Next.js + Postgres app

VerifiedLast verified 15 Nov 2026R@RIDAM7v1.0.0
Suggest a change

Cache shared, non-personal reads with use cache, cacheLife and cacheTag (Next.js 16 Cache Components). Check auth outside cached code, key on every input, invalidate tags where you write, never CDN-cache cookie responses, and fix slow SQL with indexes first.

Forweb-appsaasdashboardcontent-siteecommerce
Not forpages-router-only-appstatic-export-site

Must-have checklist

11 must · 3 should

Must

01

Check the session and permissions on every request outside the cached function, pass the verified user or tenant id in, and keep the cached helper unexported.

A cache hit returns the stored result without running the function body, so a check inside it is skipped.

Security
02

Pass every input the result depends on (user or tenant id, role, locale, filters) as an argument; never cache per-user or permission-dependent data under a shared key.

Arguments and captured variables form the cache key; anything left out is shared between callers.

Security
03

Key and tag on stable ids; keep tokens, passwords and raw emails out of cached-function arguments and cacheTag values.

Next.js stores cache keys and tags in plain text, including in remote cache handlers.

Security
04

Send Cache-Control private, no-store on any response that sets a cookie or depends on the session; never public or s-maxage.

Set-Cookie alone does not stop a shared cache from storing and reusing a response (RFC 9111, section 7.3).

Security
05

Authenticate Route Handlers that call revalidateTag or revalidatePath for webhooks (shared secret or signature) and accept only known tags.

An open endpoint lets anyone flush the cache and push the load onto Postgres.

Security
06

Tag cached reads with cacheTag (collection and entity tags) and invalidate those tags in every Server Action, Route Handler or job that writes, after the write commits.

Data
07

After a user's own change, call updateTag in the Server Action (Next.js 16) so their next read waits for fresh data; use revalidateTag(tag, 'max') where brief staleness is fine.

UX
08

Wrap components that read cookies, headers, searchParams or uncached data in Suspense with a fallback, and move those reads as deep in the tree as possible.

With Cache Components, an uncached or runtime read outside Suspense is flagged as a blocking route.

Performance
09

With more than one app instance, use a cache handler that shares tag state across instances, or document that other instances may be stale up to cacheLife.

By default revalidateTag only invalidates the cache on the instance that received the call.

Data
10

Before caching a slow query, find it with pg_stat_statements, read its plan with EXPLAIN (ANALYZE, BUFFERS), and add the missing index.

Performance
11

Use a pooled Postgres connection so cache-miss bursts after a deploy or revalidation don't exhaust max_connections.

Postgres runs one backend process per connection and max_connections is typically 100 by default.

Performance

Should

12

Set an explicit cacheLife in every use cache scope, chosen from how stale that data may be.

Without it the implicit default profile applies, and nested lifetimes become hard to reason about.

Performance
13

Serve heavy shared aggregates from a materialized view with a unique index, refreshed CONCURRENTLY on a schedule or after batch writes.

CONCURRENTLY refreshes without blocking reads but needs a unique index on plain columns.

Performance
14

Give only public, non-personalised GET Route Handlers Cache-Control public, s-maxage and stale-while-revalidate, and purge the CDN when on-demand revalidation must reach it.

revalidateTag and revalidatePath clear the Next.js cache, not a CDN copy.

Cost

Decisions to make

Asked before building

01Which Next.js caching model does the app use?

02How quickly must readers see a change after it is written?

03Are pages personalised per user or per permission?

04How many app instances or services read and write this data?

05Do pages show expensive aggregates (counts, sums or reports over large tables)?

Options

3 compared
RecommendedFits your answers

Next.js framework cache (Cache Components)

Best fit when
  • Data is shared by many users and may be a little stale
  • One Next.js app owns the writes and can invalidate tags
  • You want cached parts in the prerendered static shell
Avoid when
  • Several services must share cached values outside Next.js
  • Entries must survive a deploy
Trade-offs
  • The default store is in-memory per instance, ephemeral on serverless, and resets on every deploy
  • Invalidation reaches other instances only through a shared cache handler
  • Cache keys and tags are stored in plain text

Shared external cache (Redis-compatible)

Examples, not endorsements: Redis, Valkey, Upstash Redis

Best fit when
  • Several app instances or services need the same cached values
  • A slow or rate-limited upstream must be protected under high traffic
  • You self-host and need a shared store behind use cache: remote (cacheHandlers)
Avoid when
  • One instance and the framework cache are enough
  • Keys are mostly unique per request or per user, so the hit rate is low
  • The query is already fast
Trade-offs
  • A network round trip on every lookup
  • Another service to run, secure, monitor and pay for
  • Every write path must delete or re-tag the affected keys

Database-side materialized views

Best fit when
  • Heavy aggregates are read often and change in batches
  • Several apps or services read the same summaries
  • Minutes to hours of staleness is acceptable
Avoid when
  • Data must be current on every read
  • Base tables change so often that refreshes would run back to back
Trade-offs
  • Each refresh recomputes the whole query
  • CONCURRENTLY needs a unique index and an already populated view
  • You schedule and monitor refreshes yourself

Why this approach

With Next.js 16 Cache Components, data is dynamic by default and you opt in per function with use cache, so the framework cache is the cheapest correct default: no extra service, tag-based invalidation, and cached parts join the prerendered shell. Cache only data that is the same for everyone who can see it, or key it on a verified user id, and invalidate its tags in the code that writes. Add a shared Redis-compatible cache (through use cache: remote or your data layer) when several instances or services must share entries and the hit rate is high. Use Postgres materialized views for heavy aggregates that many readers share, and fix slow queries with indexes before caching anything.

Lenses

The main risk is serving one user's data to another. A use cache or use cache: remote entry is shared by every caller that passes the same arguments, so check the session and permissions outside the cached function on every request, pass in the verified user or tenant id, and keep the cached helper unexported so no caller can pass someone else's id. A check inside a cached function is skipped on a cache hit. use cache: private keeps results in the browser only, never in a server cache. Next.js stores cache keys and tags in plain text, so key on stable ids, never on tokens or emails. Responses that set cookies or read the session must send Cache-Control: private, no-store, because Set-Cookie alone does not stop a shared cache from storing them (RFC 9111, section 7.3). Authenticate revalidation webhooks: an open endpoint lets anyone flush the cache.

Version notes

next>=15.0.0 <16.0.0
  • use cache is experimental only; cache Postgres queries with unstable_cache(fn, keyParts, { tags, revalidate }) and dedupe per request with React cache.
  • fetch and GET Route Handlers are not cached by default; opt in with cache: 'force-cache' or export const dynamic = 'force-static'.
  • revalidateTag(tag) takes one argument and updateTag does not exist; call revalidateTag or revalidatePath in the Server Action that writes.
  • Reading cookies() or headers() makes the whole route dynamic, and they can't be read inside unstable_cache: pass values as arguments.
next>=16.0.0
  • Enable cacheComponents: true (and set partialPrefetching explicitly from 16.3); data is dynamic by default and you opt in with use cache, cacheLife and cacheTag.
  • cookies(), headers() and searchParams throw inside use cache and use cache: remote; read them outside and pass values in, or use use cache: private (browser only).
  • revalidateTag(tag, profile) needs a second argument ('max', or { expire: 0 } in webhooks); updateTag(tag) works only in Server Actions.
  • Uncached or runtime reads outside <Suspense> are flagged as blocking routes; Cache Components needs the Node.js runtime (remove any runtime export).
  • By default use cache entries live in per-instance memory, and all entries reset on every deploy; use cache: remote needs a cache handler from your host or cacheHandlers.

Verify checks

10 checks
01

Two users with different permissions load the same page and endpoint twice; each sees only their own data, including on the second, cached request.

integrationSecurity
02

Calling the exported data getter without a valid session redirects or returns 401 even when a cached entry exists for another user.

integrationSecurity
03

Every response that sets a cookie or reads the session has Cache-Control with private or no-store, and never public or s-maxage.

integrationSecurity
04

No cached function takes a token, password or raw email as an argument, and no cacheTag value contains one.

scanSecurity
05

The revalidation Route Handler returns 401 without a valid secret or signature and ignores unknown tags.

integrationSecurity
06

After a user saves a change through a Server Action, the next page view shows the new value without a reload or waiting for cacheLife to pass.

e2eUX
07

Writing a row invalidates every cached read tagged for it; list and detail views return the new data on the next request.

integrationData
08

With two app instances, a write handled by one instance is visible on the other within the documented freshness window.

integrationData
09

The materialized view has a unique index, and REFRESH MATERIALIZED VIEW CONCURRENTLY completes while concurrent reads keep returning rows.

integrationData
10

The top queries in pg_stat_statements use index scans or have a recorded reason not to, and each cached query has an EXPLAIN ANALYZE plan on record.

manualPerformance

Common mistakes

  • Checking the session inside a use cache function, so a cache hit skips the check.
  • Caching per-user or role-dependent data without the user, tenant or role in the arguments.
  • Reading cookies() or headers() inside use cache (it throws) instead of passing the values in.
  • Marking responses that set cookies or show account data public or s-maxage for a CDN.
  • Writing to Postgres without invalidating the tags that cache that data, or invalidating before the transaction commits.
  • Calling revalidateTag(tag) with one argument on Next.js 16 (deprecated), or updateTag in a Route Handler (it throws).
  • Expecting revalidateTag on one instance to clear the other instances or the CDN.
  • Caching a slow query instead of adding the missing index.
  • Using use cache: remote for keys that are unique per request, so the hit rate is near zero.
  • Omitting cacheLife and relying on the implicit default profile.

Sources

24 sources