Fast strategyIt determines whether a system can handle increased traffic or whether the entire database will be overwhelmed. It's not as simple as "installing Redis," but a series of trade-offs: where to store data, who is responsible for writing, when data expires, what to discard when it's full, and what to do when a hotspot key expires.
This article breaks down caching strategies into six aspects that can be decided one by one, from read/write patterns, invalidation mechanisms, and eviction algorithms, to the three most common online incidents: cache avalanche, cache penetration, and cache breakdown, and how consistency can be achieved between "new enough" and "fast enough".
This is the 13th article in the system design series. Previous articles discussed... DNSLoad balancing and CDN each have their own caching layer. This article brings together the concepts scattered across these layers into a caching strategy decision-making process that can be directly applied.

Table of Contents
- What is a caching strategy? Let's start with a one-sentence conclusion.
- Where should the cache be placed: Six levels and latency levels
- Four core caching strategies: Cache-Aside, Read-Through, Write-Through, and Write-Behind
- The fifth type, Write-Around, and a comparison table of cache strategy trade-offs.
- Cache expiration: TTL, active expiration, and versioning keys
- Replacement Algorithms: From LRU, LFU to W-TinyLFU
- Three major disasters: Fast Avalanche, Fast Penetration, Fast Breakdown
- Consistency: Deleting the cache first or last will result in an error.
- Practical figures: Hit rate, capacity planning and monitoring metrics
- Decision Tree for Selecting a Fast-Track Strategy: Five Questions to Determine a Solution
- Frequently Asked Questions (FAQ)
What is a caching strategy? Let's start with a one-sentence conclusion.
A caching strategy refers to the specific rules governing three things: when data enters the cache, when it leaves the cache, and who is responsible for moving it. If these three things are not clearly defined, a caching strategy can turn from an accelerator into a disaster amplifier.
Many teams only do half the job when they first implement caching: they casually write data to Redis when reading, but forget to handle writes when writing. As a result, users can modify data, but the page remains unchanged for thirty minutes. This isn't a problem with Redis; it's that the caching strategy hasn't defined a write path.
From another perspective, the essence of caching is "using a potentially expired copy to save time from having to recalculate." Since it's a copy, there will inevitably be a gap between the old and new versions; given this gap, we must clearly answer one question: how long can this data be outdated?
The answer to this question will directly determine all subsequent caching strategy choices. Inventory can be left unused for three seconds, account balances for even a second, and blog posts left unused for an hour without anyone noticing. Write down your tolerance levels first, then discuss the technical selection of caching strategies.
Where should the cache be placed: Six levels and latency levels
A request, originating from a user's browser, will pass through at least six interceptor points before actually reaching the database disk. Each additional layer increases the cost by approximately an order of magnitude.
The first layer is the browser cache..Depend on Cache-Control、ETag When working with Service Workers, latency is close to zero upon hit, and it consumes absolutely no server resources. This is the cheapest layer in the entire caching strategy, yet it is most often overlooked.
The second layer is the CDN edge node.Static resources and publicly cacheable API responses are placed here, allowing users to retrieve them locally with a latency of approximately 10 to 30 milliseconds, and the traffic never even reaches your data center.
The third layer is a reverse proxy.For example, Varnish or Nginx's proxy_cache. It stands in front of the application server, sending out the entire page or response directly without even waking up the PHP or Node process.
The fourth layer is the application layer cache.This refers to Redis and Memcached, which are the most familiar to everyone. This layer is the most flexible and can store query results, sessions, counters, leaderboards, and most discussions on caching strategies are concentrated here.
The fifth layer is the database's own buffer pool.MySQL's InnoDB keeps hot pages in memory, which you almost never need to worry about, but remember that it's also competing for the same memory space when planning capacity.
The sixth layer is the actual disk and the original query.Once a request reaches this point, the latency is typically tens to hundreds of times greater than the previous layers. The entire purpose of a caching strategy is to minimize the time a request can reach the sixth layer.
The most common caching strategy mistake in practice is "only doing the fourth layer". Even if it is a site-wide image or a ranking list that is only updated once a day, every request will send it to Redis to rebuild the HTML, which wastes the cost that could be saved by the first three layers.

Four core caching strategies: Cache-Aside, Read-Through, Write-Through, and Write-Behind
When it comes to caching strategies, the read/write models actually used in the industry are the following four. The difference between these four caching strategies is not in the performance figures, but in who is responsible for moving data in and out of the cache.

Cache-Aside (also known as Lazy Loading)
This is the starting point for 90% of teams implementing a caching strategy. When reading, the application first checks the cache; if it finds a match, it retrieves the data directly; otherwise, it retrieves it from the database and writes it back to the cache. When writing, the database is updated, and then the corresponding cache key is deleted.
Its biggest advantage is fault tolerance: even if the entire cache fails, the application can still read the database, just at a slower pace. AWS's...Official caching strategy documentThis mode is called lazy loading, and it is explicitly stated that it "only caches data that has actually been read" and does not waste memory.
The cost is threefold: the first read of each piece of data will inevitably miss; the synchronization logic between the cache and the database is scattered across each calling end; and there will be a concentrated backhaul during a cold start (e.g., right after Redis is restarted).
Read-Through
Applications only interact with the cache and never directly access the database. When a cache miss occurs, the cache component loads and populates the data from the backend itself, completely transparent to the application.
The advantage is that the client-side code is very clean, with only one copy of the loading logic. The disadvantage is that you are tied to a library or service that supports this pattern, and if the backend crashes, the cache layer's error handling becomes a single point of failure.
Write-Through
Each write operation updates both the cache and the database simultaneously, and a response is only provided after the entire process is complete. The data in the cache is always up-to-date, and the reading end almost never receives outdated values.
The cost is straightforward: write latency becomes the sum of both systems. Furthermore, it writes a lot of "cold data" that "no one will read after writing," wasting memory. In practice, TTL is usually used to allow unread cold data to disappear on its own.
The Write-Through caching strategy is truly suitable for scenarios where "there is little writing and much reading, and the reader cannot tolerate old values at all," such as product pricing or permission settings.
Write-Behind (also known as Write-Back)
Write to the cache first to immediately respond to the user, and then use background batches to asynchronously apply the changes to the database. This minimizes write latency and allows multiple updates to be merged into a single database write.
The risk is also the highest: if the caching node crashes before being written to the database, the writes made during that period are truly lost. Therefore, it is only suitable for data where a small amount of loss is acceptable, such as view counts, likes, and behavioral tracking.
A common misuse is using write-behind to process orders or payments. If a node restarts even once, you'll receive alerts about reconciliation discrepancies. For this type of data, please use the database directly; do not apply this caching strategy.
The fifth type, Write-Around, and a comparison table of cache strategy trade-offs.
There is another often overlooked way of writing it called... Write-AroundWhen writing, only the database is written, completely bypassing the cache. When someone actually comes to read it, Cache-Aside loads it in.
It specifically addresses the "cold data pollution" problem of Write-Through. If your system writes a lot, but most of what is written is not read immediately (such as logs or historical orders), Write-Around will allow the cache to retain only the truly hot data.
Comparing the five quick-access strategies side-by-side makes the choices much clearer:
| Strategy | Read delay | Write delay | Data freshness | Risk of data loss | Typical scenarios |
|---|---|---|---|---|---|
| Cache-Aside | Low (after hit) | 低 | 中 | 無 | General purpose preferred, read-heavy and write-light |
| Read-Through | Low (after hit) | 低 | 中 | 無 | Want to unify loading logic |
| Write Through | 低 | 高 | 高 | 無 | Pricing, permissions, configuration files |
| Write-Behind | 低 | lowest | 高 | 有 | Counters, event tracking, leaderboards |
| Write-Around | 中 | 低 | 中 | 無 | Write more, read less, historical materials |
In practice, these five methods are not mutually exclusive. Within the same system, it's perfectly normal for product details to use Cache-Aside, prices to use Write-Through, and pageviews to use Write-Behind. Cache strategies are determined by the type of data, not by the project.
Cache expiration: TTL, active expiration, and versioning keys
There's an old saying in computer science: there are only two hard things, naming and cache invalidation. The difficulty lies in the fact that the invalidation mechanism in a caching strategy must simultaneously satisfy two conflicting requirements—timely enough, but not too frequent enough.
The first type is TTL passive expiration.Each key has a timeout period, and it automatically disappears when the timeout expires. This is the simplest to implement and naturally has a fallback effect: even if your failure logic is written incorrectly, the data will only be out of range for the TTL at most.
There's a practical rule for choosing TTL: first ask "How long will it take for users to discover and complain about this data error?", and take one-third of that time. Don't just set it to 3600 seconds indiscriminately; that's just not a consideration.
The second type is active failure.When updating data, explicitly delete or overwrite the relevant keys. This provides the best timeliness, but the problem is that there is often more than one "relevant key"—changing a product name may simultaneously disable three caches: product details, category list, and search results.
The solution is to write down the dependencies during the design phase, or to use cache tagging, so that a single failure can clear an entire set of keys.
The third type is versioning keys.This technique is particularly useful in large systems. Include a version number or timestamp in the key name, for example... product:v7:1024When a key becomes invalid, instead of deleting it, increment the version number by one.
The advantage is that invalidation operations become O(1), eliminating the need to scan or maintain the dependency graph; old keys, if not read, will be naturally cleared by TTL or eviction algorithms. The cost is that memory will occupy an extra memory block in the short term.
These three mechanisms are usually used in combination in mature caching strategies: versioning keys handle structural changes, proactive invalidation handles single updates, and TTL is always on as a last resort.
Replacement Algorithms: From LRU, LFU to W-TinyLFU
Memory will eventually fill up. In a caching strategy, which memory to discard after it's full directly determines the upper limit of the hit rate. This is also the part of the caching strategy that is most easily skipped, yet has the greatest impact on the numbers.
LRU (Least Recently Used)The LRU key is evicted from the cache. It assumes that "things just read will be read again soon," which is time-bound. Most network applications operate on this principle, so using LRU as the default cache strategy is reasonable.
The weakness of LRU is its vulnerability to scans: a full table traversal or batch export can fill the cache with a bunch of cold data that is only read once, squeezing out the real hot data. This phenomenon is called cache pollution.
LFU (least commonly used)Instead, look at the number of accesses and eliminate the key with the fewest total accesses. It is very accurate for long-term stable hot topics, but it has two old problems: newly added keys naturally have low access counts and are easily eliminated; while keys that were popular in the early days but were later ignored will stick around based on their historical access counts.
Redis's LFU (Low Validation) uses real-time count decay to mitigate the latter.lfu-decay-time Control the rate at which the count decreases over time.lfu-log-factor Then the logarithmic curve controls the growth of the count.
FIFO (First In First Out)Looking only at the entry order, this method is the cheapest to implement, but usually has the worst hit rate. Unless your access pattern truly has no regional limitations, it's not recommended.
TTL phased outPrioritize discarding keys that are about to expire.Random Then randomly pick one and discard it. The latter sounds crude, but in scenarios with a very uniform distribution, it saves the cost of maintaining the elimination chain, and the overall throughput is actually better.
W-TinyLFU This is currently recognized as the best compromise: using a small count-min sketch to record access frequencies, and adding an admission window to give new keys a chance to prove themselves. Java's Caffeine library uses this as its default.
Back to Redis. maxmemory-policy There are currently ten settings, divided into... allkeys- 與 volatile- There are two groups; the latter only eliminates keys with set expiration times. A complete list and tuning parameters can be found directly.Redis official Key eviction file.
Here's a common pitfall:volatile- The series behaves identically without any set expiration date. noevictionIn other words, when the memory is full, writing to it is directly refused. Many online incidents occur in this way.
Another noteworthy new change: Redis 8.6 and later versions include... allkeys-lrm 與 volatile-lrm Two strategies. Most teaching materials in the Chinese-speaking world still rely on the old list of eight policies; remember to check the version when researching.

Three major disasters: Fast Avalanche, Fast Penetration, Fast Breakdown
These three terms look very similar, but their causes are completely different, and their solutions cannot be interchanged. Distinguishing between them is the watershed moment for a fast-track strategy, moving from simply "knowing how to use it" to "being able to handle online traffic."

Cache Avalanche: A large number of keys expire simultaneously
You used the same script to warm up 100,000 keys at 2 AM, setting the TTL to one hour. Then at 3 AM sharp, all 100,000 keys disappeared simultaneously, and 100,000 requests were simultaneously sent to the database.
Another type of avalanche occurs when the entire cache cluster goes down, causing all traffic to instantly return to the origin. The common feature of these two types is that they involve "large amounts" rather than "single points".
The caching strategy for avalanche has four layers: TTL plus random jitter (e.g., adding 0 to 300 seconds to the base value) to allow expiration times to spread out naturally; using different TTL intervals for hot and cold data; adding circuit breakers and degradation to the database side; and making the cache itself a master-slave or clustered cache.
Cache penetration: Querying data that does not exist.
Someone is spamming your API with a non-existent product ID. The cache will always miss because the database doesn't contain this item, so every request goes directly through the cache to the database.
This is particularly dangerous under malicious traffic, because attackers can bypass all your caches simply by generating random IDs.
There are three solutions for the caching strategy of penetration: First, cache "no such record" as well, but the TTL should be short (usually 30 to 60 seconds) to avoid not being able to read the data after it is actually added; second, use a Bloom filter to block keys that definitely do not exist before caching; third, perform parameter validity checks at the API layer and directly reject IDs that do not meet the requirements.
Cache breakdown: Single hotspot key expires
The leaderboard button on the homepage, which was read 50,000 times per second, expired right at the peak. In the few hundred milliseconds before it was rebuilt, all 50,000 requests flooded the database.
Note the difference between this and an avalanche: an avalanche causes many keys to expire simultaneously, while a breakdown causes a single, overheated key to expire. Therefore, "TTL with debounce" is useless for breakdown.
There are three solutions: use a mutex lock to allow only one request to rebuild while other requests wait or return the old value; use logical expiration, which means that the key itself does not have a TTL, but stores an expiration timestamp in the value, and after expiration, it is updated asynchronously in the background while the foreground continues to return the old value; or simply make the most frequently used keys never expire, and have them actively refreshed by a scheduled task.
Consistency: Deleting the cache first or last will result in an error.
As long as the cache and the database are two separate systems, there can be no free strong consistency. The most common interview question, "Should you update the database first or delete the cache first?", has the correct answer: both can lead to errors; the difference lies only in the probability of error.
Delete the cache first, then update the database.The risk is that after deleting the cache but before the database is fully written, another read request comes in, finds a miss, reads the old value from the database, and then writes this old value back to the cache. As a result, the cache contains dirty data that will never correct itself.
Update the database first, then delete the cache.Risk: The database update succeeds, but the step of deleting the cache fails (due to network jitter or Redis timeout), and the cache retains the old value. This risk is relatively small and easier to recover from, so this is the industry standard.
There are several ways to remedy this.Delayed double deleteThis is the most common, rudimentary method: after updating the database, delete the cache once, wait a few hundred milliseconds, and then delete it a second time to clear out the old values that were refilled during the idle period.
A more stable approach isChange log of the subscription repositoryFor example, you can use Canal or Debezium to read MySQL's binlog, with a separate consumer responsible for the failure cache. This way, the failure action no longer depends on the application remembering to perform it.
Another often overlooked detail is that deletion is safer than updating. If the new value is written directly to the cache during an update, and the order of two concurrent writes is reversed, the older value will remain in the cache. Deletion does not have this problem; the value will be reloaded on the next read.
Finally, accept the reality of "eventual consistency" in caching strategies. Most businesses really need "correct within one second," not "infallible for any nanosecond." Setting a shorter TTL is much more cost-effective than writing a complex distributed lock.
Practical figures: Hit rate, capacity planning and monitoring metrics
Whether a caching strategy is good or not cannot be judged by feeling, but by looking at four numbers.
Hit RatioThis is the first one. Generally speaking, for read-heavy and write-light business caching, it should be able to achieve more than 951 TP3T; if it drops below 801 TP3T, you should check whether the TTL is too short, the key design is too fine, or the phasing algorithm is wrong.
It's important to note that hit rates vary by key type. An overall hit rate of 97% might mask the fact that a critical path only has 40%, and that path happens to be the source of pressure on your database.
The second is the rate of obsolescence (Evictions).If a large number of caches are being evicted every second, it means there is not enough memory. The caches are being discarded before they can be reused. In this case, adding more memory is more effective than the tuning algorithm.
The third is memory utilization rate and fragmentation rate.Redis mem_fragmentation_ratio A value consistently greater than 1.5 indicates that the actual physical memory used is far greater than the data itself, which warrants investigation.
The fourth is the delay distribution.Furthermore, you should look at page 99, not the average. The average latency figures for caching strategies always look great, but the problems are hidden at the end—large key serialization, slow instructions, or blocking during eviction.
A rough estimation method for capacity planning: First, measure the average size of a single cached value, multiply it by the number of keys you want to keep in the cache, and then multiply by 1.3 as a buffer for relay data and fragmentation. The calculated number is your... maxmemory Lower limit.
Another rule of thumb: the value of a single key should not exceed 100 KB. Exceeding this will significantly worsen serialization costs, network transmission, and congestion during disposal. It is recommended to split or relocate the storage of the object.
Decision Tree for Selecting a Fast-Track Strategy: Five Questions to Determine a Solution
Summarize the preceding content into five questions. Answer them in order, and your shortcut strategy will emerge.
- How long can this document remain unused?Completely cannot be cached → Write-Through; can be cached for a few seconds to a few minutes → Cache-Aside with short TTL; can be cached for a few hours → Cache-Aside with long TTL, or even pushed up to CDN.
- What is the ratio of write volume to read volume?Reading far more than writing → Cache-Aside or Read-Through; writing more than reading → Write-Around, to avoid consuming memory with unused data.
- Is it okay if this document is slightly missing?If possible (for counting, data tracking) → Write-Behind can achieve the lowest write latency; if not possible (for orders, cash flow) → never use Write-Behind.
- Is there a single overheating key?If yes → You must handle the breakdown by rebuilding with a mutex or logical expiration; if no → TTL plus bubbling is sufficient to prevent avalanche.
- Will it be detected that the key does not exist?APIs exposed to the outside world will almost certainly have null value caching and parameter validation added, and Bloom filters will be used for high traffic volumes.
The order of these five questions is intentional. The first three questions determine the reading and writing pattern, and the last two questions determine the protective measures. Establish the fast-access strategy pattern first, then discuss protection; don't do it the other way around.
One last reminder: don't implement caching right away. First, confirm that the bottleneck is truly in read operations and that indexes and queries have been adjusted. Many problems attributed to "needing caching" are actually just due to the lack of an index. You can review this section later.Introduction to database basicsThat one.
Frequently Asked Questions (FAQ)
Which should I choose, Redis or Memcached?
For simple key-value caching and the purest multi-threaded model, Memcached is still a great option. However, if you need data structures (lists, sets, sorted sets), persistence, master-slave replication, or Lua scripts, Redis is almost the only answer, and it's the default choice for most teams.
Is local caching (within the JVM, within a process) still needed?
It's necessary, and often underestimated. In-process caching involves no network round trips, resulting in nanosecond-level latency. A common approach is to use a two-layer system: a local cache blocks the most frequently accessed keys, while Redis acts as the second layer for sharing. The trade-off is temporary inconsistencies across multiple machines, so the TTL for the local layer must be set very short.
How do I preheat a fast cache?
Before going live or restarting, caching strategies should be combined with a warm-up: use background tasks to load known popular keys first. The key is to "batch and stagger TTLs," otherwise the warm-up itself will create a pre-arranged avalanche.
Can I put the session in the cache?
Yes, it's possible and a common practice, but please treat it as "primary storage" rather than a cache. In other words, you need to enable persistence and ensure high availability. If a Redis restart causes a site-wide logout, it's not a caching issue, it's an architectural problem.
Should the caching strategy be written to a file?
Yes. At a minimum, the naming rules, TTL, expiration time, and responsible service for each type of key must be recorded. Without this caching policy file, no one will dare to touch any key after six months, and the caching will become the most untouchable part of the system.
Further Reading: System Design Series
Cache strategies are one of the few system design problems with "extremely high returns but numerous details." To understand the entire framework, you can continue reading from the following articles:
- Complete System Design GuideThis is a comprehensive overview of 12 articles, from concepts to practical components. It is recommended to read this article first before selecting any chapters.
- CDN Basic Concepts and Design (System Design 12)The edge cache works in a way that complements the application layer cache discussed in this article.
- Explanation of Load Balancers (System Design 07)There is a direct relationship between traffic offloading and cache hit rate, especially in scenarios with multi-node local caching.
- Key-Value Store Design (System Design 11)The data model and distributed considerations behind Redis.
If you want to apply this caching strategy directly to an existing system, the recommended order is: first measure the hit rate, then add protection (avalanche and penetration), and finally tune the elimination algorithm. Reversing the order will waste a lot of time tuning a parameter that is never actually used.
