← Building blocks

Keep cache and store in sync on write

Latency & performancesenior

Cache-aside leaves a window where the cache is stale after an update.

Say it like this

The counters are written far more often than they are read, so I use write-behind: the cache absorbs the increments and a flusher batches them to the database every second, accepting that a cache crash loses at most one second of counts.

Basic solution

Write-through updates cache and DB in the same request; write-behind updates the cache and flushes to the DB asynchronously.

RedisHazelcastCaffeine

Write-through versus write-behind

Write-through updates both stores before acking. Write-behind acks after the cache write and lets a flusher batch dirty entries to the database later.

How it works

  1. Write-through: the service writes the new value to the cache and to the database in the same request, and only acknowledges the caller once both writes have succeeded. At no moment does the cache hold a value that the database does not.
  2. Write-behind: the service writes the new value only to the cache and acknowledges immediately. The cache marks that entry dirty, meaning the database has not seen this value yet.
  3. A separate flusher process drains the dirty entries to the database either on a timer (every N milliseconds) or when the number of dirty entries reaches a limit. If the same key was updated many times since the last flush, the flusher sends one write carrying the combined result (for a counter, the summed delta) instead of one write per update.
  4. Reads go to the cache first in both modes. With write-through, a miss can fall back to the database because it is always current. With write-behind, a miss must not fall back, because the database may be behind by one flush interval and would return an older value.
  5. If a cache node dies, write-through loses nothing because every value was also written to the database. Write-behind loses every dirty entry that had not been flushed, unless the cache is replicated or each write was also appended to a durable journal.

What the two policies trade

  • Write-through pays write latency (two round trips instead of one) to guarantee that cache and database always agree.
  • Write-behind accepts a durability risk (the unflushed window) to turn N small writes into one batched write.

Worked example

Click counters on the URL shortener

  • 4,000 redirects per second; each click increments click_count for one alias. Writing each to Postgres is 4,000 UPDATE statements per second on hot rows, with row-lock contention on a viral link.
  • Write-behind: INCR alias in Redis (about 0.2 ms), ack the redirect. A flusher runs every 1 s and issues one UPDATE per dirty alias with the summed delta. With 20 percent of links hot, that is about 800 distinct aliases per second, so 800 updates per second instead of 4,000, each carrying 5 increments on average. A viral link taking 1,000 clicks per second becomes one UPDATE of +1,000.
  • Loss budget: a Redis crash loses at most 1 s of dirty counters, about 4,000 clicks. For analytics that is acceptable; for a wallet balance it is not.
  • Write-through instead for the link mapping itself: creating a link writes the alias to Postgres and to Redis in one request, adding roughly 1 ms to a 40-per-second write path, so a redirect immediately after creation always hits.

Variants and when each wins

Write-through

  • Cache and database are updated synchronously inside the request. It wins when a read right after a write must hit and agree with the database; the cost is write latency and cache memory spent on keys nobody reads.

Write-behind with a flush interval

  • The cache absorbs writes and a flusher batches them to the database on a timer. It wins for counters and other keys updated many times a second, and it loses the unflushed window if the cache fails.

Write-behind with a journal

  • Each write is also appended to a durable log (Kafka, the Redis append-only file) before acknowledging, so a crashed flusher can be replayed from the log. It keeps the batching benefit with near-zero loss, at the cost of one more write per update.

Write-around

  • Writes go to the database only and delete the cache entry; the next read loads the fresh value. It is cache-aside applied to writes, and it wins for data that is written once and read much later.

Recommendation: write-through for small, must-agree data such as mappings and settings; write-behind with a journal for counters and metrics; write-around for everything else.

Failure modes

Lost writes after a cache crash

  • You notice counters drop back to older values after a cache restart. It happens because the dirty entries were only in cache memory and were never flushed before the crash. Fix it by replicating the cache, journaling each write to a durable log, or shortening the flush interval to the amount of loss you can tolerate.

Flusher falls behind

  • You notice the dirty set keeps growing and the database receives writes in large bursts. It happens because the flush rate is lower than the write rate, or the database is slow to accept the flushes. Fix it by bounding the dirty set, flushing when it reaches a size as well as on the timer, and applying backpressure to writers when the bound is hit.

Read of a value that only exists in the cache

  • You notice a report built from the database disagrees with what the API shows. It happens because with write-behind the database is always one flush interval behind the cache. Fix it by documenting that lag for report consumers, and by serving user-facing counters from the cache rather than the database.

Write-through doubles write latency

  • You notice p99 on the write path rises after the cache is added. It happens because the request now waits on two synchronous round trips, and the cache write sits on the critical path. Fix it by writing the database first and the cache second, and by treating a failed cache write as a delete so the next read simply reloads.

Coalescing hides ordering

  • You notice a set-then-increment sequence produces a wrong value. It happens because the flusher merged a SET and an INCR on the same key into one write without respecting their order. Fix it by allowing only one operation type per key, or by flushing full values rather than deltas.

Interviewer follow-ups

Answer out loud before you open each one.

When would you refuse to use write-behind?

Whenever losing the unflushed window is unacceptable: balances, inventory, anything legally or financially binding. For those I use write-through or the database directly, and reserve write-behind for counters, metrics and last-seen timestamps.

How do you size the flush interval?

From the loss you can tolerate and the write reduction you need. A 1 s interval on 4,000 writes per second across 800 hot keys cuts database writes 5x and bounds loss to one second. Shorter intervals reduce both the benefit and the risk; measure dirty-set size and database write latency and tune from there.

How does write-through interact with a cache miss?

A miss is still possible because entries expire or are evicted. The service falls back to the database and repopulates the cache exactly as in cache-aside. Write-through only guarantees that whatever is in the cache is current, not that everything is in the cache.

Can write-behind and read replicas coexist?

Yes, but the lag compounds: a replica is behind the primary and the primary is behind the cache. Reads that need the latest value must come from the cache; reads that tolerate staleness can use replicas. Say which reads go where.

Connections

Pairs with
Cache the hot reads · Invalidate the cache when data changes · Batch small operations · Slow the producer when the consumer is behind
Pulls against
Let users see their own writes
Used in
Distributed Key-Value Cache (Redis / Memcached-like)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingService, FlusherCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon ElastiCacheCache (write-through), Cache (write-behind)MemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon AuroraDatabaseAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB