Scrivio Interview library
DebuggingIntermediate7 min read · updated 13 November 2026

Cache invalidation runs on change data capture: a connector streams row changes from PostgreSQL into Kafka and an invalidator service deletes the matching Redis keys. A nightly batch updated 3 million rows, consumer lag reached 1.8 million messages, and for 25 minutes users saw stale data.

Why does a bulk update hurt this design so much, and what do you change in the invalidator and in how bulk changes are handled?

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.

A bulk update turns into millions of change messages that sit in the same ordered partitions as the urgent single-row changes, so a price change made a minute after the batch waits behind 3 million deletes. We make the invalidator faster with more partitions and consumers, coalescing within each batch, pipelined or multi-key UNLINK, and skipping changes no cache depends on, and we handle bulk jobs differently: they bump a version for the affected group or go to a separate, lower-priority topic. We alert on invalidation lag in seconds and keep TTLs as the final bound.

Why this question is asked

Change data capture, reading the database's own change log and turning each row change into a message, is a popular way to drive cache invalidation because no application code can forget to invalidate. But it ties cache freshness to a queue, and queues behave badly when one producer floods them. Interviewers ask this to see whether we can reason about ordering and throughput, not just name a tool. In this answer, we will recap the pipeline, explain why the bulk update hurt so much, speed up the invalidator, change how bulk jobs are handled, and measure the lag that users actually feel.

1A Quick Recap of the Pipeline

A CDC connector, typically Debezium, reads PostgreSQL's write-ahead log through a logical replication slot and publishes one message per changed row to a Kafka topic, usually one topic per table, partitioned by the row's primary key. Each message carries the row before and after the change and the commit timestamp. The invalidator service consumes these topics and, for each message, deletes the Redis keys that cache that row.

The design has a real strength: every committed change produces a message, including changes from scripts and other services, and nothing has to remember to invalidate. Its weakness is that freshness now depends on how quickly the invalidator works through the queue.

Step throughInvalidation through change data capture
  1. PostgreSQLCommits rows; the WAL records every change
  2. Debezium connectorReads the WAL, one message per changed row
  3. Kafka topicPartitioned by primary key, strictly ordered per partition
  4. InvalidatorConsumes messages, maps rows to cache keys
  5. RedisKeys deleted; next read reloads fresh data

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

2Why the Bulk Update Hurt So Much

The nightly batch updated 3 million rows, so the connector published 3 million messages in a few minutes. Kafka keeps order within a partition, and the invalidator processes each partition in order. Any change a user made after the batch, such as a price fix on a single product, was appended behind the batch's messages in the same partition and could only be processed once everything ahead of it was done.

Now the numbers. If the invalidator deletes one key per message with one Redis round trip of about half a millisecond, a consumer handles about 2,000 messages per second. 3 million messages at 2,000 per second is 1,500 seconds, which is the 25 minutes users saw. Lag of 1.8 million messages simply means 15 minutes of work queued in front of any new change. The cache was not wrong because invalidation failed; it was wrong because invalidation was late, and the lateness came from a batch that probably did not even need precise invalidation.

3Making the Invalidator Faster

Three changes multiply the throughput. First, parallelism: a consumer group can only use as many consumers as the topic has partitions, so a topic with 6 partitions caps us at 6 consumers. Moving to 24 or 48 partitions, with matching consumers, raises the ceiling directly. Second, stop paying one round trip per message: poll a few hundred records, collect their keys, and send the deletes together. Third, coalesce: a batch often updates the same row several times, and within one poll we need only one delete per key.

Java
while (running) {
ConsumerRecords<String, RowChange> records = consumer.poll(Duration.ofMillis(200)); // up to 500
Set<String> keys = new LinkedHashSet<>(); // coalesce: one delete per key
for (var r : records) {
RowChange c = r.value();
if (!cachedColumnsChanged(c)) continue; // skip changes no cache reads
keys.addAll(keyMapper.keysFor(c)); // e.g. product:5001, page:12:5001
}
redis.executePipelined((RedisCallback<Object>) conn -> {
keys.forEach(k -> conn.keyCommands().unlink(k.getBytes(UTF_8)));
return null;
}); // 500 messages -> 1 round trip
consumer.commitSync(); // commit only after the deletes
}

Notice two details. The filter skips messages for tables or columns no cache depends on; a batch that recalculates an internal score column produces 3 million messages that need no invalidation at all, and the before and after images in the message tell us which columns changed. And the offsets are committed only after the deletes, so a crash replays a batch rather than skipping it, which is safe because deleting a key twice is harmless. With these changes a consumer handles tens of thousands of messages per second instead of 2,000. In Redis Cluster, a multi-key UNLINK only works for keys in the same hash slot, which is why the example pipelines single-key commands.

4Handling Bulk Changes Differently

Faster consumers shrink the problem, but the real fix is to stop treating a bulk job like 3 million individual edits. One option is a version bump: if the batch changes a whole group, such as all prices in a region, it increments a namespace version for that group when it finishes, which invalidates everything in the group with one command, and the invalidator ignores the batch's row messages.

The other option is to separate the traffic. The batch job identifies itself, for example by writing a marker into a small audit table in each of its transactions or by using its own database role, and the connector routes its changes to a separate topic, with a routing transform or a second connector (check what your Debezium version supports). The invalidator consumes the batch topic with lower priority, so interactive changes on the main topic are never queued behind it. Either way, urgent single-row changes keep their latency of a second or less.

5Measuring the Lag Users Feel

Consumer lag in messages is a poor alert, because 1.8 million cheap messages and 1,000 slow ones mean very different delays. What users feel is time: how long after a commit the cache key is deleted. Each message carries the source commit timestamp, so the invalidator can record now minus that timestamp for every delete, and we alert on its 99th percentile, for example above 30 seconds.

Finally, invalidation lag is the extra staleness on top of whatever else the cache allows, and the TTL is what limits it when everything else fails. A one-hour TTL means a stuck invalidator can cause an hour of stale data; if that is unacceptable for some data, its TTL should be shorter.

6Follow-up questions

How would you measure invalidation lag end to end?

Two ways together. Inside the pipeline, record the time from the source commit timestamp in each message to the moment its delete succeeded, as a histogram. From the outside, run a probe: every 10 seconds it updates a dedicated heartbeat row, reads the corresponding cache key until it disappears or changes, and reports the delay. The probe catches problems the internal metric misses, such as a connector that stopped publishing at all.

Why not just flush the whole cache after the nightly batch?

Because emptying the cache is an avalanche: every request misses at once and the database receives the full read load in the busiest seconds. A group version bump gives the same freshness for the affected data while leaving the rest of the cache warm.

Does more partitions change ordering guarantees?

Ordering is per key as long as the partition key is the row's primary key, so all changes of one row still arrive in order. Increasing partitions remaps keys to new partitions, so it is best done when the topic is drained or with the understanding that in-flight changes of a key may briefly be processed out of order, which for deletes is harmless.

7Conclusion

In this answer, we saw that CDC invalidation puts every change in an ordered queue, so a bulk update of 3 million rows delays every later change by the time it takes to process them, about 25 minutes at 2,000 deletes per second. We speed up the invalidator with more partitions and consumers, coalesced and pipelined deletes and skipping irrelevant columns, handle bulk jobs with a group version bump or a separate low-priority topic, alert on lag measured in seconds from the commit, and keep TTLs as the final bound on staleness.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is that invalidation sits in a queue. The connector turns every row change into a Kafka message, and partitions are processed in order, so a single urgent change made after the batch waits behind its 3 million messages.

Then, if they want more

If the invalidator deletes one key per message with one round trip, it does about 2,000 a second, and 3 million messages take 25 minutes, which is exactly the staleness users saw. I would fix it in two places.

In the invalidator: more partitions and consumers, because parallelism is capped by the partition count; poll a few hundred records, coalesce them into one delete per key, and send the UNLINKs in one pipelined round trip; skip tables and columns no cache depends on; and commit offsets only after the deletes.

That takes it from thousands to tens of thousands per second. For bulk jobs: they should not use per-row invalidation at all. The batch can bump a namespace version for the group it changed, or its changes can be routed to a separate topic consumed at lower priority, so interactive changes never wait behind it.

Then I would alert on lag in seconds, commit time to delete time, not in messages, and keep TTLs as the last bound.

About this answer

Last updated
13 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 official documentation for the version you use. 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 "Why does a bulk update hurt this design so much, and what do you change in the...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/dafcce7ad3/