Common patterns to write to cache includes:
Write-Through#
Data flow: App → Cache → DB (synchronously)
App writes to cache, then immediately writes to DB (both sync)
PROS:
- Keep data consistent between cache and DB
CONS:
- Slow writes, especially when in need of two phase commit
Write-Around (Cache-Aside)#
Data flows:
- On write: App → DB
- On read: App → Cache (if read from cache was unsuccessful, read from DB then write to cache)
App writes directly to DB, bypassing cache. Cache only populated on reads (when data is requested)
Preferable to write-through when most data is not going to be served from cache (most writes are not relevant to most users)
PROS:
- Faster writes (preferable to write through when most
- Database remain source of truth
CONS:
- May cause stale data to be in cache
- Expensive cache misses causing some reads to be slow
Write-Back (Write-Behind)#
Data flow: App → Cache, then Cache contents → DB (asynchronously)
App writes to cache only, returns immediately. Then, background process (possibly in the app) syncs cache to DB later (async)
PROS:
- Fastest write throughput
CONS:
- Reading database may not see writes. If cache fails, writes can be lost.
