A short course on Redis

Redis: encodings and expired keys

Two places where Redis behaves differently from the mental model most people carry: the structure it actually uses to store a key, and the moment an expired key leaves memory. This course measures both on Redis 7.4.11 inside a redis:7-alpine container, using OBJECT ENCODING, MEMORY USAGE, DBSIZE and INFO stats.

Why these two topics belong together Both are decisions Redis makes without telling anyone. Adding a 513th field to a hash makes that key take 4.65 times as much memory; DBSIZE can report 301 when only one key is readable. Both numbers are measurable, and both will mislead an operator who does not know the rule.

The two lessons

Twelve to eighteen minutes of reading each, with a lab that runs in the browser.

How the measurements were taken

Each lesson runs its own redis:7-alpine container, never sharing one with a Redis that happens to be running already. Lesson 2 needs the active expire cycle switched off to separate the two mechanisms, and DEBUG has been locked down by default since Redis 7, so the container has to start with --enable-debug-command local.

docker run -d --name rdlab -p 8088:6379 redis:7-alpine \
  redis-server --enable-debug-command local

docker exec rdlab redis-cli OBJECT ENCODING h513
# hashtable
docker exec rdlab redis-cli DEBUG SET-ACTIVE-EXPIRE 0
# OK

Each measurement script is written to a file, copied in with docker cp and run with docker exec rather than piped through stdin — that way the script survives to be re-run and checked. The two JavaScript algorithms in this course were checked against 119 measurements for lesson 1 and 25 for lesson 2.

A trap inside the measurement rig itself The first version of the encoding matrix generated values that differed only in their last digit, so set and zset deduplicated them and the real cardinality was 10 rather than 129. The resulting table looked plausible and was completely wrong. The current rig prints SCARD/ZCARD alongside each row and asserts it equals the requested count — all 112 rows agree.