Skip to content

Application caching: when it speeds things up and when it causes bugs

B2Bnetwork team · · 6 min

System performance

In brief

A cache speeds up an application when the same data is read far more often than it changes and a short delay in updates is acceptable. Typical examples are product catalogs, reference data, price lists and the results of expensive calculations. Bugs appear with data that must always be current (account balances, stock levels at reservation, permissions), with a poorly chosen time to live, and when many keys expire at once during peak traffic.

What a cache is and where to put it

A cache keeps a copy of data closer to where it is used, so the application does not ask a slower source every time: a database, an external API or a compute service. A typical web system has several cache layers:

LayerExampleStrengthRisk
Browser and CDNCache-Control header for images, scripts, public pagestraffic never reaches the serverhard to invalidate content that has already reached clients
In-process memorya map in the application server's memoryfastest read, no networkeach instance has its own copy, so instances see different data
Distributed cacheRedis, Memcachedone shared copy for all instancesan extra component that can fail or fill up
Database cachebuffer pool, query resultsworks without code changesno substitute for an index or a better query

HTTP caching is defined by RFC 9111: the Cache-Control header, with directives such as max-age, no-store and private, decides who may store a response and for how long. Private user data must stay out of shared caches, or one customer may see another's response.

When a cache actually helps

A cache pays off when three conditions hold at the same time:

  1. Reads far outnumber writes. A product page in an online store, read thousands of times between price changes, is a good candidate. A specific customer's cart is not.
  2. The same key is read repeatedly. The hit ratio tells you what share of reads is served from the cache. If keys are unique, for example because they contain a timestamp, the cache only consumes memory.
  3. The business accepts a short delay. An insurance premium calculator can show a price list from a minute ago. The balance screen in online banking cannot.

Before adding a cache, check whether the slow source can simply be made faster. A missing index or an N+1 pattern hidden behind a cache returns on every miss and every restart. How to find such queries is covered in the article on database bottlenecks.

Write and invalidation patterns

The most common pattern is cache-aside (lazy loading): the application looks for data in the cache, reads it from the source on a miss and stores a copy. When data changes, it writes to the source and deletes the cache entry, so the next read fetches the new version. The Azure Architecture Center points out that the expiration policy must match how the data is accessed: an expiration period that is too short sends the application back to the database over and over.

The second pattern is write-through: the application updates the cache together with the database. Cached data is current, but records nobody reads end up there too. AWS guidance suggests combining both and giving almost every key a time to live (TTL), so an invalidation bug expires on its own.

When the cache reaches its memory limit, the eviction policy decides what to remove. In Redis the limit is the maxmemory parameter, and on 64-bit systems there is no limit by default. The noeviction policy removes nothing and returns an error on writes. The allkeys-lru policy evicts the least recently used keys, and the Redis documentation calls it a good default if you have no reason to prefer another. Set both deliberately, because a full cache without eviction turns into application errors.

When a cache causes bugs

The most common problems show up in load tests and production, not in functional tests:

  • Stale data on a critical path. Reading stock from the cache while reserving the last item sells goods you do not have. Decisions that change data read from the source.
  • Cache stampede. A popular key expires and hundreds of requests hit the database at once to rebuild it. A lock on rebuilding a single key, random TTL jitter and refresh before expiry all help.
  • Cold start. After a deployment or restart the cache is empty and the database takes the full load. The test should cover this and the deployment plan should include warming the cache.
  • Different copies across instances. An in-process cache on several servers shows a customer a different price depending on which server answers.
  • A key without context. A key without the customer ID, language or permissions returns one user's data to another. That is a security bug, not a performance one.
  • The cache as the only copy. When the application writes data only to the cache, a restart means data loss.

How to test a cache before a peak

A cache changes performance test results, so the plan must account for it:

  1. Measure the hit ratio and the response time on hits and on misses separately.
  2. Prepare test data with a realistic key distribution. The same product requested a hundred times gives a hit ratio close to 100% and a worthless result.
  3. Run a scenario with an empty cache, meaning a cold start, and one after warm-up.
  4. Force popular keys to expire at peak and watch what happens to the database.
  5. Turn off the distributed cache during the test. The system should slow down, but keep working.
  6. In an endurance test, track cache memory usage and the number of evicted keys.

Test types and their load profiles are described in the article on load, stress and endurance testing, and preparing for a campaign in the article on performance testing before a sales peak. An e-commerce example is the project on preparing an online store for Black Friday.

Questions and answers

What TTL should I set for cache entries?

As long as the business accepts as the maximum data delay, and no shorter than the hit ratio requires. For reference data and catalogs that usually means minutes or hours; for price lists, as long as a price discrepancy may last. Add random jitter so keys loaded together do not expire in the same second.

Redis or an in-memory cache in the application?

An in-process cache is the fastest and is enough for data that rarely changes and may differ briefly between instances. Redis gives all servers one copy and survives an application restart. Teams often use both: a short local cache in front of a shared Redis, with a clear memory limit for each.

How do I check whether a cache is helping?

Compare a load test with and without the cache, using the same data and the same traffic profile. Look at the hit ratio, response time percentiles and database load. If the hit ratio is low and database load barely changes, the cache adds complexity without any gain.

Can personal data be stored in a cache?

Yes, but the cache is subject to the same rules as the database: access control, encrypted connections, retention periods and the obligation to delete data on request. A cache entry that outlives a deleted account is personal data stored without a legal basis. Private data should also stay out of shared caches and CDNs.

What it looks like in a project

Your system slows down under load? We'll find where it loses time.

Let's talk

Read more: System performance