Caching the result of a query sounds like a solved problem until you try to keep it correct. The read side is trivial: hash the SQL, look it up in Redis, serve the bytes, done. Anyone can build a cache that returns fast answers. The entire difficulty - the thing that separates a toy from a system you can put in front of a production database - is the other half: knowing precisely which cached results a given write has just made wrong, and invalidating exactly those and nothing else. Get it slightly too loose and you serve stale data, which in a cache is not a performance bug but a correctness bug that corrupts whatever reads it. Get it slightly too aggressive and a single-row insert flushes half your cache, your hit rate collapses, and the thundering herd of misses stampedes the database you were trying to protect.
This post is about that invalidation problem specifically. The system is a distributed query result cache: a layer between applications and a SQL database that caches the results of expensive queries keyed by a canonical query fingerprint, and invalidates a cached result the moment any of its source tables receives a write that could change it. The hard part, and the part the whole design is organized around, is computing a precise invalidation set at parse time for arbitrary SQL - so that an insert into orders for region='apac' does not evict a cached aggregate filtered on region='blr', while a SELECT COUNT(*) FROM orders with no filter is correctly invalidated by any write to the table. That is the difference between a cache that stays warm and one that thrashes.
Let me build it properly.
Functional Requirements (FR)
In scope:
- Cache expensive query results, read-through. The application sends a SQL read query (and its bind parameters) to the cache layer. On a hit, return the cached result. On a miss, execute against the database, store the result, and return it. The caller gets the same answer it would from the database, just faster.
- Canonical fingerprint as the key. Two queries that are semantically identical but textually different (different whitespace, case, alias names, comment, equivalent predicate ordering) must map to the same cache entry. The same template with different bind values must map to different entries, because the results differ.
- Precise invalidation on write. When a row is written (insert/update/delete) in any table, every cached result whose answer could have changed must be invalidated, and ideally only those. The granularity target is table-level at minimum, partition/shard-level where the query’s predicates allow it.
- Catch writes that bypass the cache. The source of truth is the database. Writes may arrive through the cache’s write API, but may also arrive directly (a batch job, another service, a DBA). The cache must still invalidate correctly, which means tailing the database’s change stream, not trusting callers to announce their writes.
- Configurable freshness. Per-query-pattern TTL as a safety net, and a bounded staleness bound so that even a missed invalidation self-heals within a known window.
- Observability. Hit ratio, invalidation fan-out, per-table dependency counts, and the ability to answer “why was this entry evicted.”
Explicitly out of scope (own the boundary):
- Being the database. We do not store the authoritative data, run transactions, or guarantee durability of rows. We cache derived read results; the database owns the truth. A total cache wipe must only cost latency, never correctness.
- Caching writes or write-through to disk. This is a read-result cache. Writes pass through to the database; we only observe them to invalidate.
- Arbitrary non-deterministic queries.
SELECT NOW(),RAND(),CURRENT_USER, and queries whose result depends on session state or wall-clock are flagged non-cacheable. We cache queries that are a pure function of table contents and bind parameters. - Full SQL semantic equivalence proving. We canonicalize to a strong normal form, but we do not try to prove that
a>5 AND a>3equalsa>3. Two queries that are equivalent but do not normalize to the same form simply get two cache entries - a hit-rate loss, never a correctness loss. - Cross-datacenter strong consistency. We target single-region strong-ish coherence with the primary; geo-replication of the cache is a layer on top and gets a note, not a design.
The single decision that drives everything: correctness lives entirely on the invalidation side, so the design is built backwards from “what is the smallest, provably-complete set of cached entries this write can affect, and how do I find them without scanning the whole cache.” The key, the dependency model, the reverse index, and the versioning all exist to answer that one question precisely and cheaply.
Non-Functional Requirements (NFR)
- Scale: aggregate across the services behind it, ~400K read queries/sec at peak and ~40K writes/sec against the backing database(s). A cache resident set of tens of millions of distinct hot query results. Thousands of distinct query templates, over hundreds of tables.
- Latency: a cache hit must return in sub-millisecond to low-single-digit ms (it is an in-memory lookup plus deserialization). A miss costs the database query time plus a small cache-store overhead. The invalidation path - from a committed write to the affected entries being gone - must complete in tens of milliseconds p99, because that window is the cache’s staleness exposure.
- Availability: the cache is fail-open. If a cache node or the whole cache is down, reads fall through to the database and the system is slower but correct. The cache must never be a hard dependency that takes down reads. Target 99.9%+ for the cache serving path, but a cache outage is a performance incident, not an outage.
- Consistency: read-your-writes within the invalidation window, bounded staleness otherwise. A cached entry may be at most
invalidation_lagstale in the normal path, and at mostTTLstale in the pathological path where an invalidation is missed. We do not promise linearizability; we promise that stale reads are bounded and that the common case (write then read) is correct. Correctness means: we never fail to invalidate an affected entry (no false negatives). We may over-invalidate (false positives are a hit-rate cost, not a correctness cost). - Durability: none required for cache contents. Everything in the cache is reconstructable from the database. We do need the invalidation stream to be durable and ordered per table, because a dropped invalidation is a silent stale-data bug. The change stream (database binlog/WAL) provides that.
- Efficiency as a first-class NFR. The whole point is to offload the database. A design that keeps a 90% hit ratio cuts database read load 10x; a design that thrashes to 40% because invalidation is too coarse is worse than no cache at all once you count the herd on every eviction. Hit ratio is the product metric.
Back-of-the-Envelope Estimation (BoE)
Grounding the design in numbers before drawing boxes.
Read and write traffic:
Peak read query rate (cacheable): 400,000 q/sec
Target hit ratio: 85%
-> cache-served hits: 340,000 q/sec (in-memory, must be cheap)
-> database-hitting misses: 60,000 q/sec (the DB still sees these)
Peak write rate (DB): 40,000 w/sec (each may invalidate entries)
The read side is a 340K/sec in-memory lookup firehose. The write side is 40K/sec of invalidation work. Both must be cheap per operation or the cluster melts.
Cache resident set:
Distinct hot query results kept: 30,000,000 entries
Avg serialized result size: 3 KB (aggregates + small row sets;
we cap large results, see below)
Value bytes: 30M * 3 KB = 90 GB
Per-entry metadata: key(16B) + dep tags(~80B) +
table versions(32B) + ttl/size(16B) ~ 150 B
Metadata bytes: 30M * 150 B = 4.5 GB
Reverse index: avg ~2 tags/entry, postings refs
30M * 2 * ~20 B ~ 1.2 GB
-> working set ~ 96 GB; with 3x (replica + headroom) ~ 290 GB RAM
across, say, 12-16 cache shards. Comfortable on commodity memory nodes.
The resident set is small because we cache results, not rows, and we evict cold entries with LRU. The memory sizing is dominated by the values; the metadata and reverse index are a rounding error, which matters because the dependency bookkeeping is what makes the whole thing work and it is nearly free.
Bandwidth:
Serve: 3 KB * 340K hits/sec ≈ 1.0 GB/sec out of the cache tier
(spread across 12-16 shards -> ~65-85 MB/sec/shard. Fine.)
Fill: 3 KB * 60K misses/sec ≈ 180 MB/sec written into the cache
Invalidation: 40K writes/sec * (tag msg ~120 B) ≈ 4.8 MB/sec on the
change/invalidation bus. Trivial in bytes; the cost is the
per-write index lookups, not the bandwidth.
Invalidation fan-out - the number that decides the design:
Each write resolves to a small tag set (table tag + maybe a partition tag).
Each tag maps to a postings list of affected cache keys.
If invalidation were table-level only, a write to a 5M-entry-dependent
hot table (e.g. `orders`) would evict ~N entries per write. At 40K w/sec
with even a few thousand entries each, that is tens of millions of
evictions/sec -> the cache can never stay warm.
-> This is exactly why partition/predicate-scoped tags matter: they cut
the postings list a single-row write touches from "everything on the
table" to "the handful scoped to that write's partition."
Two conclusions drive the design. First, the read path is an ordinary in-memory KV lookup and is not where the engineering is - any sharded cache serves 340K hits/sec. Second, the entire system stands or falls on invalidation fan-out: the average number of entries a single write evicts has to be small, which means the dependency tags have to be as fine as the query’s predicates provably allow. Everything interesting below is about computing those tags precisely at parse time and matching them cheaply at write time.
High-Level Design (HLD)
The cache is a read-through layer in front of the database, backed by a sharded in-memory store, with a parser/planner that computes the key and the dependency tags, a reverse dependency index for invalidation, and a change-data-capture tailer that turns committed writes into invalidation tags. The source of truth is always the database; the cache is fail-open.
READ PATH (cacheable SQL + bind params, ~400K q/sec)
┌───────────────────────────────────────────────────────────────────────────┐
│ App / service --(sql, params)--> Cache Proxy (stateless fleet) │
└───────────────────────────────────────────┬───────────────────────────────┘
│
┌────────────────▼─────────────────┐
│ Query Analyzer (per request) │
│ 1. parse SQL -> AST │
│ 2. canonicalize -> template │
│ 3. fingerprint = hash(template) │
│ 4. key = fingerprint + hash(params) │
│ 5. dep tags = f(AST, catalog, params) │
└────────┬──────────────────┬───────┘
│ key │ (store on fill)
┌────────▼─────────┐ │
│ Cache Shard │ hit │
│ (hash(key) -> N)│────────┼──> return bytes
│ KV: key->value │ │
│ + entry meta │ miss │
└────────┬─────────┘ │
│ miss │
┌────────▼─────────┐ │
│ Database (primary + read replicas) │
│ execute query, get result │
└────────┬─────────┘ │
│ result │
┌────────▼───────────────────▼──────┐
│ Fill: store(key, result, tags, │
│ table_versions_at_exec) IF the │
│ versions have not advanced (CAS) │
│ + add key to each tag's postings │
└────────────────────────────────────┘
WRITE / INVALIDATION PATH (~40K w/sec)
┌───────────────────────────────────────────────────────────────────────────┐
│ Writes --> Database (commit) │
│ │ │
│ ▼ (binlog / WAL, ordered per table) │
│ CDC Tailer --per committed row--> derive write tags │
│ {t:orders, t:orders:region=apac} (table tag + partition tag) │
│ │ │
│ ├─> bump table/partition VERSION counter (for lazy check + races) │
│ └─> for each tag: look up postings list -> delete those cache keys │
│ (publish invalidation to all shards via the bus) │
└───────────────────────────────────────────────────────────────────────────┘
Read hot path - a query being served:
- The app sends
(sql, params)to a stateless Cache Proxy. The proxy hands it to the Query Analyzer, which parses the SQL into an AST, canonicalizes it into a normalized template (literals parameterized, whitespace/case/alias normalized, commutative clauses ordered), and computes the fingerprint= hash(template). The full cache key isfingerprint + hash(bind params), because the same template with different params is a different result. - In the same pass over the AST, the analyzer computes the dependency tag set for this query from the parse tree plus the schema catalog (which tables, and for each table whether a predicate pins it to a partition/shard key value from the params). If the query is flagged non-cacheable (non-deterministic function, etc.), the analyzer short-circuits to the database and skips the cache entirely.
- The proxy routes the key to its cache shard (
hash(key) mod N) and does a GET. On a hit, it also checks the entry’s recorded table versions against the current versions (the lazy safety check, below); if fresh, it deserializes and returns. Sub-millisecond. - On a miss, the proxy executes the query against the database (a read replica for most queries), gets the result, and fills the cache: it stores
(key -> result)with the entry metadata(dep tags, table versions observed at execution time, ttl, size), and appends the key to the postings list of each dependency tag in the reverse index. The fill is a conditional write (compare-and-set on table versions) to close the stale-fill race, covered in the deep dive.
Write / invalidation path - a write being reflected:
- A write commits to the database. The CDC Tailer consumes the ordered change stream (MySQL binlog, Postgres logical WAL) row by row. For each changed row it derives the write tag set: the coarse table tag
t:<table>(which catches every full-table-scoped cached query) and, from the row’s partition/shard key value, the fine tagt:<table>:<pk>=<value>(which catches partition-scoped queries). Tailing the binlog - not trusting write callers - is what makes invalidation correct even for writes that bypass the cache. - For each write tag the tailer (a) bumps the version counter for that table/partition (used by the lazy freshness check and to resolve fill races), and (b) looks up the tag’s postings list in the reverse index and deletes those cache keys, broadcasting the deletions to the owning shards over the invalidation bus. A single-row insert into
region='apac'emits{t:orders, t:orders:region=apac}: the coarse tag evicts full-scan queries onorders, the fine tag evicts onlyapac-scoped queries, and a cached aggregate scoped toregion='blr'(taggedt:orders:region=blr) is untouched.
The architectural core: the read path is a boring sharded in-memory KV lookup, and all the design value is in step 2 (compute a precise dependency tag set at parse time) and step 6 (match a write to exactly those tags cheaply via a reverse index), with a version counter closing the races between them. The cache is correct because the database’s own change stream drives invalidation, and it stays warm because the tags are as fine as each query’s predicates provably allow.
Component Deep Dive
The four hard parts, each walked from the naive approach to where it breaks to the real design: (1) the canonical query fingerprint, (2) parse-time dependency extraction and precise partition-scoped invalidation tags - the core challenge, (3) the invalidation mechanism that finds affected entries without scanning the cache, and (4) the consistency/race model that keeps a read-through cache coherent.
1. The Cache Key: From String Hash to Canonical Fingerprint
The key must collapse semantically-identical queries to one entry and keep semantically-different ones apart. Get this wrong and you either split hits across duplicate entries (low hit rate) or, far worse, collide two different queries onto one key (served the wrong result).
Approach A: Hash the raw SQL string (the naive instinct)
key = sha256(sql_text). Simple, fast.
Where it breaks:
- Trivial textual differences fragment the cache.
SELECT * FROM orders WHERE id=5,select * from orders where id = 5, and the same query with a different alias or a stray comment all hash differently and get separate entries. The same logical query issued by three services or three ORMs caches three times, and your hit rate craters because hot queries never converge on one key. - Inlined literals explode the key space. An ORM that inlines
WHERE id=5,WHERE id=6, … produces a distinct string per value. That is sometimes what you want (different results), but it means you cannot reason about the template separately from the parameters, which you need for dependency extraction (the predicate value drives the partition tag). - No structure to extract dependencies from. A raw string gives you nothing to compute invalidation tags from. You would have to re-parse anyway.
A string hash is fast and wrong in both directions: it misses hits on equivalent queries and gives you no structure to invalidate on.
Approach B: Parse, canonicalize, then fingerprint the template plus bound params
Treat the query as a syntax tree and normalize it to a canonical form.
- Parse to an AST with a real SQL parser. This is mandatory anyway - every downstream step (dependency tags, cacheability check) needs the tree.
- Parameterize literals. Replace every literal with a positional placeholder and pull the values into a separate ordered parameter vector:
WHERE region='blr' AND status=2becomes templateWHERE region=$1 AND status=$2with params['blr', 2]. Now the template is what carries structure and dependencies, and the params distinguish results. - Normalize cosmetic differences: lowercase keywords, canonical identifier casing per the dialect, strip comments and whitespace, resolve unqualified names against the default schema (
orders->shop.orders), and expandSELECT *only if you can (otherwise leave it, but tag the whole table). Normalize alias names to positional ones (oandxboth become the first FROM entry) so alias choice does not fragment keys. - Canonically order commutative constructs where it is provably safe: sort
AND-ed predicate conjuncts, sortIN (...)lists, sort projected columns in a plain projection. Do not reorder things where order is semantic (OUTER JOIN order,ORmixed withANDwithout re-proving, window frames). The rule: normalize only transformations you can prove preserve the result; when unsure, leave it and accept two entries. - Fingerprint = hash(canonical template). The full cache key = fingerprint(template) combined with hash(param vector). Same template, different params -> same fingerprint, different key. This separation is the crux: the template is what we extract dependencies from once, and the params both distinguish the result and supply the concrete values that make a dependency tag partition-specific.
input: SELECT SUM(amount) FROM orders /* dash */
WHERE region = 'blr' AND status = 2
parse -> AST
canonical template: select sum(amount) from shop.orders
where region=$1 and status=$2
params: ['blr', 2]
fingerprint = h(template) = fp_9a3c...
key = fp_9a3c... : h(['blr',2]) = fp_9a3c..:p_71e2
Two guarantees to hold: never collide different queries (the fingerprint is over the full normalized structure, including table names and all clauses, and the param hash includes every bound value and its type, so status=2 and status='2' do not collide), and tolerate missed equivalences (if two logically-equal queries normalize differently, they get two entries - a hit-rate cost we accept rather than risk an unsound rewrite). A cache that occasionally duplicates an entry is fine; a cache that ever returns the wrong result is a disaster, so canonicalization is deliberately conservative.
2. Parse-Time Dependency Extraction: Precise Invalidation Sets (the core challenge)
This is the whole system. For every cacheable query we must compute, at parse time, the set of invalidation tags that describes exactly which writes can change its result - precisely enough that a single-row write does not evict queries scoped to a different partition.
Approach A: Invalidate by table, flush everything on any write (the naive baseline)
Tag each cached query with t:<table> for every table it reads. On any write to a table, delete every entry tagged with that table.
Where it breaks at scale:
- A single-row insert flushes the whole table’s cache.
INSERT INTO orders (..., region='apac')deletes every cached query that readsorders, includingSUM(amount) WHERE region='blr'whose answer did not change by one paisa. On a hot table with thousands of cached partition-scoped queries, every write evicts all of them. From the BoE, 40K writes/sec times thousands of entries is tens of millions of evictions/sec - the cache cannot stay warm, and every eviction triggers a miss that stampedes the database. You have built a cache that makes the database busier. - It punishes exactly the workload you most want to cache. Dashboards and tenant-scoped reads are overwhelmingly partition-filtered (
WHERE tenant_id=...,WHERE region=...). Table-level invalidation throws away the one property - the partition filter - that makes them cheap to invalidate precisely.
Table-level flush is correct but useless at scale: the fan-out is so large the hit rate collapses.
Approach B: Predicate-aware, partition-scoped tags from the parse tree + catalog
Walk the AST and, using the schema catalog (which columns are each table’s partition/shard key), compute the finest tag each table reference provably needs. The write side emits matching tags from the changed row. Both sides agree on the tag scheme, so matching is exact.
The tag rule (read side), per base table T the query reads:
- If the query has an equality predicate on
T’s partition/shard key whose value is a constant or a bind param -WHERE region=$1andregionis the partition key - tag the entryt:T:pk=<value>(with the concrete value from the params). The query’s result depends only on rows in that partition. - Otherwise - no predicate on the partition key, a range (
region > $1), anINlist (tag one per value), a function over the key, or a full scan / aggregate over the whole table - tag the entry with the coarset:T. The query can be affected by any write toT, so it must be caught by every write. - Joins: every base table in the FROM/JOIN tree contributes its own tag independently. A join of
orders(scoped toregion=blr) andcustomers(scoped toid=$2) tags the entry with botht:orders:region=blrandt:customers:id=42; a write to either dependency invalidates it. - Views and CTEs: expand them to their base tables and tag the base tables. A cached query over a view depends on the view’s underlying tables, not the view name. This expansion is why you parse, not pattern-match.
- Subqueries,
IN (SELECT ...), EXISTS: recurse; the inner query’s base tables are dependencies of the outer result too.
The tag rule (write side), per changed row in table T: emit both the coarse t:T and the fine t:T:pk=<row's partition value>. For an UPDATE that changes the partition key, emit the fine tags for both old and new values (the row left one partition and entered another). A delete emits the tags for the removed row’s partition.
Now trace the core scenario:
Cached queries on `orders` (partition key = region):
Q1: SUM(amount) WHERE region='blr' -> tag t:orders:region=blr
Q2: SUM(amount) WHERE region='apac' -> tag t:orders:region=apac
Q3: COUNT(*) (no region filter) -> tag t:orders (coarse)
Write: INSERT INTO orders (..., region='apac')
write tags = { t:orders , t:orders:region=apac }
Invalidate entries tagged with ANY write tag:
t:orders -> evicts Q3 (correct: count changed)
t:orders:region=apac-> evicts Q2 (correct: apac sum changed)
Q1 (t:orders:region=blr) matches NO write tag -> SURVIVES (correct!)
That is the exact behavior the problem demands: the single-row apac insert evicts only the apac-scoped and the unscoped queries, and leaves the blr-scoped result in cache. The coarse tag is what makes full-scan queries correct (any write emits t:orders, so COUNT(*) is always invalidated); the fine tag is what keeps partition-scoped queries from being collateral damage.
The correctness invariant that makes this safe: never under-tag, you may over-tag. The read side must emit a tag for every write that could change the result. If the analyzer cannot prove a reference is partition-scoped - a predicate it does not understand, a function on the key, a dialect feature it cannot reason about, a join condition that is not a simple equality - it falls back to the coarse t:T. Falling back lowers the hit rate (more entries share the coarse tag and get evicted together) but can never serve stale data. This asymmetry is the entire safety model: conservative tagging degrades performance gracefully, never correctness.
Multi-column partition keys and secondary scoping: if a table is sharded on (tenant_id, region), the fine tag requires equality on all key columns to be exact; an equality on only tenant_id yields t:T:tenant=$1 (a coarser-but-still-scoped tag) provided the write side also emits that prefix tag. You can define a small lattice of tag granularities per table (table -> tenant -> tenant+region) as long as every write emits every level of the lattice for its row so no read tag can be missed. The discipline is always: the write side emits the full set of ancestor tags, the read side emits the single finest tag it can prove.
This is a static-analysis problem over SQL, and the honest framing in an interview is: we extract dependencies soundly but not completely. Sound (we never miss a dependency) is required; complete (we always find the finest possible tag) is a best-effort optimization bounded by how much of SQL the analyzer understands. Start with equality-on-partition-key (covers the dashboard/tenant workload that is 80% of the value) and widen coverage over time.
3. The Invalidation Mechanism: Finding Affected Entries Without Scanning
We can compute a write’s tags. Now, at 40K writes/sec, we must turn each tag into the set of cache keys to delete - without iterating the cache - and we must catch writes that never touched our write API.
Approach A: On write, scan the cache and match (naive)
For each write, iterate cache entries and delete those whose dependency tags intersect the write’s tags.
Where it breaks: scanning 30M entries per write is absurd - it is O(cache size) per write, 40K times a second. Even sampling or maintaining it lazily, you are doing a linear scan to answer a point question. And it assumes writes come through a path you control, which they do not.
Approach B: Reverse dependency index + version counters + CDC tailing
Three pieces working together.
- Reverse dependency index (tag -> postings list of keys). Maintain, alongside the cache, a map from each dependency tag to the set of cache keys tagged with it. On fill, when we store an entry, we append its key to the postings list of each of its tags. On invalidation, a write tag is a direct lookup:
postings[t:orders:region=apac]is exactly the set of keys to delete. This turns invalidation from a scan into a hash lookup plus a bounded delete. The index is sharded the same way as the cache (or co-located by tag) so a tag’s postings and its entries can be purged together. Postings lists are pruned on eviction and on delete so they do not accumulate dead keys; a background sweeper reconciles stragglers.
Reverse index (tag -> keys):
t:orders -> { Q3key, ... all full-scan queries on orders }
t:orders:region=blr -> { Q1key, ... }
t:orders:region=apac -> { Q2key, ... }
Write tags {t:orders, t:orders:region=apac} ->
delete postings[t:orders] ∪ postings[t:orders:region=apac]
- Change-data-capture tailer as the source of invalidations. The invalidations are driven by the database’s binlog/logical WAL, not by the write API. The CDC tailer reads committed row changes in commit order, and for each row derives the write tags (table tag + partition tag from the row image) and drives the index deletes. This is the correctness keystone: any write that commits - through our API, through a batch job, through a DBA’s
psqlsession - appears in the binlog and therefore gets invalidated. A cache that trusted callers to announce writes would be silently stale the first time someone ran an ad-hoc UPDATE. The stream is ordered and durable per table, so invalidations cannot be lost or reordered relative to the writes that caused them; the tailer checkpoints its offset so a restart resumes exactly where it left off. - Version counters for lazy invalidation and fallback. Alongside eager deletion, keep a monotonic version (epoch) counter per
(table, partition), bumped by the tailer on every matching write. A cache entry records the versions of its dependency tags at execution time. On read, the proxy can lazily compare the entry’s stored versions against the current versions; if any advanced, treat the entry as stale even if the eager delete has not landed yet. This gives two independent guarantees: the eager path (postings delete) is fast and precise, and the lazy path (version check) is a cheap backstop that catches an entry the eager delete raced past. It is also the mechanism that closes the stale-fill race in part 4.
version registry:
v[orders] = 10084
v[orders:region=apac] = 332
entry Q2 stored at exec: {orders:10084, orders:region=apac:331}
after apac insert bumps: v[orders]=10085, v[orders:region=apac]=332
read Q2 -> stored apac ver 331 < current 332 -> STALE, treat as miss
Handling the postings-list fan-out. A coarse tag like t:orders can have a huge postings list (every full-scan query). Those are the entries that should die on any write, so a large delete there is correct, not wasteful - and there are relatively few such queries (full-table aggregates are not the bulk). The fine tags, which are the vast majority, have tiny postings lists (the handful of queries scoped to that exact partition value), so the common single-row write deletes a handful of keys. This is the payoff of part 2: precise tags keep the typical postings list short, which is the entire reason invalidation fan-out stays bounded.
The mechanism in one line: the reverse index makes “which keys does this tag hit” an O(1) lookup, CDC makes the invalidation trigger authoritative and complete, and version counters make it robust to the races - no part of it ever scans the cache.
4. Consistency and Races: Keeping a Read-Through Cache Coherent
A read-through cache has a notorious correctness hole: the stale set race between a slow miss-fill and a concurrent write/invalidate. Plus we need a staleness bound when something goes wrong.
Approach A: Plain look-aside / read-through with no coordination (naive)
Miss -> query DB -> SET the result. Write -> invalidate. No ordering between them.
Where it breaks - the stale-set race:
t0 Read R misses; starts executing SELECT ... -> reads value V1 from DB
t1 Write W commits, changes the row to V2
t2 CDC invalidates the (not-yet-existing) cache entry -> no-op, nothing there
t3 Read R completes and SET(key, V1) <- writes STALE V1 into the cache
... and it is tagged fresh, so nothing will evict it until TTL.
The invalidation happened before the fill wrote the stale value, so the cache now holds V1 while the database holds V2, indefinitely. A naive read-through cache is subtly, permanently wrong under write contention. This is the bug that makes people say “cache invalidation is hard.”
Approach B: Version-guarded fills (CAS) plus leases, with a TTL floor
- Version-guarded fill (compare-and-set on the table versions). When a read starts a miss, it records the current versions of the tables it is about to query. When it goes to
SETthe result, the fill is conditional: store only if those table/partition versions have not advanced since the read began. In the race above, W bumpedv[orders]between t0 and t3, so at t3 the fill sees the version moved and refuses to store V1 (or stores it already marked stale). The stale value never enters the cache. The version registry from part 3 is exactly what powers this check - the same counters serve lazy invalidation and race resolution. - Leases to tame the thundering herd and order fills. When many readers miss the same hot key at once, handing each a direct DB query stampedes the database. Use a lease (a token granted to the first misser): the first reader gets the lease and fills; concurrent missers briefly wait for the fill or serve a slightly stale value. Critically, an invalidation voids outstanding leases, so a fill holding a lease that was invalidated mid-flight is rejected - a second, cleaner mechanism for the same stale-set race, and the standard trick from Facebook’s memcache leases. One DB query refills a hot key, not ten thousand.
- TTL as the correctness floor, not the primary mechanism. Every entry carries a TTL (per query-pattern configurable). TTL is not how we stay fresh - the CDC-driven invalidation is - but it bounds the blast radius of any bug: a missed invalidation, a dropped binlog event during a failover, a tag the analyzer under-computed despite our best efforts. With a TTL of, say, 60s, the worst-case staleness of any entry is 60s even in the pathological path, and the system self-heals. You tune TTL per pattern: seconds for volatile tables, minutes or hours for near-static reference data.
- Write-path ordering and read-your-writes. A client that writes then immediately reads expects to see its write. The invalidation lag (tens of ms, from the BoE) is the window where it might not. For callers that need strict read-your-writes, the proxy supports a write-through-the-proxy path: the proxy, on a write it mediates, synchronously bumps the version and deletes the eager postings before acking the write, so the caller’s subsequent read is guaranteed to miss and refetch. Writes that bypass the proxy still get caught by CDC within the lag window; the synchronous path is an opt-in for the read-your-writes callers.
- Fail-open everywhere. If the cache shard is unreachable, the proxy queries the database and returns the answer - slower, correct. If the CDC tailer falls behind, entries still expire via TTL, bounding staleness. If the version registry is unavailable, fills skip (treat as uncacheable) rather than risk storing unguarded. Every failure mode degrades to “hit the database,” never to “serve wrong data.”
The consistency model stated plainly: we are strongly consistent in the normal path (CDC invalidation plus version-guarded fills eliminate the stale-set race) and bounded-stale in the failure path (TTL caps the damage of any missed invalidation), and we are always fail-open so the cache is a performance layer that can never corrupt a read or take down the database. No linearizability promise, but no silent staleness either.
API Design & Data Schema
Read / write API (what the application calls)
The cache is mostly transparent - ideally a driver/proxy that speaks the SQL wire protocol - but the explicit API makes the contract clear.
# Execute a (potentially cached) read query
POST /v1/query
{
"sql": "SELECT SUM(amount) FROM orders WHERE region = ? AND status = ?",
"params": ["blr", 2],
"max_staleness_ms": 60000, # optional; caps TTL for this call
"consistency": "bounded" # "bounded" (default) | "strong" (bypass cache)
}
200 OK
{
"rows": [ { "sum": 184203.5 } ],
"source": "cache", # "cache" | "database"
"fingerprint": "fp_9a3c",
"age_ms": 1430 # how old the cached result is
}
Notes:
- "consistency":"strong" bypasses the cache and reads the primary.
- Non-deterministic / flagged-uncacheable queries transparently fall through
to the database and return "source":"database".
# Mediated write (optional strong read-your-writes path)
POST /v1/write
{ "sql":"UPDATE orders SET status=? WHERE id=?", "params":[3, 42] }
200 OK { "rows_affected": 1 }
-> proxy executes on primary, then SYNCHRONOUSLY bumps versions + deletes
eager postings for the write's tags before acking.
Admin / control API
GET /v1/stats # hit ratio, fill rate, invalidation fan-out, memory
GET /v1/entry?key=fp_9a3c:p_71e2 # entry meta: tags, versions, ttl, size, age
POST /v1/invalidate # manual purge by tag (ops escape hatch)
{ "tag": "t:orders:region=apac" }
POST /v1/cacheability # mark a template non-cacheable / set its TTL
{ "fingerprint":"fp_9a3c", "cacheable": true, "ttl_ms": 30000 }
GET /v1/dependencies?fingerprint=fp_9a3c # explain the computed tag set
Data model: a KV store for results, a reverse index, a version registry, a small catalog
This is not a relational schema; it is four purpose-built structures. The bulk data lives in an in-memory sharded KV store (Redis-like / custom), not SQL - the access pattern is point GET/SET by opaque key at 340K/sec with TTL and LRU eviction, which is exactly what an in-memory KV is for and exactly what a B-tree row store is bad at. The only strongly-consistent piece is a tiny catalog.
Cache entry (sharded KV, hash(key) mod N):
key = fingerprint(template) : hash(param_vector) # e.g. fp_9a3c:p_71e2
value = serialized result rows (capped; see note)
meta {
dep_tags : [ "t:orders:region=blr", "t:customers:id=42" ] # from parse
table_versions: { "orders:region=blr": 331, "customers:id=42": 5020 } # at exec
created_at, ttl_ms, size_bytes, hit_count
}
Eviction: LRU within memory budget; TTL expiry; explicit invalidation.
Note: results above a size cap (e.g. 256 KB) are not cached - caching a
100 MB result set is a memory and bandwidth anti-pattern; those
queries fall through to the DB. Cache small/medium results only.
Reverse dependency index (tag -> postings list of keys):
tag -> set<key>
"t:orders" -> { fp_count_orders:..., ... } # coarse: full scans
"t:orders:region=blr" -> { fp_9a3c:p_71e2, ... } # fine: scoped queries
On fill: for tag in entry.dep_tags: index[tag].add(key)
On inval: for tag in write_tags: keys = index[tag]; delete keys; index[tag]-=keys
Sharded/co-located with entries; a background sweeper prunes dead key refs.
Version registry (monotonic counters, small, strongly consistent):
(table | table:partition_value) -> monotonic int64 epoch
"orders" -> 10085
"orders:region=apac" -> 332
Bumped by the CDC tailer on each matching committed write.
Read at fill-time (CAS guard) and optionally at read-time (lazy staleness).
Small and hot -> replicated in-memory with a durable log; Raft-backed is fine.
Schema catalog (tiny, authoritative, SQL/Raft):
table(name, schema) ; column(table, name, type)
partition_key(table, [columns]) # which columns define the shard/partition
cacheability(fingerprint, cacheable, ttl_ms) # overrides
non_deterministic_fns = { now, rand, uuid, current_user, ... }
-> consulted by the Query Analyzer to decide fine vs coarse tags and
cacheability. Changes rarely; read constantly; cache it in the proxies.
The split is deliberate: an in-memory KV for the results (point access, eviction, TTL - no SQL engine needed), a reverse index for O(1) tag-to-keys invalidation, a version registry for race-free fills and lazy staleness, and a small strongly-consistent catalog for schema and partition-key metadata. NoSQL/custom for the bulk because the workload is opaque-key GET/SET with eviction, not relational query; SQL/Raft only for the tiny catalog and version registry where consistency actually matters.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each.
1. Invalidation fan-out (the first and biggest wall). Coarse, table-level invalidation makes a single-row write evict thousands of entries; at 40K writes/sec the cache never stays warm and every eviction stampedes the database.
Fix: parse-time partition-scoped tags (part 2). The write emits coarse t:T plus fine t:T:pk=v; scoped reads tag themselves with the fine tag and survive writes to other partitions. This is the single change that makes the cache viable, cutting the typical write’s fan-out from “the whole table” to “a handful.”
2. Read-path hotspots / hot keys. A few extremely popular query results (a homepage aggregate) concentrate GETs on one shard, and on a miss, the herd of concurrent readers hammers the database for the same key. Fix: replicate hot entries across shards (read from any replica), and leases so exactly one reader refills a hot key while others wait or serve slightly-stale. For the shard itself, consistent-hash the keyspace and add replicas for read fan-out.
3. Stale-set race under write contention. A slow miss-fill writes a pre-write value into the cache after the invalidation already passed (part 4’s race). Fix: version-guarded (CAS) fills - store only if the table/partition versions have not advanced since the read began - plus lease voiding on invalidation. The stale value is refused entry. TTL is the floor that bounds any residual bug.
4. Writes that bypass the cache. A batch job or DBA writes directly to the database; a caller-announced invalidation scheme would never see it and would serve stale data forever. Fix: drive invalidation from the database change stream (CDC/binlog), not from the write API. Every committed write is in the ordered, durable log, so every write is invalidated regardless of who issued it. The tailer checkpoints its offset to survive restarts.
5. CDC tailer as a single point / lag. The tailer is the one component whose failure causes silent staleness, and if it lags, invalidations are late. Fix: partition the tailer by table/shard so it scales horizontally and one table’s write burst does not back up others; checkpoint offsets for exactly-resume; run standby tailers with leader election; and keep TTL as the staleness bound that holds even if the tailer is briefly down. Alert hard on tailer lag - it is the system’s correctness pulse.
6. Reverse-index postings bloat. Postings lists accumulate references to evicted/expired keys, and coarse-tag lists grow large. Fix: prune on eviction/delete, run a background sweeper to reconcile, and accept that coarse-tag lists (full-scan queries) are correctly large but few in number. Partition the index with the cache so a tag’s postings and entries are co-located and purged together.
7. Cardinality of fine tags / partition-value explosion. A table partitioned on a high-cardinality column (user_id) produces millions of distinct fine tags and version counters.
Fix: this is usually good (precise, tiny postings each), but bound the version registry memory with LRU over cold partition counters (a missing counter means “assume changed, treat as coarse”), and choose the tag granularity to match the actual partition/shard key, not an arbitrary high-cardinality column. The tag lattice (table -> tenant -> tenant+region) lets you pick a sane level.
8. Analyzer coverage gaps = silent coarse fallback. SQL the analyzer cannot fully reason about falls back to coarse t:T, quietly lowering the hit rate on those patterns.
Fix: measure coarse-fallback rate per template, surface the worst offenders, and extend analyzer coverage where the ROI is highest. Correctness is never at risk (coarse is sound); this is a hit-rate backlog, prioritized by traffic.
9. Large result sets. Caching a multi-megabyte result set burns memory and saturates fill/serve bandwidth. Fix: a size cap - results above a threshold are not cached and fall through to the database. Cache the many small/medium results that dominate the hit count, not the few giant ones.
10. Cold start / mass invalidation herd. A schema change, a cache flush, or a huge bulk load invalidates a large swath at once, and the refill misses stampede the database. Fix: lease-gated refills cap concurrent misses per key; request coalescing at the proxy; staggered TTLs (jitter) so entries do not expire in sync; and for a known bulk load, warm the hot templates before cutting traffic over. The database read replicas absorb the controlled miss rate.
Wrap-Up
The trade-offs that define this design:
- All the engineering is on the invalidation side, not the lookup side. Serving a hit is a boring sharded in-memory GET; the design value is computing, at parse time, the precise set of writes that can change a result, and matching a write to exactly those cached entries without scanning the cache. We spend our complexity budget entirely on staying correct under writes.
- Partition-scoped tags over table-level flush. By extracting an equality predicate on the partition/shard key from the AST and tagging a scoped query
t:T:pk=v, a single-row write into one partition leaves every other partition’s cached results untouched. This is the one decision that turns the cache from a thrashing liability into a 10x database offload, and it is bounded by a hard rule: never under-tag (sound), fall back to the coarse table tag whenever you cannot prove scoping (conservative), over-tagging costs hit rate but never correctness. - CDC-driven invalidation over caller-announced invalidation. Driving invalidation from the database’s own ordered, durable change stream makes the cache correct for every committed write - API, batch job, or ad-hoc DBA session - instead of trusting writers to announce themselves. The tailer is the system’s single most correctness-critical component, so it is partitioned, checkpointed, and standby-replicated, with TTL as the staleness floor behind it.
- Version-guarded fills and leases over naive read-through. The stale-set race (a slow miss-fill storing a pre-write value after invalidation passed) is the classic read-through correctness hole; conditional fills on table versions plus lease-voiding on invalidation close it, and a per-pattern TTL bounds the damage of any invalidation we ever miss.
- Fail-open, bounded-stale over strong consistency. We do not promise linearizability. We promise correctness in the normal path, a TTL-bounded staleness in the failure path, and that a cache outage only ever makes reads slower by falling through to the database - never wrong, never a hard dependency.
One-line summary: a fail-open read-through layer that keys expensive query results by a canonical parsed-and-normalized fingerprint plus bind params, computes partition-scoped dependency tags from the AST and schema catalog at parse time, invalidates via a reverse tag-to-keys index driven authoritatively by the database change stream, and uses per-partition version counters to guard fills against the stale-set race - trading strong consistency for bounded staleness so that a single-row write evicts exactly the cached results it affects and nothing else.
Comments