Scrivio Interview library
DebuggingIntermediate7 min read · updated 13 November 2026

A Redis cache that should hold about 2 million keys with one-hour TTLs keeps growing until eviction starts. INFO keyspace shows db0:keys=48000000,expires=1900000, although every cache write is supposed to set a TTL.

What does the INFO line tell you, which common code paths create keys without a TTL, and how do you clean up and prevent it?

Try it yourself

Cache-aside: one read, three cache states

See what a cache hit saves, what a miss costs, and why a write deletes the cached entry instead of updating it.

Read this example as text

When the entry is in the cache (a hit)

  1. A request arrives. A caller asks the service for product 42. The cache already holds it.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Hit: the value comes back. The entry is there and still fresh, so the cache answers at once. The database is never touched.

1 cache call, 0 database reads.

When it was never cached (a miss)

  1. A request arrives. A caller asks the service for product 42. Nobody has asked for it before, so the cache holds nothing.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. The key was never stored. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When its time to live has run out

  1. A request arrives. A caller asks the service for product 42. The cache held it once, but its time to live ran out 12 seconds ago.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. An expired key is the same as a missing one: Redis no longer returns it, and removes it. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When the price changes afterwards

  1. The price changes. Later, someone updates the price to 25. The service writes the database first: UPDATE products SET price = 25 WHERE id = 42.
  2. Delete the cached entry. Then it deletes the key: DEL product:42. It does not write 25 into the cache. Deleting is simpler and safer: the next read misses and loads whatever the database holds then.
  3. The next read will miss. The cache is empty for this key again, so the next request repeats the miss path and stores 25.

3 cache calls, 1 database read, 1 database write.

What this example leaves out
  • One request at a time. Two requests missing at the same moment (a stampede) are not shown.
  • The write deletes the key. Some systems update the cache instead, which this example does not model.
  • The numbers are counts of round trips, not measured times.

The line says only about 1.9 million of 48 million keys have a TTL, so roughly 46 million keys live until eviction removes them, and they hold most of the memory. Typical causes are a plain SET that replaces a key and drops its TTL, a separate EXPIRE that was skipped or failed, a template call without a timeout, and RENAME onto a cache key. We find the prefixes by sampling with SCAN and TTL, clean up gradually with a rate-limited SCAN job, and prevent it with SET ... EX in one command, a helper that refuses writes without a TTL, and an alert on the ratio of expires to keys.

Why this question is asked

A cache that should be the size of its working set but grows without limit is almost always a cache whose keys are not expiring. Interviewers like this question because one line of INFO output tells the whole story, if we know how to read it, and the fixes test whether we know Redis commands precisely. In this answer, we will read the INFO line, go through the code paths that create keys without a TTL, find which ones are guilty here, clean up without hurting latency, and set up the guards that keep it from happening again.

1Reading the INFO Keyspace Line

INFO keyspace prints one line per database. keys is the total number of keys, and expires is the number of keys that have a TTL. Here that is 48,000,000 keys and 1,900,000 with a TTL, so about 46,100,000 keys, 96 percent of the keyspace, will never expire on their own.

That matches the expected size exactly: about 2 million keys with one-hour TTLs is the healthy part, and the rest is leakage. Keys without a TTL can only disappear through an explicit delete or through eviction, so the cache grows until it hits maxmemory and eviction starts. What happens then depends on the eviction policy. With a volatile policy, Redis only evicts keys that have a TTL, so it throws away the 1.9 million useful keys and keeps the 46 million leaked ones, and soon refuses writes. With an allkeys policy, it evicts from both, which keeps working but wastes most of the memory on keys nobody needs.

2Code Paths That Create Keys Without a TTL

The most common cause surprises many people: SET replaces the whole key, including its TTL. So code that writes once with a TTL and later updates the value with a plain SET silently makes the key permanent.

SQL
SET product:42 "{...}" EX 3600 # OK
TTL product:42 # (integer) 3600
SET product:42 "{...new...}" # OK
TTL product:42 # (integer) -1 the TTL is gone
SET product:42 "{...}" KEEPTTL # OK, keeps whatever TTL the key had (Redis 6.0+)
Common sources of permanent keys
Code pathWhy the TTL is missing
SET after the first writeSET replaces the key and drops its TTL
SET then EXPIREThe EXPIRE fails, times out or is skipped
Template set without DurationNo TTL was ever requested
Default RedisCacheManagerNo entryTtl configured
HSET, SADD, INCR on a new keyCollection commands never set a TTL
RENAME tmp -> cache keyThe destination takes the source's TTL: none

The other causes follow the same pattern: the TTL is a separate step that can be forgotten or lost. Code that calls SET and then EXPIRE as two commands leaves a permanent key whenever the second call fails, times out or is skipped by an early return. In Spring, redisTemplate.opsForValue().set(key, value) without a Duration writes no TTL at all, and a RedisCacheManager built from the default configuration has no entry TTL unless entryTtl is set. Commands that create collections, such as HSET, SADD or INCR, never set a TTL. And RENAME moves the source key's TTL to the destination, so renaming a freshly built temporary key without a TTL onto a cache key produces a permanent cache key.

3Finding Which Prefixes Leak

We do not need to look at 48 million keys. A sample of 100,000 keys, grouped by prefix and by whether TTL returns -1, which means the key exists without a TTL, shows the culprits clearly. SCAN walks the keyspace in small steps without blocking the server, unlike KEYS.

Java
// sample with SCAN, then TTL per key in a pipeline; count persistent keys per prefix
Map<String, Long> persistent = new TreeMap<>();
ScanOptions opts = ScanOptions.scanOptions().count(1_000).build();
try (Cursor<String> c = redis.scan(opts)) {
for (int i = 0; i < 100_000 && c.hasNext(); i++) {
String key = c.next();
if (redis.getExpire(key) == -1) {
persistent.merge(key.substring(0, key.indexOf(':') + 1), 1L, Long::sum);
}
}
}
// {cart:=61210, product:=33007, session:=12} (example output)

In a real job the TTL calls go through a pipeline, but the idea is the same. Two redis-cli options complete the picture: redis-cli --bigkeys reports the largest key of each type, and redis-cli --memkeys (Redis 6 and later) samples memory per key, so we see which prefixes hold the memory and not just the count. Once we know the prefix, a search of the code for that key name usually leads straight to the SET without EX or the forgotten timeout.

4Cleaning Up Without Hurting Latency

The tempting fix, deleting everything with a pattern, is the dangerous one. KEYS blocks the single-threaded server while it scans 48 million keys, and a burst of DEL on large values frees memory synchronously on the main thread. Instead we run a background job that walks the keyspace with SCAN, and for each persistent key of a cache prefix either gives it a TTL or removes it.

Giving it a TTL with jitter is the gentle option: EXPIRE key <random 600 to 3600> NX sets a TTL only if the key has none (the NX option exists since Redis 7.0), and the keys then expire over the next hour instead of all at once. UNLINK is the faster option for keys we know are garbage, because it removes the key immediately but frees the memory in a background thread. Either way, the job runs at a controlled rate, for example 5,000 keys per second in pipelines of 500, while we watch latency, and it skips prefixes that are not caches, since some keys may be meant to be permanent.

5Preventing It From Happening Again

First, write the value and its TTL in one command: SET key value EX 3600, or KEEPTTL for an update that should keep the existing expiry. For collections, set the TTL in the same MULTI or Lua script that creates them. Second, put all cache writes behind a small helper whose signature requires a Duration, and make it reject zero, so the forgotten timeout cannot compile or fails in the first test. For Spring caching, configure RedisCacheConfiguration with entryTtl for every cache.

Third, make the problem visible. An alert on the ratio expires/keys for a cache database, for example below 0.9, would have fired months ago. Finally, choose the eviction policy on purpose: for a pure cache, allkeys-lru or allkeys-lfu keeps the server working under pressure, while a volatile policy is only right when the instance also holds permanent keys that must never be evicted.

6Follow-up questions

Which eviction policy would have hidden this problem longest, and why?

allkeys-lru or allkeys-lfu. Once memory is full they evict any key, with or without a TTL, so writes keep succeeding and memory stays flat at maxmemory. Nothing errors; the only signs are rising evicted_keys and a slowly falling hit ratio, because leaked keys compete with useful ones. With a volatile policy the server would soon refuse writes, and with noeviction it would refuse them at once, which is painful but impossible to miss.

Why does TTL return -1 for some keys and -2 for others?

-1 means the key exists but has no TTL, which is what we are looking for. -2 means the key does not exist, for example because it expired between the SCAN and the TTL call. The sampling job should ignore -2 rather than count it.

Is it ever right to cache without a TTL?

Rarely. A small, bounded set of keys that are always rebuilt on change, such as a version pointer, can live without one if the instance's eviction policy will never remove it. Everything else, especially anything keyed by user or product id, should have a TTL.

7Conclusion

In this answer, we saw that expires=1900000 against keys=48000000 means about 46 million keys never expire and only eviction can remove them. They come from writes where the TTL is a separate, forgettable step: a plain SET on an existing key, SET followed by a failed EXPIRE, template calls without a timeout, collection commands and RENAME. We find the prefixes by sampling with SCAN and TTL plus --memkeys, clean up with a rate-limited SCAN job using EXPIRE with jitter or UNLINK, and prevent recurrence with single-command writes, a helper that requires a TTL, and an alert on the expires to keys ratio.

What to say in the interviewAbout 80 seconds aloud

Open with

The INFO line says 48 million keys exist and only 1.9 million have an expiry, so about 46 million keys never expire and stay until eviction. The healthy part is exactly the 2 million we expect; the rest is leakage, and it holds most of the memory.

Then, if they want more

The usual causes are writes where the TTL is a separate step. A plain SET on an existing key replaces it and drops its TTL unless you pass KEEPTTL. SET followed by EXPIRE leaves a permanent key if the EXPIRE fails or is skipped. A RedisTemplate set without a Duration, or a RedisCacheManager without entryTtl, never sets a TTL.

HSET, SADD and INCR create keys without one, and RENAME gives the destination the source's TTL. To find them I sample with SCAN and TTL, count keys returning minus one per prefix, and use redis-cli --memkeys to see which prefixes hold memory.

To clean up I run a rate-limited SCAN job that gives cache-prefix keys a jittered EXPIRE with NX, or UNLINKs them, never KEYS. To prevent it I write with SET EX in one command through a helper that requires a TTL, and alert when expires divided by keys drops below about 0.9.

About this answer

Last updated
13 November 2026
Versions it names
Redis 6, Redis 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What does the INFO line tell you, which common code paths create keys without a TTL, and...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/673c0aaacb/