Caching is the practice of temporarily storing commonly used or frequently accessed data in a location that can be read faster, so that it does not have to be fetched again from the data source every time. It is not a specific technology, but a widely used approach.
Basic mechanism
When a program needs a piece of data, it first checks whether the cache has it. If it does, it uses it directly, and this step is usually very fast; if not, it fetches the data from the source and also keeps the result in the cache for next time.
The cost of caching is the consistency problem: when the data at the source changes, the cache still holds the old version. Therefore, in addition to storing and retrieving, you also need to decide when to invalidate it and when to actively update it.
Where it appears
- Browser: keeps files such as images, styles, and scripts locally, so they do not need to be downloaded again when the same site is visited again.
- Network nodes: nodes of a content delivery network keep copies and respond to access requests from nearby locations.
- Inside applications: temporarily stores database query results in memory to reduce repeated queries.
- The database itself: some systems have built-in caching mechanisms for query results.
These kinds of caches often exist at the same time. A speedup for a single visit is usually not the effect of one layer, but the result of multiple layers stacking together.
Invalidation and update strategies
There are several common approaches: set a validity period by time and fetch again after it expires; evict based on usage, prioritizing retention of content that was accessed most recently or most often; and actively clear the corresponding cache when data is updated. Which one to choose depends on how frequently the content changes—content that changes little is suitable for a longer validity period, while content with high real-time requirements is not suitable for staying for long.
Why changes are not visible after an update
After website content is updated, if you open it yourself and still see the old page, in most cases the cache has not yet expired. You can try a forced refresh, clearing the browser cache, or waiting for the validity period to end. This also explains why, after content goes live, different regions and different users may see the update at different times.
What to pay attention to when using it
Caching can significantly reduce server pressure and improve opening speed, but setting it properly requires distinguishing between content types: stable images, styles, and scripts are suitable for long caching; prices, inventory, and news lists that change frequently should be cached briefly or not at all. Incorrectly caching time-sensitive content for a long time will cause trouble for users, and such problems are often harder to troubleshoot than "being a bit slow."
