AlgoViz

Cache TTL

easy 24 min

A time to live (TTL) says how long a cached copy may be used.

Video lesson · Chapter 1 of 5

Sixty seconds from which event?

0:00 / 3:26

Cache TTL in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 1 min.

What it is

A cached copy starts to age the moment it is made, because the original can change. A time to live is the number of seconds the copy may be used. After that it has expired and the next reader needs a fresh value.

The promise is simple: if copies are only made from fresh data and the TTL is 60 seconds, a reader of that cache never sees data more than 60 seconds old. Nothing has to notice the change.

Why it exists

Without a TTL, one forgotten update leaves a wrong value in the cache for ever. With it, every mistake heals by itself after a known time.

A TTL is also a control for load. A longer one means fewer visits to the source, a shorter one means fresher data. Every TTL is a point on the line between those two wishes.

A short history

  1. September 1981

    RFC 791 gives every internet packet a time to live, so that lost packets cannot circle for ever.

  2. November 1987

    RFC 1035 gives every DNS record a TTL that tells resolvers how long they may keep the answer.

  3. January 1997

    RFC 2068, the first HTTP/1.1 specification, defines Cache-Control with max-age.

  4. March 1998

    RFC 2308 describes negative caching in DNS: remembering that a name does not exist.

  5. May 2010

    RFC 5861 defines stale-while-revalidate and stale-if-error for HTTP caches.

Words to know

TTL
Time to live: how long a copy may be used.
Fresh
The copy is younger than its TTL.
Stale
The copy is older than its TTL, or differs from the source.
Jitter
A random change to a TTL so that copies expire at different times.
Revalidation
Asking the source if a copy is still correct.
Negative caching
Caching the fact that something does not exist.
Origin
The server that owns the real response.

How it works

Step through the idea, or press Play.

Step 1 of 3

Store with a lifetime. The copy gets an expiry time

Understand it

Start here

Flowers with a replace-by day

Imagine flowers in vases, each with a card that says when to replace them. Nobody inspects the flowers every hour. The card is enough. That is a TTL.

Replace by Friday
TODAYMonFriFriFriEvery card says: replace by Friday

The card limits the age without anybody watching. That is why TTLs are everywhere.

The idea

Too short, too long, just right

  • Too short

    Fresh data, but the source does nearly all the work again. The cache earns little.

  • Just right

    As stale as users accept, and no fresher than you need to pay for. It differs per kind of data.

  • Too long

    Fast and cheap, but people see outdated information.

What a read does

Expired does not always mean deleted. Many caches check on read and clean up later.

Why a TTL matters

ReasonWhat it gives you
Data consistencyNobody sees a wrong value for ever
MemoryUnused entries go away
PlanningA predictable load on the origin
SecurityA shorter window for a leaked or revoked value
CostA dial between storage and computing
ComplianceCopies do not outlive retention rules by much
A cache TTL alone does not satisfy a deletion law. It only limits how long a forgotten copy can survive.

Kind 1

Absolute TTL

The clock starts when the value is stored. Reading does not change it. Created at 0 with a TTL of 60, it expires at 60, even if somebody reads it at 59.

Good for

  • Stock prices, exchange rates, breaking news
  • Anything with a staleness limit
  • Predictable expiry

Costs

  • May expire in the middle of heavy use
  • Values stored together expire together

Kind 2

Sliding TTL

Every access restarts the clock. A 60-second value stored at 0 and read at 30 and 80 now expires at 140. It disappears only after 60 quiet seconds.

Good for

  • User sessions
  • Shopping carts
  • Keeping active data in memory

Costs

  • Busy data may never be refreshed
  • Every read becomes a small write
  • Needs a maximum age

Kind 3

Adaptive TTL

The TTL changes with what you observe. One version gives popular entries a bonus.

A popularity bonus

T=Tbase+min⁡(n⋅b,;Bmax)60+min⁡(30⋅2,;60)=120 sT = T_{base} + \min(n \cdot b,; B_{max}) \qquad 60 + \min(30 \cdot 2,; 60) = 120\text{ s}
30 accesses with a bonus of 2 seconds each, at most 60. Popular values are then also the stalest, so many designs adapt to how often the data changes instead.

Good for

  • Trending content and viral posts
  • Popular products
  • Less hand tuning

Costs

  • More complex, harder to explain
  • Popularity can mean more staleness
  • Needs limits at both ends

The three side by side

AbsoluteSlidingAdaptive
Clock startsWhen storedAt each accessDepends on the rule
A read changes itNoYesOften
Limits the age of dataYesNoOnly with a cap
Typical usePrices, cataloguesSessionsTrends, search

Choosing

How to choose the number

  1. 1

    Ask about harm

    How old may this be before somebody is misled? That is the upper limit.

  2. 2

    Look at change

    Data that changes once a day does not need a 10-second TTL.

  3. 3

    Check the load

    Compute the refreshes per second that remain.

  4. 4

    Add events

    If you can delete the key on a change, the TTL is only a safety net and may be longer.

  5. 5

    Measure

    Start short, watch hit rate and complaints, then lengthen.

Hit rate of one key with an absolute TTL

h=λT1+λTλ=2/s,;T=60:;120121≈99.2%h = \frac{\lambda T}{1 + \lambda T} \qquad \lambda = 2/s,; T=60:; \tfrac{120}{121} \approx 99.2\%
With random arrivals at rate λ\lambda and a quick refresh. A key read once in 100 seconds gets only 0.6/1.6=37.5%0.6 / 1.6 = 37.5\% from the same TTL.

Starting points by use case

Use caseKindTTLWhy
User sessionsSliding, with a cap15 to 30 minutesEnds after inactivity
Product catalogueAbsolute, plus delete on change1 to 24 hoursChanges rarely
Stock prices on a pageAbsolute, short1 to 5 secondsMust be fresh
User profilesAbsolute, plus events5 to 15 minutesThe owner notices a change
Search resultsAdaptive1 to 60 minutesPopular searches repeat
Feature flagsShort, or polling30 to 60 secondsQuick switch-off, little load
Rules of thumb, not standards. Your answer to the harm question wins. Orders and payments should not use a cached price.

Short against long

FactorShort TTLLong TTL
FreshnessHighLow
Hit rateLowerHigher
Database loadHigherLower
MemoryLowerHigher
Average latencyHigherLower
Expiry stampedesMore oftenRarer, not smaller

Layers

Every layer has its own clock

Four copies, four lifetimes

A browser keeps a response for 60 seconds. When it is stale it asks a CDN, outside our system, which keeps it for 300 seconds. The CDN asks our API on an app server, which reads Redis with a TTL of 120 seconds. When that has expired the API reads the database, which has no TTL.
Each layer asks the next only when its own copy has expired.

Typical ranges

LayerTTLHolds
Browser1 hour to 1 yearStatic files that rarely change
CDN5 minutes to 24 hoursPublic pages and responses
Application cache1 minute to 1 hourComputed results, sessions
Query results1 second to 5 minutesFrequent queries

Ages can add up. If the app fills the CDN from a Redis value that is already 119 seconds old, the CDN keeps it 300 more. HTTP caches report their own waiting time in the Age header, so a browser counts the time spent in the CDN, but HTTP knows nothing about Redis.

Worst age at the user

Aworst≈Tapp+max⁡(TCDN,Tbrowser)=120+300=420 sA_{worst} \approx T_{app} + \max(T_{CDN}, T_{browser}) = 120 + 300 = 420\text{ s}
When the HTTP caches respect Age. If they do not, add every layer: 120 + 300 + 60 = 480 s.

HTTP

TTL in HTTP headers

Browsers and CDNs read their TTL from the response, for example Cache-Control: public, max-age=3600.

DirectiveMeaning
max-age=NFresh for N seconds
s-maxage=NThe same for shared caches such as CDNs
publicShared caches may store it
privateOnly the user's browser may store it
no-cacheMay be stored, but must be checked before each use
no-storeMust not be stored
stale-while-revalidateMay be served stale for N seconds while it is refreshed
The names mislead: no-cache still stores. Cloudflare documents that s-maxage turns stale-while-revalidate off there, because it requires revalidation.

ETag: renewing a copy without sending it again

An ETag is a fingerprint of the content. If it still matches, the server answers 304 with no body.

Common header patterns

ContentHeader
CSS and JS with a hash in the namemax-age=31536000, immutable (1 year)
Public API responsemax-age=300 (5 minutes)
HTML pagemax-age=0, must-revalidate
User-specific dataprivate, max-age=60

More on this layer in API caching.

Trouble

When everything expires together

Load 10,000 keys at deployment with the same 10-minute TTL and they all expire in the same second. A single very popular key is just as bad: more than 100 readers can miss at once. The full story is in thundering herd.

Four preventions: JELS

  • Jitter

    Add a random part to each TTL. 60 s plus or minus 10% is 54 to 66 s.

  • Early refresh

    Renew some time before expiry, with a probability that grows.

  • Locking

    One request computes the new value; the others wait for it.

  • Stale while revalidate

    Return the old value now and refresh in the background.

Jitter turns a spike into a trickle

refreshes per second=N2jT=10,0002⋅0.1⋅600≈83\text{refreshes per second} = \frac{N}{2 j T} = \frac{10{,}000}{2 \cdot 0.1 \cdot 600} \approx 83
10,000 keys, TTL 600 s, jitter of 10% each way: a window of 120 seconds instead of one.

Same keys, spread expiry

Jitter helps when many keys expire together. It does nothing for one hot key: that needs a lock or a stale answer.

Details

How expiry really works

Redis removes expired keys in two ways. Passive: when a client touches the key. Active: it regularly tests a few random keys that have an expiry and deletes the expired ones. So expired data can hold memory for a while, but no client is given it.

Three traps

  1. 1

    Writing can remove the TTL

    In Redis a plain SET clears the expiry. Set it again in the same command, or use KEEPTTL.

  2. 2

    Two commands are not one

    SET and then EXPIRE leaves a key without expiry if the client dies between them. Use SET key value EX 60.

  3. 3

    Clocks

    Measure durations inside a process with a monotonic clock, since the wall clock can jump.

Which kind of TTL?

Golden rules

  1. 1

    Start shorter

    Lengthen it once you know the access pattern.

  2. 2

    Add jitter

    For every group of keys that is stored together.

  3. 3

    Watch the hit rate

    A low rate may mean a short TTL, or keys nobody repeats.

  4. 4

    Invalidate user changes

    People notice when their own edit is missing.

  5. 5

    Give each layer its own TTL

    Long where you can purge (the CDN), short where you cannot (the browser).

  6. 6

    Cache missing data

    With a shorter TTL.

Summary

The whole topic in one minute.

A TTL limits how old a cached copy may be. Absolute TTLs count from creation, sliding TTLs restart on use, adaptive TTLs grow with popularity. Only the absolute kind limits the age of the data.

Choose it from the staleness users accept, then check the load that remains. Add jitter so copies do not expire together, invalidate on important changes, and keep the TTL as the safety net under everything else.

  • A TTL limits how long a wrong copy can live.
  • Absolute limits age, sliding limits idleness, adaptive follows behaviour.
  • Choose from the harm of staleness, then check the load.
  • Jitter spreads many keys; a lock or stale answer protects one hot key.
  • Ages of layers can add up.

Sources