Video in progress

Strong Middle ⚡ Redis and caching

How does a Spring Data Redis repository (`@RedisHash`) store data in Redis, and what unexpected problems come up with `@Indexed` and TTL?

Each object is a separate hash, all the IDs go into a shared Set, and one more Set is stored for every @Indexed value. When a hash expires by TTL, the Sets are not cleaned up automatically. Spring does it through keyspace events and a "phantom" key, and if the application isn't running at that moment, "ghost" IDs remain in the indexes.

📖 Answer

@RedisHash(value = "otp", timeToLive = 300)
public record OtpSession(@Id String id, @Indexed String phone, String codeHash) {}

After save(), keys roughly like these appear in Redis:

otp:7f3a            HASH   the object itself, TTL 300
otp                 SET    all the IDs
otp:phone:998901234567  SET   index: the IDs belonging to this phone
otp:7f3a:idx        SET    which indexes this object is in
otp:7f3a:phantom    HASH   a copy, TTL 300 + 5 minutes

Redis deletes otp:7f3a by TTL, but doesn't touch the otp and otp:phone:... Sets. For Spring to clean them up:

@EnableRedisRepositories(enableKeyspaceEvents = EnableKeyspaceEvents.ON_STARTUP)

Then it listens for the expired event, reads the data from the phantom, cleans up the indexes and publishes a RedisKeyExpiredEvent.

This is where the problems start:

  • if this flag isn't turned on, findByPhone finds deleted IDs and the Sets grow without limit;
  • the events arrive over Pub/Sub, so records that expire during a deploy are left uncleaned;
  • on managed Redis, CONFIG SET notify-keyspace-events may be forbidden and you have to configure it by hand;
  • phantom keys almost double the memory;
  • findAll() does an SMEMBERS on a large Set.

What I usually do: for short-lived data with a TTL, I use a plain RedisTemplate and keys I build myself instead of a repository. A repository is more convenient for data without a TTL that rarely changes.