Write Policies: Write Back Policy
A write policy decides what happens to the cache and the database when a write request arrives. It is different from a replacement policy, which runs only when the cache has no memory left for a new entry.
In a write back policy the cache is updated and the database is not. Key 1 holds 20. A write sets it to 30 in the cache, and the database still holds 20.
Reads are consistent as long as the cache is alive. If the cache crashes it is rebuilt from the database, and key 1 is 20 again.
Three things write the value back to the database:
- A timeout. The entry has a time to live of 50. A read at 51 finds it stale, removes it and persists it.
- An event. After five updates the value is written.
- A replacement. Key 3 arrives with 70, key 1 is removed from the cache and written to the database.
The database is eventually consistent. Comments on a post and aggregated counts of likes fit this policy.
Write Through Policy
In a write through policy a write removes the key from the cache and updates the database.
Key 1 holds 10 in the cache and in the database. A write sets key 1 to 30. The cache drops its entry for key 1, and the database changes 10 to 30. The database's response changes nothing in the cache.
The next read of key 1 finds no entry in the cache. The cache pulls 1 and 30 from the database and returns it. The two are consistent again.
One case is tricky. A read of key 1 arrives after the cache has dropped the entry and before the database has finished the write.
- The cache has no entry, so it queries the database.
- If the write holds a lock on that row, things are fine.
- If the isolation level is read uncommitted, no lock is taken and the read returns 10.
Write through gives high consistency and high persistence. It is not the most efficient policy. It fits transaction data.
Write Around Policy
In a write around policy a write goes around the cache and updates only the database.
Key 1 holds 30 in the cache and in the database. A write sets key 1 to 50. The request is sent directly to the database, which now holds 50. The cache still holds 30, which is stale. A queue can sit between the request and the database.
A read of key 1 returns 30, and keeps returning 30 until the entry is kicked out of the cache.
The policy has three properties:
- Persistence. Every write reaches the database. Write back can lose data.
- Eventual consistency. The entry is kicked out at 12 o'clock and repopulated at 3 o'clock with 50. A replacement and a load have to happen before the cache is consistent.
- Efficiency. There is no contention on the cache and no ordering of writes in it. The cache only serves reads.
Write through goes through the cache to the database. Write back updates the cache immediately and the database after some time.