Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Several services keep Redis caches of data owned by other services' databases. Evict-after-commit in each writer is not enough, because some writes come from batch jobs, SQL scripts and other services. Design a cache invalidation approach that stays correct with transactions across these sources.

Try it yourself

Cache-aside: one read, three cache states

See what a cache hit saves, what a miss costs, and why a write deletes the cached entry instead of updating it.

Read this example as text

When the entry is in the cache (a hit)

  1. A request arrives. A caller asks the service for product 42. The cache already holds it.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Hit: the value comes back. The entry is there and still fresh, so the cache answers at once. The database is never touched.

1 cache call, 0 database reads.

When it was never cached (a miss)

  1. A request arrives. A caller asks the service for product 42. Nobody has asked for it before, so the cache holds nothing.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. The key was never stored. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When its time to live has run out

  1. A request arrives. A caller asks the service for product 42. The cache held it once, but its time to live ran out 12 seconds ago.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. An expired key is the same as a missing one: Redis no longer returns it, and removes it. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When the price changes afterwards

  1. The price changes. Later, someone updates the price to 25. The service writes the database first: UPDATE products SET price = 25 WHERE id = 42.
  2. Delete the cached entry. Then it deletes the key: DEL product:42. It does not write 25 into the cache. Deleting is simpler and safer: the next read misses and loads whatever the database holds then.
  3. The next read will miss. The cache is empty for this key again, so the next request repeats the miss path and stores 25.

3 cache calls, 1 database read, 1 database write.

What this example leaves out
  • One request at a time. Two requests missing at the same moment (a stampede) are not shown.
  • The write deletes the key. Some systems update the cache instead, which this example does not model.
  • The numbers are counts of round trips, not measured times.

I would drive invalidation from the database's commit log: change data capture, for example Debezium reading the PostgreSQL WAL or the MySQL binlog, publishes every committed row change to Kafka, and a consumer evicts or updates the matching cache entries. That catches every writer, including batch jobs and SQL scripts, and only sees committed data. Services add domain-level events through a transactional outbox, consumers apply only newer versions because events can be delayed or reordered, TTLs stay as a safety net, and CDC lag is monitored against the staleness each cache accepts.

Why this question is asked

Evict-after-commit works well when one service owns both the data and the code that writes it. It stops working when other paths write the same tables: a nightly batch job, a support engineer running a SQL fix, or another service sharing the database. None of them know which Redis keys to clear, so caches drift away from the truth and nobody notices until a customer does. Interviewers ask this design question to see whether we can find a single place every change passes through and build invalidation around it. In this answer, we will see why writer-side eviction is not enough, how change data capture works, how the outbox pattern complements it, how to handle delay and reordering, and what to monitor.

1Why Writer-Side Eviction Is Not Enough

Writer-side eviction means each piece of code that writes the database also evicts the related cache keys after it commits. It relies on every writer knowing about every cache. As soon as there are writers outside our control, such as batch jobs, migration scripts or a service owned by another team, the rule breaks. Adding a new cache in a consuming service would also require changes in every writer, which couples teams in the wrong direction.

What every writer does have in common is the database itself. Every committed change, no matter who made it, ends up in the database's commit log. So the log is the natural place to start.

2How Change Data Capture Works

Databases write every change to a log before applying it, so they can recover after a crash. PostgreSQL calls it the write-ahead log, or WAL; MySQL replicates through the binary log, or binlog. Change data capture, CDC for short, reads that log and turns each committed change into an event. Debezium is a common open source tool for this: it runs as a Kafka Connect connector, reads the WAL through a logical replication slot or the binlog as a replica would, and publishes one event per row change to a Kafka topic per table.

Two properties make this a good base for invalidation. Events are only produced for committed transactions, so a rolled-back write never causes an eviction. And every writer is covered, because the log does not care whether the change came from our service, a batch job or psql.

Step throughInvalidation driven by the commit log
  1. Writersservices, batch jobs, SQL scripts
  2. Database commit logPostgreSQL WAL or MySQL binlog
  3. Debezium connectorreads committed changes
  4. Kafka topicsone per table, keyed by primary key
  5. Cache invalidatorconsumer per cache owner
  6. Redis cachesevict or update the entry

6 layers, from the top down. Step through them one at a time.

3Turning Row Changes Into Cache Actions

Each cache-owning service runs a consumer that maps row changes to the cache keys it uses. A change to the customers row with id 42 might evict customer:42 and also customer-summary:42. The simplest safe action is to evict; updating the entry with the new row is possible when the cached value is exactly that row, but it requires the ordering rules we will see below.

Java
@KafkaListener(topics = "crm.public.customers")
void onChange(ChangeEvent e) {
long id = e.key().id();
long version = e.after() != null ? e.after().version() : e.source().lsn();
// evict every key derived from this row
redis.delete(List.of("customer:" + id, "customer-summary:" + id));
metrics.lag(Duration.between(e.source().commitTime(), Instant.now())); // how stale were we?
}

Notice that the consumer belongs to the team that owns the cache, not the team that owns the table. That keeps the coupling pointing the right way: writers do not need to know who caches their data.

4Adding the Transactional Outbox for Domain Events

Row changes are low-level. Sometimes a cache depends on a business event that spans several tables, such as order placed, and translating raw rows into that meaning in every consumer is error-prone. For changes made by services, the transactional outbox pattern helps. The service writes its business change and an event row into an outbox table in the same transaction, so either both are committed or neither is. CDC then reads the outbox table and publishes the event. Consumers that understand the domain event can evict exactly what it affects.

So we use both: CDC on the tables catches every writer, including scripts and batches, and the outbox gives clear domain events from the services that support it.

5Handling Delay and Reordering

CDC is asynchronous. There is a lag, usually milliseconds to a few seconds, between the commit and the eviction, and during an incident it can grow to minutes. Events for one row stay in order within a Kafka partition when keyed by the primary key, but consumers can restart and replay, and different sources, such as a CDC event and an outbox event, can arrive in any order.

So every cached value carries a version, such as a version column or the log position of the change, and the consumer only replaces an entry with a newer version. With pure eviction, ordering matters less, but a slow reader can still load an old row just before the eviction and put it back afterwards, so readers should also write with a version check or a short TTL. TTLs remain the last safety net: if the pipeline stops entirely, entries still expire.

Step throughApplying one change event
  1. Event read from Kafkarow key, new version, commit time
  2. Cached version older?
    YesEvict or replace the entryNoIgnore the event: a newer value is cached
  3. Record lagcommit time to now
  4. Lag above the cache's bound?
    YesAlert, rely on TTLNoNormal

4 steps in order. Play them, or step through them one at a time.

6Defining Staleness and Monitoring the Pipeline

For each cache we write down the staleness it can accept, for example 5 seconds for prices and 10 minutes for product descriptions. The CDC pipeline is then part of the system's correctness, so we monitor its lag end to end: the age of the newest event processed by each consumer, the replication slot's retained WAL in PostgreSQL (a stuck slot keeps WAL on disk and can fill it), and connector health. When lag exceeds a cache's bound, an alert fires, and for very sensitive caches we can shorten the TTL automatically or bypass the cache until the pipeline recovers.

7Follow-up questions

What is the delayed double delete pattern and why is it weaker than CDC?

The writer deletes the cache key, updates the database, waits a fixed time such as 500 ms, and deletes the key again, hoping to remove any old value a concurrent reader put back in between. It is a guess about timing: if the reader is slower than the delay, the old value survives. It also only works for writers that implement it, so batch jobs and scripts are still missed. CDC evicts after the commit is in the log, for every writer, and can use versions instead of timing guesses.

What happens if the CDC connector is down for an hour?

Events wait in the database log and are published when it recovers, so no change is lost, but caches can be stale for that hour unless TTLs are shorter. We alert on connector health and lag, and for PostgreSQL we watch the replication slot so the retained WAL does not fill the disk.

Should the consumer update the cache or only evict?

Evicting is simpler and safer, because the next reader loads the current row. Updating saves a database read, but it needs versioned writes so a late event cannot overwrite a newer value. I would start with eviction and update only hot entries where the extra load matters.

8Conclusion

In this answer, we saw that writer-side eviction fails when batch jobs, scripts and other services write the same data, so we drive invalidation from the commit log with change data capture, which sees only committed changes from every writer. The outbox pattern adds domain-level events in the same transaction as the data, versions protect against delayed and reordered events, TTLs remain the safety net, and we monitor CDC lag against the staleness each cache can accept.

What to say in the interviewAbout 80 seconds aloud

Open with

Since not every writer can evict, I would stop relying on writers and use the one thing every change passes through, the database commit log. With change data capture, for example Debezium reading the PostgreSQL WAL through a replication slot or the MySQL binlog, every committed row change becomes a Kafka event keyed by primary key.

Then, if they want more

Each team that owns a cache runs a consumer that maps the row to its cache keys and evicts them. That covers services, batch jobs and SQL scripts alike, and it never reacts to rolled-back writes.

For changes made by services I would add a transactional outbox, writing a domain event in the same transaction as the data, so consumers get clear business events where raw rows are hard to interpret.

CDC is asynchronous, so I would expect delay and occasional reordering or replay: cached values carry a version and consumers only apply newer ones, and TTLs remain as the safety net if the pipeline stops. Finally, I would agree a staleness bound per cache and monitor end-to-end lag, connector health and the replication slot, alerting when lag passes the bound.

I would also mention that delayed double delete is weaker, because it guesses timing and only covers writers that implement it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Several services keep Redis caches of data owned by other services' databases....": https://scrivio-interview-library.netlify.app/databases/caching/a65d4b9e68/