Aller au contenu principal

Two Stores, One Truth: Keeping a Cache and a Database in Sync

· 10 minutes de lecture
Clustron Team
Ingénierie des systèmes distribués

A cache in front of a database is one of the most common performance moves there is. Reads that used to hit disk and run a query now come back from memory in microseconds, the database stops being the bottleneck, and the whole system gets faster for the price of a little RAM. The catch arrives the instant you add it: the same fact now exists in two places at once. As long as that fact never changes, the two copies agree and everything is fine. But facts change, and when one does, you are suddenly obliged to update two independent systems — the database and the cache — that have no shared transaction between them. You cannot write both in a single atomic step, and that gap is the whole problem.

The usual response is cache-aside, and it looks airtight. On a read, check the cache; on a miss, load from the database and populate the cache so the next read is fast. On a write, update the database — the source of truth — and then invalidate the cached copy so the next read reloads the new value. Simple, widely used, and correct for a single thread doing one thing at a time. The trouble is that a real system has many threads, and cache-aside has a narrow window where two of them interleave badly.

In that window, a reader that missed the cache and a writer that is updating the database cross paths, and the cache ends up holding a value that was stale before it was ever written. This post is about that race — why it happens, why invalidating beats updating, how a version number closes the gap, and why the cleanest answer is to stop doing two writes at all.

The pattern that is almost right​

Start with the write path, because its ordering is the first thing people get wrong. On a write you update the database first and invalidate the cache second. If you reverse it — invalidate first, then update the database — a concurrent reader can slip in between the two steps, miss the just-emptied cache, read the old value from the not-yet-updated database, and repopulate the cache with it. So the rule is database-then-invalidate: change the source of truth, then drop the stale copy so the next read is forced to reload.

With that ordering the pattern handles the simple cases cleanly. A write lands in the database and clears the cache; the next reader misses, reloads the fresh value, and caches it. No staleness, no coordination, nothing clever. The reason cache-aside is everywhere is that this is genuinely most of the traffic, and for most of the traffic it is exactly right.

The stale-repopulation race​

Now add concurrency. Reader A asks the cache for a key and misses. It goes to the database and reads value v1. It is now holding v1, a microsecond away from writing it into the cache. In that microsecond, Writer B updates the database to v2 and invalidates the cache — but the cache is already empty, so the invalidation does nothing. Then A completes its populate, writing v1 into the cache. The cache now holds v1; the database holds v2; and nothing will reconcile them, because no further write is on its way to trigger another invalidation. A read populated a value that was obsolete the moment it landed, and the invalidation that was supposed to prevent exactly this fired into an empty slot a beat too early.

Reader ACacheDatabaseWriter B1 · GET → miss2 · read → v13 · write v24 · invalidate (empty — no-op)5 · populate v1 (stale!)Cache = v1 ✗Database = v2the cache stays stale until its TTL expires — no write is coming to fix it

Invalidate, don't update​

A question that comes up here: on a write, why delete the cached entry instead of just writing the new value straight into the cache? Because updating the cache opens a second race. Two writers that both update the cache can land out of order relative to how they landed in the database. Writer B commits v2 and then writes v2 to the cache; Writer A commits v3 and writes v3 to the cache; but if the cache writes arrive in the order A-then-B, the cache ends up holding v2 while the database holds v3. Deleting sidesteps the whole problem: an invalidation carries no value to land in the wrong order, and the next reader reloads from the single source of truth. "Invalidate, don't update" eliminates that entire class of races. It does not, on its own, fix the repopulation race above — but it is strictly less to go wrong, and it is the right default.

A version is a fence for the cache​

The repopulation race has a precise fix, and it is the same idea as a fencing token. Give every value a monotonically increasing version from the database — a row version, a commit sequence number, a logical update counter. Carry that version into the cache alongside the value, and make the cache accept a write only if its version is newer than whatever the slot already holds or has recently held. Now replay the race: Writer B's commit makes the database version 2; Reader A tries to populate with (v1, version 1); the cache, having already observed version 2, rejects anything older and refuses the stale write. The reader can no longer win a race with a value it fetched before the writer committed, because the value it fetched is stamped as older and the cache will not move backward.

// Read miss: load the value AND its version from the database.
(value, version) = db.Load(key)
cache.PutIfNewer(key, value, version) // refused if the cache holds a higher version

// Write: bump the database version, then invalidate.
version = db.Write(key, value) // returns the new row/commit version
cache.Invalidate(key) // next read reloads (value, version)

This is fencing applied to cache coherence: the cache keeps a high-water mark and rejects anything below it, exactly as a fenced resource rejects a superseded lock holder. It requires a cache that supports a conditional, version-aware write — but that is a small price for closing the one race a plain invalidation cannot.

The real fix: stop writing twice​

Every technique so far is damage control around a basic impossibility — you cannot atomically write two independent stores. The way out is to not write two stores. Make one of them derived from the other: let the database be the single source of truth, and feed the cache from the database's ordered change stream. Every committed change flows through a log in commit order, and the cache applies the log in that order. Now the cache is never updated out of order, because the log is ordered; never updated with a value the database did not actually commit, because the log is the commit record; and never more stale than the log's lag. There is no dual write, because there is only one write — to the database — and the cache is a projection of it. This is where an operation log or a change feed earns its keep: it turns "keep two stores in sync" into "replay one ordered stream," which, unlike the dual write, is a problem with a real solution.

Wrap-up​

Fronting a database with a cache means holding one truth in two places that cannot be written atomically, and the ordering and timing of the two updates is where staleness lives. Cache-aside is the right default and is almost correct; the "almost" is a concurrency gap in which a reader's populate lands just after a writer's invalidate and pins a value that was obsolete before it arrived. Invalidate instead of update to kill the out-of-order-write races, bound the residual staleness with a TTL, and fence the repopulation race with a monotonic version the cache refuses to go backward on. But the cleanest answer is to stop writing twice: make the database the source of truth and the cache a derived view fed from its ordered change stream, so keeping them in sync stops being two racing writes and becomes one ordered replay. Two stores can hold one truth — but only when one of them is downstream of the other.