How to Cache Database Queries Safely
Cache query results without stale correctness: key by all inputs, scope by user where needed, invalidate on write, and guard the N+1 case.
On this page
Introduction
Caching database query results removes repeat work: the same expensive aggregate served to many requests without re-running it. The risk is correctness. A cache key that misses one input serves the wrong result for that input; a key that omits the user serves one user’s data to another; a cache that is not invalidated on write shows old data after a change. Done carefully, a query cache is a large win; done carelessly, it is a source of bugs that are hard to reproduce.
This tutorial caches query results with correct keys, per-user scoping, write invalidation, and stampede protection. It covers what belongs in a key, how to scope personalized queries, how to invalidate derived results, and how to test correctness alongside hit rate. The examples use an application-level cache in front of a database.
Key by every input that changes the result
The cache key must include everything that affects the result: the query identity, each parameter, the sort order, the pagination, and any flag that changes the rows returned. Hash a canonical serialization of these into the key. If a parameter is missing from the key, two different queries collide and one gets the other’s result, which is a silent correctness bug that tests with varied inputs catch.
Canonicalize the inputs before hashing so equivalent queries share a key. Sort parameter names, normalize the pagination, and use a stable serialization so the same logical query always produces the same key. Include a schema or a query version in the key, so a change to the query shape does not reuse results computed by the old shape.
function queryKey(queryId: string, params: Record<string, unknown>, opts = {}) {
const canon = JSON.stringify({
q: queryId,
p: Object.keys(params).sort().map((k) => [k, params[k]]),
o: opts,
});
return 'q:' + queryId + ':' + createHash('sha256').update(canon).digest('hex').slice(0, 16);
}
// different params -> different key; equivalent params in any order -> same key
Scope personalized queries by user or tenant
A query whose result depends on the caller’s identity must include that identity in the key. A dashboard for user A and one for user B compute different rows from the same query text, and a shared key would serve A’s data to B. Include the user or tenant id in the key for any scoped query, and be explicit about which queries are global versus scoped so the decision is visible.
For a query scoped to a role or a permission, include the permission or a hash of it in the key too, so a role change does not reuse a result computed for the old permission. When in doubt, scope; a scoped key is a smaller cache but a correct one, and mixing scoped and global results under one key is the error that leaks data.
function scopedKey(queryId: string, scope: { userId: number; tenantId: number }, params: unknown) {
// scope first so scoped results never collide with global ones
return ['q', 'u' + scope.userId, 't' + scope.tenantId, queryId, hash(params)].join(':');
}
// a global query uses scope = { userId: 0, tenantId: 0 }, a distinct namespace
Invalidate on write, including derived keys
A write that changes rows must evict the query keys whose results include those rows. The affected query may be the direct lookup plus any list, count, or aggregate that includes the changed row. An invalidation that only evicts the direct lookup leaves the list stale. Enumerate the affected keys at write time, or version the affected entity so all its derived keys become unreachable, and prefer a version when the set of derivatives is large or hard to enumerate.
Delete after the write commits, and consider the read-after-write race that can repopulate a stale value; versioned keys avoid it. As a backstop, give every query cache a TTL so a missed invalidation self-heals within the TTL. The TTL is not the primary mechanism for results that must be prompt, but it is the safety net that makes a bug in the invalidation logic a bounded staleness rather than a permanent wrong result.
async function updateOrder(id, patch) {
return db.transaction(async (tx) => {
const order = await tx.update('orders', id, patch);
// version the order: all derived query keys for it become unreachable
const v = await tx.incrVersion('order', id);
return { order, v };
});
}
// reads derive their key from the current version, so old keys are dead
Guard against the N+1 miss
A query cache that is keyed per row can turn a list read into many cache lookups, one per row, which is the N+1 pattern applied to the cache. Prefer caching at the list level, so one lookup returns the page, and reserve per-row caching for rows read individually and often. When both are useful, cache the list and the rows, and invalidate both on a write to a row.
Also protect the origin from a stampede when a hot query key expires: single-flight the load so concurrent misses trigger one database query, not one per request. Pair the single-flight with TTL jitter so a batch of keys set together does not expire together and stampede as a group.
Test correctness and hit rate
Test that a cached result equals the uncached result for the same inputs, which catches a key that omits an input. Test that two different parameter sets produce two different keys and miss each other, which proves the key covers the inputs. Test that a scoped query for one user does not return another user’s cached result. Test that a write evicts the direct and derived keys. Finally, count database queries and assert a warm read does not hit the database, which proves the cache is used.
# same query twice -> one database call; different params -> two
curl -s 'http://localhost:3000/report?month=3' >/dev/null
curl -s 'http://localhost:3000/report?month=3' >/dev/null # cache hit, no db
curl -s 'http://localhost:3000/report?month=4' >/dev/null # different key, one db call
grep -c 'query report' db.log
Common pitfalls
A key that omits a parameter so queries collide, a key that omits the user so scoped data leaks, invalidation of only the direct key, a read-after-write race that repopulates a stale value, and per-row caching that becomes an N+1 in the cache are the recurring mistakes. Keys over every input with canonicalization, scope in the key, versioned or enumerated invalidation as a backstop to a TTL, and list-level caching with single-flight address them.
Conclusion
Caching query results is worth it when the key is right. Include every input and the scope in the key, canonicalize so equivalent queries share, invalidate derived keys on write or version the entity, and guard the miss with single-flight and a TTL backstop. Self-check by asserting a cached result equals the uncached one and that a warm read makes no database call. Then the cache removes repeat work without ever serving the wrong rows.
Sources: PostgreSQL: Prepared statements and plan caching, Redis: Caching patterns, AWS: Caching best practices.
FAQ
- What goes in the cache key?
- Everything that changes the result: the query identity, all parameters, the sort and pagination, and the tenant or user if the result is scoped to them. A key missing one input will serve the wrong result for that input, which is a correctness bug, not just a cache miss.
- How long should a query cache live?
- As long as the staleness the product accepts, with an explicit invalidation on write for results that must reflect changes promptly. A short TTL alone is often enough for dashboards; user-facing reads that follow a write need eviction or a versioned key.
Report a problem with this articleOpens a pre-filled issue on GitHub.