3. Memory Internals: Hash Tables & ZipLists
Inside the Global Dictionary
Under the hood, Redis does not organize data in columns or tables. It is structured as a global dictionary (or map) that links a unique string Key to a specific Value pointer. This dictionary is implemented as a hash table structure called dict. When you look up a key, Redis passes the key string through a hashing function called **SipHash**. SipHash outputs a numeric index representing a bucket in the hash table array. If two keys hash to the same bucket (a collision), Redis chains them together in a linked list. Because lookups resolve directly to array indexes, finding any key is an O(1) constant-time operation—it takes the same amount of time whether you have 10 keys or 100 million keys.
As you add more keys, the hash table's load factor increases, leading to more collisions and slower lookups. To prevent this, the hash table must resize (rehash). In a traditional database, rehashing locks the table while it creates a new, larger array and copies all elements over. On a database with millions of keys, this would block the event loop for several seconds. To solve this, Redis uses **Incremental Rehashing**. It maintains two internal hash tables: ht[0] (the active one) and ht[1] (the new, larger one). Every time a client executes a read or write command, Redis moves a small bucket of keys from ht[0] to ht[1]. A background task also migrates keys incrementally. Once the migration completes, the memory of ht[0] is freed, and pointers are swapped, ensuring zero latency spikes during resizing.
Dynamic Encodings: ZipLists and the Pointer Tax
On a 64-bit operating system, every pointer (memory address reference) consumes 8 bytes of space. If you create a collection of small strings (like a list of user IDs: [10, 11, 12]), a standard linked list requires storing the numbers plus the forward and backward pointers for each element. The pointer metadata can consume up to 80% of the allocated RAM, leaving only 20% for the actual data. This is known as the **Pointer Tax**. Since memory is expensive, Redis uses memory-saving encodings to store small collections.
The primary memory-saving structure is the **ZipList** (and in newer versions, listpack). A ZipList is a single, contiguous block of bytes in memory that stores elements back-to-back without using pointers. It includes a header specifying metadata and offsets, allowing traversal by calculating byte steps. Because elements are packed contiguously, ZipLists maximize CPU cache locality—when the CPU reads an element, it pre-fetches the surrounding bytes into L1/L2 cache lines, making operations incredibly fast. However, ZipLists have a limitation: inserting or deleting elements requires reallocating the entire contiguous memory block. If a ZipList grows too large, this memory reallocation becomes a performance bottleneck.
To balance memory efficiency and speed, Redis monitors the size of the structure. When a list, hash, or set exceeds configured limits (e.g., 512 elements or when any element exceeds 64 bytes), Redis dynamically and transparently recompiles the data structure, upgrading it to a standard Hash Table, Linked List, or SkipList. Developers can adjust these thresholds inside `redis.conf` (using parameters like hash-max-ziplist-entries) to optimize RAM footprints for their specific workloads.
// Auditing Key Memory Footprints and Encodings const Redis = require('ioredis'); const redis = new Redis({ host: '127.0.0.1', port: 6379 }); async function auditKeyMemory(key) { // Query the internal memory encoding representation const encoding = await redis.object('ENCODING', key); // Retrieve the actual memory size consumed by this key in bytes const bytesConsumed = await redis.memory('USAGE', key); console.log(`Key: "${key}"`); console.log(`-> Encoding: ${encoding}`); // e.g., 'ziplist', 'hashtable', 'raw', 'intset' console.log(`-> RAM Consumed: ${bytesConsumed} bytes`); return { encoding, bytesConsumed }; }
Knowledge Check
Ready to test your understanding of 3. Memory Internals: Hash Tables & ZipLists?