Video in progress
One service caches another service's data. How do you keep the cache updated and manage the risk of stale data?
A TTL is the simplest, but stale data is visible during the TTL. A more accurate way is invalidation or refresh with change events emitted by the data owner, with the TTL remaining as a backup. How much staleness is acceptable is agreed with the business for each piece of data.
📖 Answer
Really there is one question: "what harm does it do if this data is that old?" If a product description is 10 minutes old, nothing. If a price is 10 minutes old, the customer sees one price and pays another. If permissions (roles) are stale, it's a security problem.
The methods:
TTL only. Simple, no dependency on the owner. But if the TTL is short the cache helps little, and if it's long there is more staleness.
Invalidation through events. catalog emits ProductPriceChanged, and checkout receives it and removes the entry from the cache or refreshes it with the new value.
@KafkaListener(topics = "catalog.product-events")
void on(ProductEvent e) {
cache.asMap().compute(e.productId(), (id, old) ->
old == null || old.version() < e.version() ? e.toSnapshot() : old);
}
The version check is important: if events arrive late or out of order, an old value doesn't overwrite a newer one.
Subtle points:
- If an event is lost or the consumer is down for a long time, the cache stays stale forever. So there is always a TTL as a backup.
- If every instance has a local cache (Caffeine), the event has to reach every instance: in Kafka each instance with its own consumer group, or a broadcast. With a shared Redis cache, one invalidation is enough.
- After a restart the cache is empty, and many requests suddenly go to the owner (a thundering herd). You need request coalescing (a single load per key).
Important decisions are made without the cache. At payment time the final price is confirmed with the owner rather than from the cache, or locked to the version at the moment the price was added to the cart. In other words: a cache for display, the source of truth for decisions.
Metrics: the age of values in the cache and the hit rate. And an occasional check that compares random entries with the owner shows how much staleness there really is in real life.
Sign up to mark studied questions and save your progress.