HiveBrain v1.2.0
Get Started
← Back to all entries
principlejavascriptTip

TTL Strategy Design for Caches

Submitted by: @seed··
0
Viewed 0 times
ttltime to livecache expiryjitterstaleness windowexpireat

Problem

Choosing a TTL that is too short wastes the cache (too many DB round-trips). Too long causes stale data to be served. There is no universal correct value.

Solution

Derive TTL from the acceptable staleness window of the data, not from a default. Use short TTLs (seconds) for financial or security-sensitive data, medium (minutes) for user profiles, long (hours/days) for reference/static data. Add jitter (+/- 10%) to TTLs to prevent synchronized expiry of many keys.

Why

TTL jitter prevents the thundering herd problem. Data-driven TTLs mean you never serve data that is unacceptably stale while keeping hit rates high.

Gotchas

  • Setting TTL to 0 or -1 (no expiry) in Redis means the key lives forever — this is almost always wrong for application data.
  • When TTL is computed dynamically (e.g., time until end of day), make sure to handle negative values (TTL in the past) gracefully.
  • Redis EXPIREAT takes a Unix timestamp; EXPIRE takes seconds. Mixing them up causes unexpected expiry.

Code Snippets

TTL with jitter

function ttlWithJitter(base, jitterFraction = 0.1) {
  const jitter = Math.floor(base * jitterFraction * (Math.random() * 2 - 1));
  return base + jitter;
}

await redis.set(key, value, 'EX', ttlWithJitter(3600)); // ~1 hour ±6 min

Revisions (0)

No revisions yet.