Write-Back (Write-Behind) Cache
Master high-speed write performance. Learn how to buffer writes in memory and sync them to the database asynchronously.
π¨ Write-Back (Write-Behind) Cache
Write-back is a caching strategy where data is written only to the cache initially. The write to the permanent database happens only after a specified interval or under certain conditions.
π‘ The Logic (ELI5)
Think of a Busy Bartender:
- You order a round of 10 drinks.
- If the Bartender had to walk to the computer and punch in every single drink before pouring them (Write-Through), the line would never move.
- Write-Back is the Bartender scribbling the orders on a Note Pad (The Cache) and pouring the drinks instantly.
- Only when there is a lull in the line (a "Cool down" period) does the Bartender take the note pad and enter all 10 drinks into the computer (The Database) at once.
- It's incredibly fast for the customer, but if the Bartender loses that note pad, the bar loses the record of those 10 drinks!
π The Deep Dive
How it works
- Application writes data to the Cache.
- Cache acknowledges the write immediately.
- At a later time (based on time or batch size), the Cache syncs the data to the Database.
Pros
- Extreme Write Speed: Best possible write performance because you only wait for RAM, not Disk.
- Write Coalescing: If a value is updated 100 times in 1 second, only the final value needs to be written to the DB.
- Reduced DB Load: Batching writes reduces the pressure on your database.
Cons
- Data Loss Risk: If the cache server (Redis/Memcached) crashes before it syncs to the DB, that data is gone forever.
- Complexity: Much harder to implement correctly, especially ensuring "Eventual Consistency."
π― Interview Pulse
Use Case
Best for Write-Heavy systems where speed is more important than absolute data safety (e.g., Gaming leaderboards, real-time analytics, logging).
When to choose?
Interviewers will ask: "How do you handle 100,000 writes per second on a SQL database?" Answer: Use a Write-Back Cache. Buffer the writes in Redis and use a background worker to batch-insert them into SQL.
Key Risk: Cache Failure
How do you survive a cache crash? Answer: Use Persistent Caches (like Redis AOF) or accept that some data might be lost in exchange for extreme performance. πͺοΈ