Quick revision
The short answer
A repository save writes the entity as a hash at sessions:<id>, adds the id to a set of all ids called sessions, adds it to one index set per indexed value such as sessions:userId:<value>, and for an entity with a TTL writes a phantom copy that lives a few minutes longer. When the hash expires, Redis does not touch those sets; only Spring removes the id, and only when an application instance receives the keyspace expired event. With notifications off, no listener running, or events lost in restarts and failovers, ids stay forever, so we enable notifications correctly, add a periodic cleanup of ids whose hash is gone, or replace the repository with a simpler model that we expire ourselves.
What to remember
In this answer, we saw that a repository save writes the hash plus a set of all ids, index sets and a phantom copy, and that only the hash and phantom expire. Spring cleans the sets when an instance receives the keyspace expired event, so notifications that are off, a listener that is not running, events lost during restarts, or events on other cluster nodes all leave ids behind forever. Enabling notifications properly, adding a paced cleanup job, or replacing the repository with a simpler per-user set that expires by itself fixes it.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A repository save writes the entity as a hash at sessions:<id>, adds the id to a set of all ids called sessions, adds it to one index set per indexed value such as sessions:userId:<value>, and for an entity with a TTL writes a phantom copy that lives a few minutes longer. When the hash expires, Redis does not touch those sets; only Spring removes the id, and only when an application instance receives the keyspace expired event. With notifications off, no listener running, or events lost in restarts and failovers, ids stay forever, so we enable notifications correctly, add a periodic cleanup of ids whose hash is gone, or replace the repository with a simpler model that we expire ourselves.
Why this question is asked
Spring Data Redis repositories make Redis look like a database: we annotate a class, extend CrudRepository, and get save, findById and even findByUserId. The convenience hides a set of extra keys that Spring maintains on our behalf, and when one piece of that machinery is missing, those keys grow forever. Interviewers ask this question to check whether we know what a framework writes into Redis, not just what our code writes. In this answer, we will look at exactly what a save stores, see how expiry is supposed to clean the indexes, find why it failed here, and go through the fixes.
1What a Repository Save Writes
Take an entity like this one. It is stored as a Redis hash, has an index on userId so we can find a user's sessions, and has a time to live.
Notice that only the hash and its phantom copy have a TTL. The set of all ids and the index sets are shared by many entities, so they cannot expire with any one of them. Someone has to remove s1 from them when the session ends. The phantom copy exists for exactly that moment: when the main hash expires, its data is gone, so Spring keeps a copy a little longer (five minutes in current versions) to know which indexes to clean and to publish an event with the expired entity's contents.
2How Expiry Is Supposed to Clean Up
Redis can publish a keyspace notification when a key expires, a message on a channel such as __keyevent@0__:expired carrying the key name. Spring's KeyspaceEventMessageListener in each application instance subscribes to it. When the message for sessions:s1 arrives, Spring reads the phantom copy, removes s1 from sessions and from each index set listed in sessions:s1:idx, deletes the helper keys and publishes a RedisKeyExpiredEvent.
Two settings make this happen. Redis must have notify-keyspace-events including at least E (keyevent channel) and x (expired events), and the repository must be told to listen, with enableKeyspaceEvents = ON_STARTUP on @EnableRedisRepositories. By default Spring tries to set the Redis config itself with CONFIG SET.
- Redis expires sessions:s1the sets still contain s1
- notify-keyspace-events includes Ex?YesRedis publishes an expired eventNoNo event: s1 stays in the sets forever
- An app instance is subscribed right now?YesSpring reads sessions:s1:phantomNoEvent lost: s1 stays forever
- Remove s1 from sessions and index setsusing sessions:s1:idx
- Delete helper keys, publish RedisKeyExpiredEvent
5 steps in order. Play them, or step through them one at a time.
3Why the Ids Outlived the Sessions Here
The flow has several places to fail, and every failure leaves ids behind. If notifications are off, Redis never publishes the event; managed services often block CONFIG SET, so Spring's attempt to enable them fails quietly or with a warning, and nobody notices. If enableKeyspaceEvents is left at its default, OFF, no listener runs. Pub/sub is fire-and-forget: if no instance is subscribed at the moment of expiry, during a deployment, a restart or a failover, the event is lost and never repeated. And in Redis Cluster, each node publishes events only for its own keys, while the listener may subscribe through one node only, so events from other nodes never arrive; check how your version handles this before relying on it.
Over months, each lost event leaves one id in sessions and one in sessions:userId:<value>, and the :idx helper key stays too. That is how the set of all ids grew to ten times the number of live sessions. Finders suffer as well: findByUserId reads the index set and returns ids whose hashes no longer exist, which shows up as nulls or extra lookups.
4Fix 1: Make Notifications Reliable
First, set notify-keyspace-events to at least Ex on every node, through the managed service's parameter group if CONFIG SET is blocked, and enable keyspace events on the repository. In a cluster, confirm that the listener receives events from every primary. This stops most of the growth, but because pub/sub can still drop events during restarts, it does not make the sets exactly right on its own.
5Fix 2: A Periodic Cleanup
Second, add a job that walks the set of all ids in small batches and removes those whose hash no longer exists, together with their index entries. SSCAN reads the set a page at a time without blocking Redis, and EXISTS checks each hash.
The job should run on one instance at a time (a scheduler lock such as ShedLock does this), and it should pace itself, as we discuss in the FAQ, so it does not add latency for other clients.
6Fix 3: Replace the Repository With a Simpler Model
Often the cleanest fix is to drop the repository for this case. If all we need is the sessions of a user, our own code can keep the session as a hash with a TTL and a per-user set, user:u42:sessions, that also has a TTL refreshed on every write. When a user is inactive, the whole set expires with them. Reads check each member with EXISTS or read the hashes and drop missing ones lazily. This uses only Redis expiry, needs no notifications and no listener, and never grows without bound.
7Follow-up questions
How would you size the cleanup job so it does not hurt latency?
By limiting work per second rather than per run. With SSCAN COUNT 500 and EXISTS checks pipelined in batches, each batch costs Redis well under a millisecond, so a pause of 50 to 100 ms between batches keeps the job to a few thousand checks per second. For ten million ids that is about an hour, which is fine for a nightly job. I would watch Redis latency and the job's own duration, and make the batch size and pause configurable.
Why does Spring need the phantom copy at all?
Because when the main hash expires, its contents are deleted before the event is delivered, and the event only carries the key name. The phantom copy keeps the data a few minutes longer so Spring can find the entity's indexes and include the expired entity in the RedisKeyExpiredEvent. Newer versions let us turn it off with a shadow copy setting when we do not need the event's contents; check your version.
8Conclusion
In this answer, we saw that a repository save writes the hash plus a set of all ids, index sets and a phantom copy, and that only the hash and phantom expire. Spring cleans the sets when an instance receives the keyspace expired event, so notifications that are off, a listener that is not running, events lost during restarts, or events on other cluster nodes all leave ids behind forever. Enabling notifications properly, adding a paced cleanup job, or replacing the repository with a simpler per-user set that expires by itself fixes it.
Open with
A save does more than write the hash. Spring Data Redis writes the entity as a hash at sessions:id with the TTL, adds the id to a set of all ids called sessions, adds it to an index set for each indexed value, here sessions:userId:value, keeps a helper set of which indexes hold the id, and writes a phantom copy that lives about five minutes longer than the hash.
Then, if they want more
Only the hash and the phantom expire. The sets have no TTL, so Redis never removes the id from them; Spring does that, but only when an application instance receives the keyspace expired event, which needs notify-keyspace-events with at least Ex and enableKeyspaceEvents set to ON_STARTUP on @EnableRedisRepositories.
If notifications are off, which is common on managed services that block CONFIG SET, or no instance is listening at that moment, or events are lost during restarts and failovers, the ids stay forever. That is why the id set is ten times larger, and finders return ids of missing hashes.
In Redis Cluster each node only publishes events for its own keys, so the listener must hear every primary.
To fix it, I enable the notifications properly, add a paced cleanup that SSCANs the id set and removes ids whose hash no longer exists, or replace the repository with a simple per-user set with its own TTL that my code maintains.
About this answer
- Last updated
- 13 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Redis documentation
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 "How do Redis repositories store an entity and its indexes, why do index entries outlive...": https://scrivio-interview-library.netlify.app/databases/redis-scaling/1f0753aa63/