Memory and the Allocator
The 5 Layers Behind SET mykey "hello"
Breakdown of ~88 bytes — every small key has this overhead
| 32 bytes (24 raw + jemalloc rounding) | Layer 1 — dictEntry (hash table bucket entry) |
| 16 bytes (3B header + 5B data + 1B null → rounded) | Layer 4 — Key SDS "mykey" |
| 16 bytes (type, encoding, lru, refcount, *ptr) | Layer 2 — redisObject (value wrapper) |
| 16 bytes (3B header + 5B data + 1B null → rounded) | Layer 3 — Value SDS "hello" |
| ~8 bytes amortized share of the bucket array | Bucket array |
| Total: ~88 bytes verify: MEMORY USAGE mykey · DEBUG OBJECT mykey | |
The rule of thumb: every small key costs roughly 60–100 bytes, regardless of value size.
Layer 1 — Hash Table Entry (dictEntry)
The keyspace is one big hash table (dict). Every key maps to a bucket:
hash("mykey") % total_buckets → index N → bucket[N] → dictEntry
dictEntry
├── *key → pointer to key string ("mykey")
├── *val → pointer to value object
└── *next → next dictEntry in bucket chain (for hash collisions)Size: 24 bytes raw → 32 bytes after jemalloc rounding, plus ~8 bytes amortized bucket-array cost.
Hash Table Rehashing — Deep Dive
How many buckets are there?
Redis starts every new dict with 4 buckets (hardcoded minimum, always a power of 2). On the first SET, Redis allocates the bucket array at size 4.
When does the count change?
Redis tracks a load factor: used_keys / total_buckets.
grow when load > 1.0 (more keys than buckets)shrink when load < 0.1 (buckets mostly empty) on trigger, double or halve — always staying a power of 2
4 buckets, 5 keys → load = 1.25 → grow
→ allocate new table with 8 buckets
→ rehash all entries: old positions change because
hash(key) % 8 ≠ hash(key) % 4Does Redis actually shrink in practice? Rarely. The shrink threshold (load < 0.1) is very hard to hit without mass deletions — you'd need to delete 9,000 of 10,000 keys quickly. Growth is far more common. There's also a second guard: while a BGSAVE or BGREWRITEAOF is in progress, Redis raises the growth threshold from 1.0 to 5.0, delaying growth so it doesn't trigger COW page copies during a fork snapshot.
No fork running: grow if load > 1.0
Fork in progress: grow if load > 5.0 ← extra headroom to avoid COW pressureIncremental rehashing — two tables at once
Redis does not rehash all at once — on millions of keys that would block the event loop for seconds. Instead it keeps two bucket arrays simultaneously:
dict
├── ht[0] → [ old table, being drained ] 4 buckets
└── ht[1] → [ new table, being filled ] 8 buckets
└── rehashidx = 2 ← "next bucket to migrate"How migration actually happens
Migration is driven by serverCron (the 100 ms tick) and by each individual command:
- Execute the command.
- Move 1 bucket from
ht[0]→ht[1](rehashidx++). - If
ht[0]is now empty → discard it, promoteht[1]toht[0], clearht[1].
serverCron also runs up to 1 ms of migration per tick (100 buckets max) so progress happens even on an idle server.
Bucket migration (one step):
ht[0][rehashidx]: dictEntry A → dictEntry B → NULL
│
└──► re-hash each entry with new modulus
A: hash("keyA") % 8 = 3 → ht[1][3]
B: hash("keyB") % 8 = 7 → ht[1][7]
ht[0][rehashidx] = NULL (bucket is now empty)
rehashidx++The full lifecycle
Phase 1 — Normal operation
ht[0] has N buckets, ht[1] = NULL; all reads/writes go to ht[0]
Phase 2 — Trigger: load > 1.0
Allocate ht[1] with 2N buckets; set rehashidx = 0
Phase 3 — Incremental migration (can take many ms or seconds)
Reads: check ht[0] first, then ht[1]
Writes: always go to ht[1]
Every command: migrate 1 bucket · serverCron: up to 100 buckets/tick
Phase 4 — ht[0] is empty
Discard ht[0]; ht[0] = ht[1]; ht[1] = NULL; rehashidx = -1
Back to Phase 1Why always a power of 2?
hash % 8 ≡ hash & 7 (when N = 8 = 2³) modulo with a power of 2 becomes a single bitwise AND — much faster
This is why Redis always doubles/halves rather than picking arbitrary sizes. Bucket count is always 2^n.
Layer 2 — Value Wrapper (redisObject)
dictEntry.*val doesn't point at "hello" directly — it points at a wrapper struct.
dictEntry
└── *val ──→ redisObject
├── type (string / list / hash / set / zset / stream)
├── encoding (int / embstr / raw / listpack / skiplist...)
├── lru (eviction policy: timestamp or frequency)
├── refcount (shared object reference count)
└── *ptr ──→ SDS ("hello")Size: 16 bytes.
- Shared objects: integers 0–9999 are pre-allocated at startup.
SET a 100andSET b 100point to the sameredisObject. It's freed only whenrefcounthits 0. intoptimization: small integers are stored directly in the*ptrfield — no SDS allocated at all, no third hop.
Layer 3 & 4 — SDS (Simple Dynamic String)
Redis doesn't use plain C strings. Both the value and the key are SDS:
memory layout:
[ len | alloc | flags | h | e | l | l | o | \0 ]
←── header ──→ ←──────── buf ────────────────→
↑
*ptr points here| Problem | C strings | SDS |
|---|---|---|
| Length lookup | O(N) — must scan to \0 | O(1) — read the len field, so STRLEN is always O(1) |
| Binary data | Breaks on embedded \0 bytes | Stores arbitrary bytes safely |
| Append | Full realloc every time | alloc capacity field gives pre-allocated headroom — often free |
flags selects which of 5 header variants is used, minimizing waste on short strings. Size for "hello": 3-byte header + 5 data + 1 null = 9 bytes → 16 bytes after rounding. "mykey" gets its own identical 16 bytes.
Layer 5 — jemalloc Rounding
Redis ships with jemalloc. Instead of arbitrary allocation sizes it maintains separate free lists per size class:
free list for 16-byte slots: [slot][slot][slot]...
free list for 32-byte slots: [slot][slot]...
free list for 64-byte slots: [slot][slot][slot]...- Allocation = pop from the right list → O(1), no searching.
- Deallocation = push back → O(1), no OS involvement.
- Cost: internal fragmentation — asking for 9 bytes, getting 16.
Slabs: jemalloc asks the OS for a large chunk (~2 MB) upfront, carves it into fixed slots, and hands them out. One syscall amortized across tens of thousands of allocations.
The final tally
| Allocation | Raw size | Rounded |
|---|---|---|
dictEntry | 24 bytes | 32 |
Key SDS ("mykey") | 9 bytes | 16 |
Value redisObject | 16 bytes | 16 |
Value SDS ("hello") | 9 bytes | 16 |
| Bucket array share | ~8 bytes | ~8 |
| Total | ~88 bytes |
Encodings That Save Memory
The encoding field inside redisObject tracks how data is physically stored. Check with OBJECT ENCODING <key>.
String encodings
| Encoding | When | What it saves |
|---|---|---|
int | Value is an integer | The entire SDS; 0–9999 reuses a shared redisObject — no allocation at all |
embstr | String ≤ 44 bytes | One allocation instead of two; better cache locality |
raw | String > 44 bytes | Baseline — no savings |
raw: [ redisObject ] ──→ [ SDS header | data ] (2 mallocs, 2 cache misses)
embstr: [ redisObject | SDS header | data ] (1 malloc, 1 cache fetch)The 44-byte limit is not arbitrary: redisObject (16) + SDS header (3) + 44 data + 1 null = 64 bytes — exactly one jemalloc size class. Catch: embstr is immutable; any APPEND immediately promotes it to raw.
Collection encodings
| Encoding | Used for | Structure | Read cost |
|---|---|---|---|
listpack | Small hashes, sets, sorted sets (≤128 entries) | Flat byte blob, length-prefixed | O(N) scan — fine when N is tiny |
intset | Integer-only sets | Sorted array of raw integers | O(log N) binary search |
quicklist | Lists | Linked list of listpack nodes | O(1) head/tail |
Promotion thresholds (either condition alone triggers it):
too many entries: count > hash-max-listpack-entries (default 128)
any entry too big: size > hash-max-listpack-value (default 64 bytes)Promotion is one-way — Redis never demotes back to a compact encoding. The only way back is to delete the key and recreate it.
Fragmentation: mem_fragmentation_ratio
used_memory → what Redis thinks it's using (logical) used_memory_rss → what the OS says the process holds (physical) mem_fragmentation_ratio = used_memory_rss / used_memory
| Ratio | Meaning | Action |
|---|---|---|
| ~1.0–1.1 | healthy | Nothing |
| > 1.3 | fragmented jemalloc can't return pages that still hold live allocations | Enable activedefrag yes |
| < 1.0 | emergency data is swapped to disk — sub-ms ops become ms ops | vm.swappiness=0 immediately |
Active defrag (activedefrag yes) incrementally moves live allocations in small time-boxed bursts on the main thread — it self-throttles and doesn't block commands.