public User get(long id) { var cached = cache.get(id); if (cached != null) return cached; var user = repo.findById(id).orElseThrow(); cache.put(id, user); return user;}
2. Implementing Write-Through Cache
Aspect
Detail
Write
To cache and DB synchronously
Read
From cache (always fresh)
Pro
Strong consistency
Con
Write latency higher
3. Implementing Write-Behind Cache
Aspect
Detail
Write
To cache; async to DB
Pro
Low write latency, batching
Con
Data loss risk on crash
Use
Metrics, analytics, non-critical
4. Implementing Cache Invalidation Logic
Strategy
Detail
TTL
Time-based; eventual consistency
Explicit on write
Evict matching keys
Event-driven
Invalidate on domain event
Versioned key
Bump version on data change
Warning: Cache invalidation is one of the two hard problems in CS — design for staleness tolerance.