Idempotency Key Expiration Strategy
You'll learn: How to set time-to-live (TTL) values for idempotency keys that balance client retry needs with storage efficiency.
The Expiration Problem
When you store idempotency keys server-side (as covered in lesson 1011), you can't keep them forever. Storage isn't free, and stale keys from months-old requests serve no purpose. But expire them too quickly, and legitimate retries will be treated as new requests—defeating the entire point of idempotency.
Choosing the Right TTL
The standard practice is to set TTLs between 24-48 hours. This window is based on realistic retry behavior:
- Client retry windows: Most well-behaved clients retry failed requests within seconds to minutes, not days
- Human intervention time: If automated retries fail, a human might investigate and manually retry within a business day
- Network partition recovery: Even extended outages typically resolve within hours
Think of it like a hotel's lost-and-found policy: keep items long enough for guests to realize they forgot something and come back, but not so long that your storage room overflows.
Balancing Constraints
Your TTL should consider:
- Storage costs: Longer retention means more keys in your database or cache
- Compliance windows: Some industries require request deduplication for specific audit periods
- Client SLAs: If you promise clients they can safely retry for 48 hours, honor that
A 24-hour TTL works for most high-volume APIs. A 48-hour TTL provides extra safety for critical financial operations. Anything beyond 72 hours is typically unnecessary overhead.
Key Takeaway: Set idempotency key TTLs to 24-48 hours—long enough to cover realistic retry scenarios while keeping storage manageable and avoiding indefinite accumulation of stale keys.