Prompt
How do I use TTL to keep cached data fresh?
Latest observation
Oct 25, 2026
OpenAI APIWeb search: off
TTL, or Time To Live, is a simple way to keep cached data reasonably fresh by giving each cached item an expiration time.
Basic idea
When you store something in the cache, you also store:
- the data
- the time it was cached
- a TTL value, like 60 seconds
Then:
- if the item is younger than TTL, use the cached value
- if it’s older than TTL, treat it as stale and refresh it from the source
Example flow
- User requests data.
- Check cache.
- If cached item exists and hasn’t expired, return it.
- If expired or missing, fetch fresh data from the database/API.
- Store the fresh data back in cache with a new TTL.
Simple example
If you cache a user profile with a TTL of 5 minutes:
- requests within 5 minutes get the cached profile
- after 5 minutes, the next request refreshes it
Why use TTL
- reduces load on databases/APIs
- improves response times
- automatically limits stale data
Important tradeoff
Short TTL:
- fresher data
- more cache misses
Long TTL:
- fewer cache misses
- staler data
So you pick a TTL based on how often the data changes and how much staleness is acceptable.
Common patterns
- Write-through cache: update cache whenever source changes
- Cache-aside: app checks cache first, refreshes on miss/expiry
- TTL + refresh on access: stale entries are replaced when requested
- Background refresh: refresh popular items before they expire
Tips
- Use shorter TTLs for rapidly changing data
- Use longer TTLs for mostly static data
- Add some random jitter to TTLs to avoid many entries expiring at once
- If correctness matters, don’t rely on TTL alone—also invalidate cache when data changes
If you want, I can show TTL examples in Redis, Python, JavaScript, or a cache-aside design.
Brands