Skip to content

Caching

Introduction

Temporarily keep results that are "expensive to compute or slow to change" in a faster place and fetch them directly next time, instead of recomputing.

✗ Without it
1,000 users view the same product
1,000 database queries
Heavy database load
Pages slow down or crash
✓ With it
1,000 users view the same product
1st request hits the DB and fills the cache
The other 999 read the cache
Millisecond responses; the database stays calm

Why use it

  • Faster: memory reads are usually one or two orders of magnitude faster than database queries.
  • Cheaper: less database pressure means the same servers can serve more users.

New problems it brings

Caching is not free. The hardest part is: when the data changes, how do you update the cache?

Problem Plain explanation Mitigation
Cache expiry / invalidation The database changed, but the cache still has the old value Set a TTL; actively delete the cache on write
Cache penetration Always looking up data that does not exist, so every miss hits the database Cache “empty results” for a short time
Cache breakdown A hot key expires and many requests hit the database at once Lock so only one request rebuilds it
Cache avalanche Many keys expire at the same time Add random jitter to TTLs

Component comparison

In-process memory cache

Built into the frameworkOpsLow

Temporarily keep computed results in the program's own memory and fetch them directly next time without querying the database.

Best forA single server and small amounts of rarely changing data, such as config and lookup tables.

Avoid whenThere are multiple servers and data must be consistent, or the cached content is large.

Pros

Reads and writes stay inside the process, so there is no network cost

The framework usually includes it, and a few lines of code are enough

You do not deploy Redis or any other cache

Cons

It is valid only in this process, and machines do not stay in sync

As soon as the program restarts, the cached contents are all gone

It uses the application's own memory, and too much of it can drag the process down

Redis distributed cache

Self-hosted open sourceOpen sourceOpsMedium

Put the cache in a standalone Redis service, so all servers read and write the cache from the same place.

Best forMulti-server deployments, session sharing, and caching hot data (products, user info).

Avoid whenSmall single-machine projects with small data and traffic volumes.

Pros

Instances share one cache, so they read the same data

The cache lives in its own process, so an application restart does not drop it

You can set an expiry, and it can also count and rate-limit

Cons

Redis is deployed on its own, which is one more point of failure

Every read goes over the network, which is slower than an in-process cache

Inconsistency, and a cache expiring all at once, are both yours to prevent

HTTP cache / CDN cache

Managed servicePay-as-you-goOpsLow

Let the browser or the CDN node nearest the user store images, pages and API results, so requests never need to reach your server.

Best forContent that looks the same to everyone: images, files, public pages, articles.

Avoid whenContent varies by person (such as personal orders or balances) or must be accurate in real time.

Pros

It can clearly reduce load on the origin and outbound bandwidth

Users are closer to a node, so the page opens faster as well

Images, scripts, and styles should almost all be cached

Cons

After an update the old cache is still there, so purge it or add a version

A response that carries user data must not be cached, or users see each other's data

A CDN is generally billed by traffic or by the number of requests

Database-native cache / materialized views

Built into the frameworkOpsLow

Have the database precompute and store the results of complex queries (materialized views), or rely on the database's built-in query cache.

Best forReports, statistics dashboards and complex aggregate queries where a few minutes of delay is acceptable.

Avoid whenData must be consistent in real time, or the bottleneck is many simple queries rather than complex statistics.

Pros

A complex statistical query can drop from several seconds to milliseconds

The result stays in the database, so you do not start another cache service

Data and results are both in the database, so backups stay in one place

Cons

A materialized view has to be refreshed on a schedule, and that uses database resources

Support differs by database, and MySQL has no native materialized view

It cannot replace an application cache, because requests still connect to the database

Checklist

  • Confirmed the bottleneck is repeated reads, not the query itself
  • Every cache entry has a TTL
  • There is an invalidation strategy when data changes
  • Multi-instance deploys use a shared cache (Redis), not per-process memory
  • TTLs include random jitter to prevent avalanches