CodePark/ questions / Caching patterns
START PRACTICINGPRACTICE
Backend question · Redis & caching › Caching patterns

Compare cache-aside, read-through, write-through and write-behind caching.

They differ in who loads data into the cache and when writes reach the database.

Cache-aside: the application reads from the cache first. On a miss (the key is not in the cache), the app loads the data from the database and puts it in the cache itself.

Read-through: the flow is the same, but a cache library or layer loads from the database on a miss. The app only talks to the cache.

Write-through: every write goes to the cache and the database at the same time, and the write waits for both (synchronous). So the cache is always fresh. The downsides: writes are slower, and data that nobody ever reads still gets cached.

Write-behind (also called write-back): writes go to the cache first. The cache sends them to the database later, in the background (asynchronous), often in batches. Writes are very fast and the database gets less load. The downsides:

  • If the cache fails before it sends the writes, those writes are lost.
  • The database is always a little behind the cache.

In practice:

  • Cache-aside with TTLs (a TTL, time to live, is how long a key lives before Redis deletes it) is the default choice.
  • Write-through suits read-heavy data that must stay fresh.
  • Write-behind suits high-volume writes, like counters, where losing a few writes is acceptable.
  • In cache-aside, the app handles misses. In read-through, the cache layer handles them.
  • Write-through writes to the cache and the database together, so the cache is always fresh, but writes are slower.
  • Write-behind sends writes to the database later in the background. It is fast but can lose writes.
  • Cache-aside with a TTL is the common default.
  • Choose the pattern by your read/write ratio and how much data loss you can accept.