Video in progress
How do you keep data consistent between a Redis cache and PostgreSQL? How do you close the race conditions in cache-aside?
Usually cache-aside: on a read, if it's not in the cache I fetch from the database and write it to the cache; on a write, I update the database and then delete the cache key (I don't update it). But a parallel read and write can put a stale value back into the cache, so I add a TTL, deletion after commit, and sometimes a version or a delayed second delete.
📖 Answer
The main rule: the source of truth is the database. The system must work correctly even if the cache is wiped at any moment, just slower.
The classic race:
- Reader A doesn't find it in the cache and reads the old value
v1from the database. - Writer B writes
v2to the database and deletes the cache entry. - A writes
v1into the cache. Now the cache is stale until the TTL expires.
Ways to close it:
- Delete after commit. If you delete inside the transaction, before the commit another reader caches the old value again. In Spring:
@TransactionalEventListener(phase = AFTER_COMMIT).
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void evict(ProductChanged e) {
redis.delete("product:" + e.id());
}
- A TTL always. It limits the effect of any bug or race by time. Seconds or minutes, depending on how important the data is.
- A version. You write the value into the cache together with its
version; a write happens only if the version is newer (atomically, with a Lua script). This closes the race completely, but it's complex. - Invalidation through CDC. Debezium reads the change in the database and deletes the cache entry: you don't have to change every write place in the application, and changes made with direct SQL are covered too.
Where I don't cache: values that decisions are made on, like a balance or stock. You can show them from the cache, but the check and the write still happen in the database with a lock.
Sign up to mark studied questions and save your progress.