Cache Consistency Governance

A cache sits between the application and the database, holding frequently accessed data so fewer queries hit the database directly. When you keep hot data in fast storage like Redis, repeated requests are served straight from the cache instead of running the same database query again, which cuts response latency significantly.

That performance gain comes with a new set of problems, and the biggest one is keeping the cache consistent with the database. Because they are two separate storage systems, updates do not always sync in real time, so the two can drift apart. When that happens, users see stale or wrong data, which hurts both user experience and business decisions.

So whenever you introduce a cache into a system, keeping it consistent with the database becomes a problem you can’t dodge. You have to trace the exact scenarios that cause divergence and design governance strategies that keep inconsistency rare without throwing away the performance you added the cache for in the first place.

Introducing a cache

In the simplest case, an early-stage product with light traffic, reads and writes go straight to the database. The architecture looks like this:

img

As traffic grows, hitting the database on every request starts causing performance bottlenecks. That’s when a cache enters the picture:

img

The usual choice here is Redis (there are other great caching systems too, I just haven’t used them). Once the cache is in place, the immediate question is: how does data get into it?

One approach is to dump the entire database into the cache with no expiration time, sync changes over via scheduled jobs or DTS, and route all reads to the cache:

img

Reads hit the cache directly, so speed is great. The downside is low cache utilization, because the cache fills up with rarely read cold data. And no matter how well you tune your sync pipeline, you’ll never get zero-latency replication, so inconsistency is guaranteed to happen.

Cache utilization and consistency

Let’s tackle utilization first. We only want to cache hot data, using a simple flow:

  • All writes go to the database.
  • Reads check the cache first; on a miss, read from the database.
  • Write the result back to the cache with an expiration time (TTL).

img

Over time, cold entries expire and never get rebuilt because nobody queries them. Before long, what remains in the cache is genuinely hot data.

Now for consistency. Since scheduled jobs and DTS can’t give us zero latency, a write request has to update both the database and the cache. Right away, that raises an ordering question:

  1. Update the database first, then update the cache.
  2. Update the cache first, then update the database.

Because there are two separate steps, step one can succeed while step two fails:

  1. Database update succeeds, cache update fails: subsequent reads hit the cache and get the old value until the old entry expires and gets rebuilt. To the user, their edit either didn’t take effect or only showed up after a delay.
  2. Cache update succeeds, database update fails: reads get the new value for a while, then the cache entry expires, gets rebuilt from the database’s old value, and suddenly the user’s change appears to have reverted on its own.

Set ordering aside for a second and look at concurrency.

Scenario: two threads, T1 and T2, update the same record at the same time using “update DB first, then update cache.” Here’s what can happen:

  1. T1 updates DB: x = 1
  2. T2 updates DB: x = 2
  3. T2 updates cache: x = 2
  4. T1 updates cache: x = 1

Final state: DB has x = 2, cache has x = 1. They’re out of sync. “Update cache first, then DB” suffers from the exact same race, so no need to belabor it.

How do you prevent concurrent updates from stepping on each other? The usual answer is a distributed lock.

Before updating, a thread has to acquire a lock; only the holder proceeds, while others block or fail and retry.

Even then, both dual-update patterns hurt cache utilization because every write pushes data into the cache, filling it with cold records. Worse, adding distributed locks to writes consumes machine resources and slows down response times, which goes against why we added a cache in the first place.

Deleting the cache instead

Instead of updating the cache, what if we delete it?

  1. Delete the cache first, then update the database.
  2. Update the database first, then delete the cache.

Again, check what happens when step two fails:

  1. Cache delete succeeds, DB update fails: the next read misses the cache, loads the old value from the DB, and rebuilds the cache. To the user, the edit simply failed.
  2. DB update succeeds, cache delete fails: reads keep returning the stale cached value until it expires and gets rebuilt. To the user, it looks like the edit failed, and then they refresh a bit later and it suddenly works.

Now check concurrency. With Option 1 (delete cache, then update DB) under concurrent read/write:

  1. T1 deletes the cache.
  2. T2 misses the cache, reads the old value x = 1 from the DB, and rebuilds the cache.
  3. T1 updates the DB to x = 2.

Final state: cache has x = 1, DB has x = 2. Out of sync.

Now check Option 2 (update DB, then delete cache) under concurrent read/write:

  1. x is not currently in the cache.
  2. T1 reads x = 1 from the DB.
  3. T2 updates the DB to x = 2.
  4. T2 deletes the cache.
  5. T1 writes x = 1 back into the cache.

Final state: DB has x = 2, cache has x = 1. They are out of sync, though the odds of hitting this are very low because three things all have to happen at once:

  1. The cache entry happened to expire right then (step 1).
  2. A read and a write occur concurrently.
  3. Updating the DB + deleting the cache (steps 3 and 4) finishes faster than reading the DB + rebuilding the cache (steps 2 and 5).

In theory, database writes take longer than reads because writes involve locking, so steps 3 and 4 will almost always take longer than steps 2 and 5. That makes Option 2 consistent in the vast majority of cases.

Making sure both steps succeed

Whether you dual-update or delete the cache, if step two fails, you get inconsistency. Making sure step two eventually succeeds is the real crux of the problem.

The simplest answer is retrying: when step two fails, retry it. Blind synchronous retries come with two obvious issues, though:

  1. Retrying immediately will probably just fail again.
  2. Too many retries tie up application threads.

Any experienced developer reading this is probably already thinking one word: async.

For async retries, you could spin up a dedicated retry thread, though I think a message queue (MQ) is cleaner: put the failed delete into the queue and let a dedicated consumer retry until it succeeds. That solves both issues 1 and 2.

One caveat: bringing in an MQ adds its own failure modes and operational overhead. Whether it’s worth it depends on how strict your consistency requirements really are. There are no silver bullets, only trade-offs.

With an MQ in the mix, the architecture looks like this:

img

Another option is subscribing to the database binlog (for example, using Alibaba’s Canal) and driving cache deletions from there:

img

So far, our playbook is: update the DB first, then delete the cache, backed by an MQ or Canal for retries.

Replication lag and delayed double deletion

In “delete cache first, then update DB,” inconsistency happens because a concurrent reader repopulates the cache with stale data. If the writer runs one more delete after that reader rebuilds the cache, consistency is restored.

And if you run read-write splitting with primary-replica replication lag, even “update DB first, then delete cache” can diverge:

  1. T1 updates the primary DB to x = 2.
  2. T1 deletes the cache.
  3. T2 misses the cache, queries a replica, and gets the stale value x = 1.
  4. T2 writes x = 1 into the cache.
  5. The replica finally catches up with the primary.

Final state: DB is 2, cache is 1. That’s where delayed double deletion comes in.

After the first delete, T1 can sleep briefly and delete the cache key a second time, or publish a delayed message to an MQ so a consumer runs the second delete later.

Two constraints matter here:

  1. The sleep or message delay must be longer than primary-replica replication lag.
  2. It must also be longer than the time T2 takes to query the DB and write back to the cache.

Under high concurrency, estimating that exact window is tough. In practice, teams pick an empirical value, say 1 to 5 seconds, to push the probability of stale data as low as possible.

Strong consistency

If you truly want strong consistency, the textbook tools are consensus and commit protocols like 2PC, 3PC, Paxos, or Raft. They are slow, complex, and bring plenty of fault-tolerance headaches of their own.

Stop and ask the question from the other direction: why did we add a cache in the first place?

Right: performance.

The moment you decide to put a cache in your system, you sign up to deal with consistency. Performance and consistency sit on opposite ends of a scale; you don’t get to max out both.

With every pattern we just walked through, as long as other requests can come in before both the database and cache operations finish, someone can observe an intermediate state.

So if you insist on strict strong consistency, no other request can be allowed through until the entire update finishes.

You can enforce that with a distributed lock, of course, but the cost can easily wipe out all the speed you gained from adding a cache.

Once you choose to use a cache, you have to accept some level of inconsistency and focus on driving its probability down as far as practical.

And don’t forget: cache entries have a TTL. Even when brief inconsistencies slip through, expiration is still there as a fallback, so the data eventually becomes consistent again.

Summary

  1. Introduce a cache to speed up response times.
  2. Once you add a cache, you must address cache-DB consistency, typically via two routes:
    1. Dual updates (update both DB and cache).
    2. Update DB, delete cache.
  3. Dual updates break under concurrency unless you add distributed locks, which eat resources, slow down requests, and contradict why you added a cache.
  4. “Delete cache, then update DB” suffers from read/write races; delayed double deletion mitigates it.
  5. “Update DB, then delete cache” needs both steps to succeed, so use an MQ or binlog subscription for retries.
  6. Under read-write splitting with replication lag, even “update DB, then delete cache” can diverge; delayed double deletion mitigates this too.

Lessons learned

  1. You can’t maximize performance and strong consistency at the same time. For performance, most systems opt for eventual consistency.
  2. Cache-DB consistency centers on three problems: cache utilization, concurrency races, and making sure both the cache and DB steps succeed.
  3. Retrying is the standard way to preserve consistency on failure; synchronous retries hurt throughput, so async retries are the usual choice.
  4. Subscribing to a database’s change log treats the authoritative data source (like MySQL) as the leader replica and turns downstream systems (like Redis or Elasticsearch) into follower replicas, keeping them in sync by replaying the change log.