Implementation
Implement cache invalidation strategies to maintain consistency between cache and database. When data changes, cached copies must be updated or removed.
Three main strategies:
- Write-Through: Update cache and DB synchronously
- Write-Behind: Update cache, async update DB
- Cache-Aside with Invalidation: Delete cache, update DB
Also handle cache stampede: when many requests hit an expired key simultaneously.
Sample Test Cases
{
"src": "c0",
"dest": "n1",
"body": {
"type": "init",
"msg_id": 1,
"node_id": "n1",
"node_ids": [
"n1"
]
}
}{"src":"n1","dest":"c0","body":{"type":"init_ok","in_reply_to":1,"msg_id":0}}Hints
Hint 1▾
Hint 2▾
Hint 3▾
Theoretical Hub
Cache Invalidation
"There are only two hard things in Computer Science: cache invalidation and naming things." - Phil Karlton. Keeping cache consistent with the source of truth is notoriously difficult.
Write-Through
Every write goes to both cache and database synchronously. Simple to reason about but adds latency to writes. Cache is always consistent but writes are slow.
Write-Behind (Write-Back)
Writes go to cache immediately, then asynchronously to database. Fast writes but risk of data loss if cache fails before flush. Requires careful durability handling.
Cache Stampede
When a popular key expires, many requests simultaneously miss and hit the database. Solutions include: locking (only one fetches), early expiration (refresh before actual expiry), or probabilistic early expiration.