Video in progress

Strong Middle ⚡ Redis and caching

Why is it a bad idea to separate services into databases numbered 0, 1, 2 (`SELECT`) on a single Redis instance?

Numbered DBs are only a separate namespace for keys: the thread, the memory limit, eviction, FLUSHALL and slow commands are all shared. One service's mistake takes down the others as well. And Redis Cluster supports only DB 0 at all.

📖 Answer

It looks convenient:

spring:
  data:
    redis:
      database: 2    # notification-service

But the separation is shallow:

  • One thread: if the orders service runs a 3-second Lua script or KEYS * in DB 1, notification in DB 2 also waits 3 seconds.
  • One maxmemory: if one service fills the cache, allkeys-lru evicts another service's keys, since the DB number doesn't matter for eviction.
  • FLUSHALL: if a script someone wrote for testing reaches prod, all DBs are wiped.
  • Cluster: if you grow later and move to Redis Cluster, SELECT doesn't work and you have to migrate all the services at once.
  • Observability: INFO keyspace shows only the key count per DB; memory, CPU and latency can't be broken down by DB.

So what should you do:

  • in a small project, one DB, a prefix with the service name (orders:, notif:) and an ACL user for each service: ~orders:* allows access only to its own keys;
  • for an important or heavy service, a separate instance. Data with different requirements, like a cache versus sessions/queues, is also better off on separate instances.

DB numbers are handy for separating tests in local development, not in prod.