With the load balancer, Rutaverde's application layer can now grow sideways. But all the instances still go to the same database, and the Tracking service will have to answer 250 queries per second in peak season with a p95 under 500 ms. The cheapest way to serve a read is not to have to compute it: if someone asked the same thing five seconds ago, the answer is almost always still valid. That is the idea behind caching. In this lesson we will see why it works, at which levels it can be placed, what in-memory stores such as Redis are, which strategies exist for reading and writing, how data expiration is managed, and which classic problems have to be anticipated. We will apply it to the tracking query and record the decision in ADR-005.

Contents

  1. What a cache is and why it works
  2. Cache levels
  3. In-memory stores: Redis and Memcached
  4. Read and write strategies
  5. Expiration, invalidation, and eviction policies
  6. Classic problems and their solutions
  7. Metrics: the hit rate and its effect on load
  8. Example: cache-aside for the tracking query
  9. Other uses of the in-memory store
  10. Design for Rutaverde

  1. What a cache is and why it works

A cache is a fast store of limited capacity that keeps copies of data that is expensive to obtain, in order to serve subsequent requests without repeating the work. Two basic terms:

  • Hit: the requested data is in the cache and is served from it.
  • Miss: it is not there; you have to go to the origin, and normally it is stored for next time.

Caching works because access to data is not uniform. Two properties explain it:

  • Locality. What was queried recently is very likely to be queried again soon, and a small part of the data accounts for most of the accesses. Of the millions of shipments Rutaverde keeps, almost all the queries refer to the ones out for delivery today.
  • Reads that are far more frequent than writes, and repeated. The average of 4 queries per shipment hides a very uneven distribution: many shipments are queried once or never, and a minority are queried dozens of times in a few minutes. It is the recipient waiting at home and reloading the page nonstop, or the online store asking in a loop about its open shipments. During those bursts, which are what make up the peaks, the status does not change.

A cache is not free. Its price is that the data served may not be the latest. Every caching decision is, at heart, an answer to the question: how much staleness does this data tolerate? It is the trade-off between consistency and performance from the previous module, applied to a specific case.

Good candidate for caching Bad candidate for caching
It is read a lot and changes little It changes on every read
Obtaining it is expensive Obtaining it is already fast
It tolerates seconds or minutes of staleness It must be exact: a balance, an amount to be invoiced
It is the same for many users It is different for every request

  1. Cache levels

There are caches all along the path a request travels. The closer to the user it is resolved, the less work reaches the system.

flowchart LR
    N["Browser"] --> C["CDN"]
    C --> P["Reverse proxy"]
    P --> A["Application"]
    A --> M["In-memory store"]
    A --> B["Database"]
Level What it stores Who controls it Use at Rutaverde
Browser Static files and responses, according to Cache-Control The origin, through headers Static files for the portal and for tracking
CDN Static content, close to the user The origin, through headers Decided in the patterns lesson
Reverse proxy Complete HTTP responses The proxy configuration Not used in the first phase
Application, local Data in the memory of each instance The code Reference tables: cities, rates
Application, distributed Data in a shared in-memory store The code The tracking query
Database Data pages and indexes in memory The database engine Already exists in db-01

The two application levels deserve a closer look:

  • The local cache lives inside each instance. It is the fastest, but each instance has its own: with five instances there are five copies that may differ and five times as many misses. It is useful for small, nearly immutable data.
  • The distributed cache lives in a shared external store. All the instances see the same thing, and a freshly started instance benefits from what the others have already stored. It is the right one for a service that scales horizontally.

  1. In-memory stores: Redis and Memcached

An in-memory store is a database that keeps its data in RAM instead of on disk. Since accessing memory is thousands of times faster than accessing a disk, it responds in around a millisecond or less. Its model is key-value: a value is stored under a key and retrieved by that same key. There are no complex queries, and that simplicity is the source of its speed.

The two best-known products in this category are Redis and Memcached:

Aspect Redis and compatible stores Memcached
Value types Strings, lists, sets, sorted sets, hashes, counters Strings only
Atomic operations Yes: increment, append to a list, set with expiration Basic
Persistence to disk Optional No
Replication Yes, primary and replicas Not natively
Complexity Medium Very low
Typical use Cache, sessions, counters, simple queues Pure cache

As for data structures, we will use three: the string to store a serialized response, the atomic counter to count requests without two instances stepping on each other, and per-key expiration, which deletes the data automatically after a given time.

As for optional persistence: an in-memory store loses its content if it restarts, unless it is configured to dump it to disk, either with periodic snapshots or by logging every operation to a file. For a pure cache this is not needed, because everything can be recomputed. For sessions it is advisable, or at least having a replica.

From here comes the most important rule of the lesson: the cache is an accelerator, not a source of truth. Everything in it must be rebuildable from the origin store. If losing the cache means losing data, what you have is a poorly protected database.

  1. Read and write strategies

There are four classic ways of coordinating the cache with the origin store.

Cache-aside

The application manages the cache on its own: first it looks there; on a miss, it reads from the origin and stores the result.

sequenceDiagram
    participant A as Application
    participant C as Cache
    participant O as Origin store
    A->>C: Read key
    C-->>A: Not found
    A->>O: Read data
    O-->>A: Data
    A->>C: Store key with expiration

Read-through

The same as the previous one, but it is the cache itself, or a library that wraps it, that goes to the origin on a miss. The application only talks to the cache.

sequenceDiagram
    participant A as Application
    participant C as Cache
    participant O as Origin store
    A->>C: Read key
    C->>O: Read data if it does not have it
    O-->>C: Data
    C-->>A: Data

Write-through

Every write updates the cache and the origin in the same operation, synchronously. The cache is always up to date.

sequenceDiagram
    participant A as Application
    participant C as Cache
    participant O as Origin store
    A->>C: Write data
    C->>O: Write data
    O-->>C: Confirmed
    C-->>A: Confirmed

Write-behind

The write is confirmed as soon as it is in the cache; the origin is updated later, in the background and often in batches.

sequenceDiagram
    participant A as Application
    participant C as Cache
    participant O as Origin store
    A->>C: Write data
    C-->>A: Confirmed
    C->>O: Write later, in batches
Strategy Advantage Drawback When to use it
Cache-aside Simple; if the cache goes down, the application keeps working The first access is always a miss; logic in the application Default option for reads
Read-through Cleaner application code Depends on the cache or the library offering it When the tool provides it out of the box
Write-through Reads are always fresh Slower writes; data nobody will read is stored too Data that is read right after being written
Write-behind Very fast writes; batches work together Risk of loss if the cache goes down before flushing Counters and statistics that tolerate losses

For Rutaverde we choose cache-aside: it is the simplest (P3), the whole team understands it, and it keeps the cache as an optional piece. The write-behind strategy is ruled out for any business data, because it contradicts the rule that the cache is not a source of truth.

  1. Expiration, invalidation, and eviction policies

Data leaves the cache by three routes.

Time-based expiration

Each key is stored with a TTL (time to live). Once that time is up, it deletes itself. It is the simplest and most robust mechanism, because it puts an upper bound on the staleness of the data without anyone having to remember anything.

Choosing the TTL is choosing a point on the trade-off: a long one gives more hits and older data; a short one, the opposite. A TTL of just 30 seconds may seem useless, but with 250 queries per second concentrated on the day's shipments it eliminates the vast majority of reads.

Explicit invalidation

When the data changes at the origin, its key is deleted or updated at that moment. It gives fresher data, but requires every path that modifies the data to remember to invalidate. Hence the well-known joke that cache invalidation is one of the hard problems in computer science.

The recommended practice is to combine both: explicit invalidation so that the change is seen quickly, and a TTL as a safety net in case the invalidation fails.

Eviction for lack of space

Memory is limited. When it fills up, the store must decide what to discard according to an eviction policy:

Policy What it discards Suitable for
LRU, least recently used Whatever has gone the longest without being queried Almost all caches; it is the usual option
LFU, least frequently used Whatever has been queried the fewest times Data whose popularity is stable over time
Nearest expiration Whatever was going to expire soonest When all keys have a TTL
No eviction Nothing: it rejects new writes Data that cannot be lost, such as sessions

A practical consequence: it is not a good idea to mix cache data and data that must not disappear in the same store. With an LRU policy, a spike in tracking queries could evict the merchants' sessions.

  1. Classic problems and their solutions

Stale data

This is the inherent cost of caching. It is managed, not eliminated:

  • Set the TTL according to the real tolerance of the business, function by function.
  • Invalidate explicitly when the data changes.
  • Do not cache what must be exact.
  • Show the age of the data when it helps: the tracking page will say "updated at 10:15".

Stampede

A stampede (thundering herd or cache stampede) happens when a heavily queried key expires and, in the next instant, hundreds of requests miss at once and all go to the origin to compute the same thing. If, on top of that, many keys expire at the same time, the origin suddenly receives the load the cache was sparing it.

Solution What it consists of
TTL jitter Adding a random value to each TTL so that the keys do not expire at the same time
Recomputing only once A lock makes only the first request go to the origin; the others wait for its result
Serving stale data while refreshing The old data is returned and updated in the background
Pre-warming Loading the most requested data before opening up the traffic

A special case is the cold cache: after a restart, the in-memory store is empty and the whole load falls on the origin. The design consequence is important: the origin must be able to hold up for a while without the cache, or the application must use backpressure to limit how many queries it lets through.

Cache penetration

Penetration happens when keys that do not exist are requested repeatedly. Since there is nothing to store, every request misses and reaches the origin. It can be accidental or deliberate: someone trying tracking codes at random.

Solution What it consists of
Negative caching Also storing the "does not exist" result, with a short TTL
Upfront validation Rejecting codes with an invalid format without querying anything
Rate limiting Slowing down the client that makes too many requests

There is a connection here with a known flaw in RouteManager: its tracking codes are consecutive and therefore easy to enumerate. The three measures in the table limit the damage from the scalability side; the underlying problem, which is one of security, is addressed in Module 3.

  1. Metrics: the hit rate and its effect on load

The main metric of a cache is the hit rate:

hit rate = hits / (hits + misses)

Its effect on the origin is not proportional, and it is worth seeing it with numbers. Suppose a query resolved in the cache takes 2 ms and one that reaches the store takes 20 ms:

queries_per_second = 250
hit_ms = 2
miss_ms = 20

for rate in [0.0, 0.50, 0.80, 0.90, 0.95]:
    to_store = queries_per_second * (1 - rate)
    latency = rate * hit_ms + (1 - rate) * miss_ms
    print(f"hit rate {rate:.0%}: {to_store:.1f} queries/s to the store, {latency:.1f} ms on average")

Explanation:

  • The first three lines set the assumptions: the peak load from NFR-07 and how long a query takes in each case.
  • For each hit rate, to_store computes how many queries per second are not resolved in the cache: the ones that miss, 1 - rate.
  • latency is a weighted average: the proportion of hits times their time plus the proportion of misses times theirs.
hit rate 0%: 250.0 queries/s to the store, 20.0 ms on average
hit rate 50%: 125.0 queries/s to the store, 11.0 ms on average
hit rate 80%: 50.0 queries/s to the store, 5.6 ms on average
hit rate 90%: 25.0 queries/s to the store, 3.8 ms on average
hit rate 95%: 12.5 queries/s to the store, 2.9 ms on average

Two takeaways:

  • With a 90% hit rate, the store receives 25 queries per second instead of 250: one tenth.
  • Going from 90% to 95% halves the load on the origin. At the high end, every point of improvement is worth a lot. And the reverse: a drop from 95% to 90% doubles the load without anything else having changed.

Other metrics worth watching are the memory used, the number of evictions (if it is high, there is not enough memory), and the latency of the store itself. Rutaverde sets as its target a hit rate of 85% or higher at peak hours, with an expectation of 90%. It is a hypothesis, just like the capacity per instance: it depends on how concentrated the queries really are and will only be confirmed by measuring. If the real measurement turned out lower, the main lever is to lengthen the TTL, relying on explicit invalidation. And, to be on the safe side, the store will be sized to withstand the whole load without the cache for a while.

  1. Example: cache-aside for the tracking query

This is the heart of the Tracking service, in simple Python. The cache and store objects represent the in-memory store and the service's own data store:

import json
import random

TTL_ACTIVE = 30         # seconds: shipments that can still change status
TTL_DELIVERED = 3600    # one hour: the DELIVERED status no longer changes
TTL_NOT_FOUND = 60      # negative caching

def get_tracking(code):
    key = f"trk:v1:{code}"

    cached = cache.get(key)
    if cached is not None:
        return json.loads(cached)                   # hit

    shipment = store.find_by_code(code)             # miss: go to the origin

    if shipment is None:
        result = {"exists": False}
        ttl = TTL_NOT_FOUND
    else:
        result = {
            "exists": True,
            "code": code,
            "status": shipment.status,
            "updated": shipment.updated,
        }
        ttl = TTL_DELIVERED if shipment.status == "DELIVERED" else TTL_ACTIVE

    ttl = ttl + random.randint(0, ttl // 10)        # jitter of up to 10%
    cache.set(key, json.dumps(result), ex=ttl)
    return result

Step by step:

  • The three constants capture the expiration decisions. A shipment in progress is stored for 30 seconds; a delivered one, for an hour, because it is not going to change anymore; and a nonexistent code, for 60 seconds.
  • key builds the name under which the data is stored. The trk prefix identifies the service and v1 the version of the format: if the format changes, we move to v2 and the old keys expire on their own, with no conflicts during a rolling deployment.
  • cache.get is the first step of cache-aside. If it returns something, it is converted from JSON text to a dictionary and the response is sent without touching the store.
  • store.find_by_code runs only on a miss.
  • if shipment is None applies negative caching: the fact that the code does not exist is stored too, which protects against penetration.
  • ttl + random.randint(...) adds jitter of up to 10% so that the keys do not all expire at once, which prevents a stampede.
  • cache.set(..., ex=ttl) stores the result as text with its expiration.

Two pieces complete the design outside this function:

  • Invalidation. When the Tracking service gets the news that a shipment has changed status, it updates its store and deletes that shipment's key. The next query reloads it with the new status. How that news reaches it is the topic of the lesson on asynchronous communication.
  • Tolerance to cache failures. Calls to cache are made with a timeout of 50 ms. If the cache does not respond, it is treated as a normal miss and the store is queried. The cache is optional: if it goes down, the service must get slower, never go out of service.

  1. Other uses of the in-memory store

The same type of store solves two needs that were left pending in the patterns lesson.

Sessions. The portal session is stored under a key such as session:s-81f2, with a 30-minute expiration that is renewed on every request. Any instance of the monolith can read it.

Counters for rate limiting. Several instances need a common counter, and the atomic increment provides it:

def request_allowed(ip):
    key = f"rate:trk:{ip}:{current_second()}"
    count = cache.incr(key)
    if count == 1:
        cache.expire(key, 2)
    return count <= 10
  • The key includes the IP and the current second: it is a one-second fixed-window counter.
  • incr adds one and returns the new value atomically: even if ten instances do it at once, no count is lost.
  • On the first request of each second, a 2-second expiration is set so that old counters delete themselves.
  • The request is allowed if the 10 for that second have not been exceeded. That is the tracking limit: 10 queries per second per IP.

  1. Design for Rutaverde

The design adds two in-memory stores, kept separate on purpose:

Store Where Content Eviction policy Configuration
cache-tracking Cloud, managed Redis-compatible service Tracking responses and rate counters LRU Primary and replica in different zones; 4 GB
redis-dc-01 and redis-dc-02 Data center Portal sessions No eviction Primary and replica with automatic failover
flowchart TB
    subgraph DC["Zaragoza data center"]
        MONO["mono-01 to mono-03"] --> RS["redis-dc-01 and redis-dc-02: sessions"]
        MONO --> DB["db-01"]
    end
    subgraph CLOUD["Public cloud"]
        TRK["Tracking instances"] --> CS["cache-tracking"]
        TRK -->|"only on a cache miss"| AS["Tracking's own store"]
    end

The 4 GB come from a back-of-the-envelope calculation: at the peak there are around one million active shipments per day and each stored response takes up around 1 KB, that is, roughly 1 GB, with room to grow.

The decision is recorded as follows:

# ADR-005: Distributed cache with a cache-aside strategy for tracking

Status: Accepted
Date: 2026-04-23
Participants: Marta (architecture), Íñigo (operations)

## Context
Tracking must handle 250 queries per second with a p95 under 500 ms
(NFR-05, NFR-07). Queries are concentrated on the day's shipments and the
status changes only a few times. ADR-001 already accepts that tracking is
eventually consistent.

## Options considered
A. No cache: size the store for the whole load.
B. Local cache in each instance.
C. Distributed cache in a shared in-memory store.

## Decision
We will use a managed, Redis-compatible in-memory store with a
cache-aside strategy. TTL of 30 s for shipments in progress, 1 h for
delivered ones, and 60 s for nonexistent codes, with jitter of up to
10%. We will invalidate the key when a status change is received.
The cache will be optional: a 50 ms timeout and, if it fails, a query to
the store. Portal sessions will go in a separate store, with no
eviction.

## Consequences
Positive: the Tracking store receives around one tenth of the queries;
average latency of a few milliseconds.
Negative: the status shown may be up to 30 s old if the invalidation
fails; two more components to operate.
Risks: stampede with a cold cache; dependency on a specific interface,
mitigated by its being a protocol with several compatible
implementations (NFR-13).

A note of caution: tracking responses and sessions contain data related to people. What can be stored in a cache, for how long, and with what protection are questions that must be reviewed by the head of security and, where applicable, by the regulatory compliance department. They are covered in Module 3.

Common Mistakes and Tips

  • Using the cache to cover up a badly written query. If the query takes 4 seconds, the first user after each expiration still waits 4 seconds. Fix the query first.
  • Treating the cache as a source of truth. Everything it contains must be rebuildable.
  • Keys with no TTL. Without expiration, an invalidation failure leaves incorrect data in place forever.
  • The exact same TTL for everything. It is the recipe for a stampede. Always add jitter.
  • Forgetting negative caching. Nonexistent data gets queried too, sometimes massively.
  • Caching personalized data under a common key. One user would end up seeing another's data. The key must include everything the response depends on.
  • Letting a cache outage bring down the service. Short timeout and an alternative path to the origin.
  • Not measuring the hit rate. A cache with a 20% hit rate is complexity with no benefit, and without measuring you do not know.
  • Tip: before setting a TTL, ask the business "what happens if this data is seen one minute late?" The answer almost always allows more than the technical team would dare to propose.

Exercises

Exercise 1

Decide for each piece of data whether you would cache it, at which level, and with what approximate TTL:

  1. The list of cities in which Rutaverde operates.
  2. The amount pending invoicing for a merchant, shown on the billing screen.
  3. The logo of the tracking page.
  4. The status of a shipment that is OUT_FOR_DELIVERY.

Exercise 2

In the middle of peak season, the Tracking service receives 250 queries per second. The metrics show 200 cache hits per second.

  1. What is the hit rate?
  2. How many queries per second reach the store?
  3. The team wants no more than 20 queries per second to reach the store. What hit rate is needed?
  4. Propose two measures to get closer to it.

Exercise 3

At 06:00, an overnight process preloads into the cache the status of all the shipments that will go out for delivery that day, all with a TTL of exactly 2 hours. At 08:00 the Tracking service becomes very slow for several minutes. Explain what is happening and how to fix it.

Solutions

Solution 1

  1. Yes, in the local application cache, with a TTL of an hour or more. It is a small piece of data that almost never changes. Adding a city is infrequent and can wait an hour.
  2. No. It is financial data that must be exact. It is read from the origin store.
  3. Yes, in the CDN and in the browser, with a TTL of one year and a file name that includes the content fingerprint.
  4. Yes, in the distributed cache, with a TTL of 30 seconds plus jitter, and invalidation when the status changes.

Solution 2

  1. 200 / 250 = 80%.
  2. 250 − 200 = 50 queries per second.
  3. At most 20 out of 250 may miss: 1 − 20/250 = 92%.
  4. Among others: check that negative caching is active, because nonexistent codes may be generating a good share of the misses; check whether there are evictions due to lack of memory and increase it; lengthen the TTL of shipments in progress, relying on explicit invalidation; and validate the format of the code before querying.

Solution 3

It is a stampede caused by simultaneous expiration. All the keys were loaded at once with the same TTL and expire at once, at 08:00, which is also the time when recipients start checking. For a few minutes almost all the queries miss and go to the store.

Fixes: add jitter to the preload TTL, for example between 2 and 3 hours, to spread out the expirations; apply single recomputation with a lock so that each key is recomputed only once; and, better still, serve the stale data while it is refreshed in the background. The preload itself was a good idea; the mistake was the identical TTL.

Conclusion

A cache takes advantage of the fact that accesses are concentrated on a small amount of data and that far more is read than written. We have gone through the levels at which it can be placed, from the browser to the database; the in-memory stores and what they offer; the four strategies for coordinating with the origin; expiration, invalidation, and eviction; and the three problems every design must anticipate: stale data, stampede, and penetration. The hit rate sums up its effectiveness, and we have seen that at the high end every point counts double.

At Rutaverde, ADR-005 places cache-tracking in front of the Tracking store with cache-aside and a 30-second TTL, and a second store, redis-dc-01 and redis-dc-02, holds the portal sessions. Of the 250 queries per second, only about 25 will reach the store.

But the cache has a clear limit: it only helps with repeated reads. It does not help with writes, or with reports that scan millions of rows, or with an event table that grows by almost 300 million rows a year. And we have mentioned several times a "Tracking's own store" that we have not yet designed. The time has come to face the hardest bottleneck: the data layer.

© Copyright 2026. All rights reserved