【Cache System】缓存更新策略 - Write Through

Posted by 西维蜀黍 on 2021-08-05, Last Modified on 2022-12-10

Write Through Pattern

The write-through strategy adds data or updates data in the cache whenever data is written to the database.

Write Through 套路和Read Through相仿,不过是在更新数据时发生。

这里,可以由 composite 存储更新数据库和缓存(注意是先更新DB,再更新cache),也可以由数据库直接更新缓存。

![](assets/2021-08-05 14-02-24.png)

Analysis

Write back caches improve the write performance and are good for write-heavy workloads.

When combined with read-through, it works good for mixed workloads, where the most recently updated and accessed data is always available in cache.

It’s resilient to database failures and can tolerate some database downtime. If batching or coalescing is supported, it can reduce overall writes to the database, which decreases the load and reduces costs.

Some developers use Redis for both cache-aside and write-back to better absorb spikes during peak load. The main disadvantage is that if there’s a cache failure, the data may be permanently lost.

Advanteges

Disadvanteges

Write penalty vs. read penalty

Every write involves two trips:

  1. A write to the database
  2. A write to the cache

Which adds latency to the process. That said, end users are generally more tolerant of latency when updating data than when retrieving data. There is an inherent sense that updates are more work and thus take longer.

Missing data

  • If you spin up a new node, whether due to a node failure or scaling out, there is missing data. This data continues to be missing until it’s added or updated on the database. You can minimize this by implementing lazy loading with write-through.

Cache churn

  • If most of the data is never read, cache will unnecessarily host useless data. This can be controlled by using TTL or expiry.

Write DB or Cache First

答案:先写 DB,再写 Cache

Reference