Video in progress
Why does a cache need a TTL, and how do you choose one?
The TTL is how long an entry lives in the cache. It puts a limit on how long stale data can be visible, and it keeps unneeded entries from occupying memory forever.
📖 Answer
Choose the TTL as a business question, not a technical one: "How stale can the data be before it does harm?"
- exchange rate list — 1 minute is fine;
- product description — 10–30 minutes;
- list of countries — a day or more;
- account balance — better not to cache it at all.
// write to Redis with a 10-minute TTL
redisTemplate.opsForValue()
.set("product:" + id, json, Duration.ofMinutes(10));
One practical tip: if many keys are created at the same time (for example after a deploy), they will all expire at the same time and the database gets hit all at once. So you add a little random jitter to the TTL: 10 minutes + 0–60 seconds.
Sign up to mark studied questions and save your progress.