Dictionary is a data structure for storing key-value pair. Each key in a dictionary is unique and has a corresponding value. Redis implements its own dictionary and use it for hash key.

As a data structure in server side, dictionary must take memory into consideration. That’s the reason why resizing and rehashing are so significant.

The code analyzed in this post is based on 5.0.0


Each key-value pair is represented by dictEntry. The type of key is a void* and value is a union allowing more flexibility. Each key-value includes a next pointer for resolving key collision.

typedef struct dictEntry {
    void *key;
    union {
        void *val;
        uint64_t u64;
        int64_t s64;
        double d;
    } v;
    struct dictEntry *next;
} dictEntry;

dictht is our hash table structure, and every dictionary has two of this as we implementing incremental rehashing, for the old to the new table.

typedef struct dictType {
    uint64_t (*hashFunction)(const void *key);
    void *(*keyDup)(void *privdata, const void *key);
    void *(*valDup)(void *privdata, const void *obj);
    int (*keyCompare)(void *privdata, const void *key1, const void *key2);
    void (*keyDestructor)(void *privdata, void *key);
    void (*valDestructor)(void *privdata, void *obj);
} dictType;

typedef struct dictht {
    dictEntry **table;
    unsigned long size; // the number of buckets
    unsigned long sizemask; 
    unsigned long used; // how many buckets are occupied
} dictht;

typedef struct dict {
    dictType *type;
    void *privdata;
    dictht ht[2];
    long rehashidx; /* rehashing not in progress if rehashidx == -1 */
    unsigned long iterators; /* number of iterators currently running */
} dict;

Here is an example of dictionary that is not rehashing, the table pointer of ht[1] is NULL.

Create a Dictionary

For creating a dictionary, a new memory space should be allocated, then two dictht will be reset with their member variable 0 or NULL.

static void _dictReset(dictht *ht)
    ht->table = NULL;
    ht->size = 0;
    ht->sizemask = 0;
    ht->used = 0;

dict *dictCreate(dictType *type,
        void *privDataPtr)
    dict *d = zmalloc(sizeof(*d));

    return d;

int _dictInit(dict *d, dictType *type,
        void *privDataPtr)
    d->type = type;
    d->privdata = privDataPtr;
    d->rehashidx = -1;
    d->iterators = 0;
    return DICT_OK;

Incremental Rehashing

I’d like to introduce _dictRehashStep first so that you may not surprised when it is called in dictAddRaw, dictGenericDelete, dictFind and dictGetRandomKey.

_dictRehashStep performs just a step of rehashing, and only if there are no safe iterators bound to our hash table.

When we have iterators in the middle of a rehashing we can’t mess with the two hash tables otherwise some element can be missed or duplicated.

static void _dictRehashStep(dict *d) {
    if (d->iterators == 0) dictRehash(d,1);

This function is called by common lookup or update operations in the dictionary, that’s why it’s called incremental rehashing.

ht[0] and ht[1] is coexisting when rehashing, so two tables must be searched if you lookup. Inserting a new item is much easier, it should be done in ht[1] only.

After rehashing, ht[0] will be empty and reassigned to ht[1], the later will be reset.

int dictRehash(dict *d, int n) {
    int empty_visits = n*10; /* Max number of empty buckets to visit. */
    if (!dictIsRehashing(d)) return 0;

    while(n-- && d->ht[0].used != 0) {
        dictEntry *de, *nextde;

        /* Note that rehashidx can't overflow as we are sure there are more
         * elements because ht[0].used != 0 */
        assert(d->ht[0].size > (unsigned long)d->rehashidx);
        while(d->ht[0].table[d->rehashidx] == NULL) {
            if (--empty_visits == 0) return 1;
        de = d->ht[0].table[d->rehashidx];
        /* Move all the keys in this bucket from the old to the new hash HT */
        while(de) {
            uint64_t h;

            nextde = de->next;
            /* Get the index in the new hash table */
            h = dictHashKey(d, de->key) & d->ht[1].sizemask;
            de->next = d->ht[1].table[h];
            d->ht[1].table[h] = de;
            de = nextde;
        d->ht[0].table[d->rehashidx] = NULL;

    /* Check if we already rehashed the whole table... */
    if (d->ht[0].used == 0) {
        d->ht[0] = d->ht[1];
        d->rehashidx = -1;
        return 0;

    /* More to rehash... */
    return 1;
  1. Before rehashing
  2. Do rehashing
  3. After rehashing
  4. Reassigned hash table

Get a Key

dictFetchValue returns a value corresponding to the given key.

#define dictGetVal(he) ((he)->v.val)

void *dictFetchValue(dict *d, const void *key) {
    dictEntry *he;

    he = dictFind(d,key);
    return he ? dictGetVal(he) : NULL;

Hash function is binding with the type of dictionary. dictFind locates the index of the giving key by ANDing the hash value with sizemask.

#define dictHashKey(d, key) (d)->type->hashFunction(key)

dictEntry *dictFind(dict *d, const void *key)
    dictEntry *he;
    uint64_t h, idx, table;

    if (d->ht[0].used + d->ht[1].used == 0) return NULL; /* dict is empty */
    if (dictIsRehashing(d)) _dictRehashStep(d);
    h = dictHashKey(d, key);
    for (table = 0; table <= 1; table++) {
        idx = h & d->ht[table].sizemask;
        he = d->ht[table].table[idx];
        while(he) {
            if (key==he->key || dictCompareKeys(d, key, he->key))
                return he;
            he = he->next;
        if (!dictIsRehashing(d)) return NULL;
    return NULL;


Load factor is an important measure of how full the dictionary is allowed to get before its capacity is automatically increased. Redis always tries to keep USED/BUCKETS ratio near to <=1, which is done by resizing.

dictResize resize the table to the minimal size that contains all the elements. If the dictionary is rehashing indicated by rehashidx, resizing will be skipped.

The new size of dictionary is the next power of two that is larger than current size. For example, if the present size is 30, then the brand-new size will be 32.

Please note that the new allocated hash table is assigned to ht[0] or ht[1] depend on this is the first initialization or not. In other words, if it’s NOT initialized firstly, ht[1] will be prepared for incremental rehashing.

#define dictIsRehashing(d) ((d)->rehashidx != -1)

int dictResize(dict *d)
    int minimal;

    if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR;
    minimal = d->ht[0].used;
    if (minimal < DICT_HT_INITIAL_SIZE)
        minimal = DICT_HT_INITIAL_SIZE;
    return dictExpand(d, minimal);

int dictExpand(dict *d, unsigned long size)
    /* the size is invalid if it is smaller than the number of
     * elements already inside the hash table */
    if (dictIsRehashing(d) || d->ht[0].used > size)
        return DICT_ERR;

    dictht n; /* the new hash table */
    unsigned long realsize = _dictNextPower(size);

    /* Rehashing to the same table size is not useful. */
    if (realsize == d->ht[0].size) return DICT_ERR;

    /* Allocate the new hash table and initialize all pointers to NULL */
    n.size = realsize;
    n.sizemask = realsize-1;
    n.table = zcalloc(realsize*sizeof(dictEntry*));
    n.used = 0;

    /* Is this the first initialization? If so it's not really a rehashing
     * we just set the first hash table so that it can accept keys. */
    if (d->ht[0].table == NULL) {
        d->ht[0] = n;
        return DICT_OK;

    /* Prepare a second hash table for incremental rehashing */
    d->ht[1] = n;
    d->rehashidx = 0;
    return DICT_OK;

Add an Element

int dictAdd(dict *d, void *key, void *val)
    dictEntry *entry = dictAddRaw(d,key,NULL);

    if (!entry) return DICT_ERR;
    dictSetVal(d, entry, val);
    return DICT_OK;

dictAddRaw is the function for low level add and find. This function adds the entry but instead of setting a value returns the dictEntry structure to the user, that will make sure to fill the value field as he wishes.

dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing)
    long index;
    dictEntry *entry;
    dictht *ht;

    if (dictIsRehashing(d)) _dictRehashStep(d);

    /* Get the index of the new element, or -1 if
     * the element already exists. */
    if ((index = _dictKeyIndex(d, key, dictHashKey(d,key), existing)) == -1)
        return NULL;

    /* Allocate the memory and store the new entry.
     * Insert the element in top, with the assumption that in a database
     * system it is more likely that recently added entries are accessed
     * more frequently. */
    ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
    entry = zmalloc(sizeof(*entry));
    entry->next = ht->table[index];
    ht->table[index] = entry;

    /* Set the hash entry fields. */
    dictSetKey(d, entry, key);
    return entry;

The rehashing will not be interrupted when adding a new item, and the new element will be insert into ht[1] if the dictionary is rehashing.

Here we can also find that Redis use linked list to handle key collision, and the new key-value pair will become the new head.

Other high level functions that use dictAddRaw includes:

  • dictAddOrFind
  • dictReplace

Remove an element

int dictDelete(dict *ht, const void *key) {
    return dictGenericDelete(ht,key,0) ? DICT_OK : DICT_ERR;

dictGenericDelete is a helper function for dictDelete and also dictUnlink searching and removing an element. This function will operates ht[0] firstly, and then ht[1] if needed.

After finding the element to be deleted, dictGenericDelete will unlink it from the list, then release its memory.

static dictEntry *dictGenericDelete(dict *d, const void *key, int nofree) {
    uint64_t h, idx;
    dictEntry *he, *prevHe;
    int table;

    if (d->ht[0].used == 0 && d->ht[1].used == 0) return NULL;

    if (dictIsRehashing(d)) _dictRehashStep(d);
    h = dictHashKey(d, key);

    for (table = 0; table <= 1; table++) {
        idx = h & d->ht[table].sizemask;
        he = d->ht[table].table[idx];
        prevHe = NULL;
        while(he) {
            if (key==he->key || dictCompareKeys(d, key, he->key)) {
                /* Unlink the element from the list */
                if (prevHe)
                    prevHe->next = he->next;
                    d->ht[table].table[idx] = he->next;
                if (!nofree) {
                    dictFreeKey(d, he);
                    dictFreeVal(d, he);
                return he;
            prevHe = he;
            he = he->next;
        if (!dictIsRehashing(d)) break;
    return NULL; /* not found */

Return a Random Entry

This function involves two random() calls. Firstly, it is called for get the index of buckets, then address the index of list.

Actually, it is NOT strict random. Considering a dictionary with only 2 buckets, a bucket with only one elements in the list and the other bucket with 2 elements in the list. The element in former bucket has 50% probability to be gotten, the one in the later bucket only 25%.

dictEntry *dictGetRandomKey(dict *d)
    dictEntry *he, *orighe;
    unsigned long h;
    int listlen, listele;

    if (dictSize(d) == 0) return NULL;
    if (dictIsRehashing(d)) _dictRehashStep(d);
    if (dictIsRehashing(d)) {
        do {
            /* We are sure there are no elements in indexes from 0
             * to rehashidx-1 */
            h = d->rehashidx + (random() % (d->ht[0].size +
                                            d->ht[1].size -
            he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] :
        } while(he == NULL);
    } else {
        do {
            h = random() & d->ht[0].sizemask;
            he = d->ht[0].table[h];
        } while(he == NULL);

    /* Now we found a non empty bucket, but it is a linked
     * list and we need to get a random element from the list.
     * The only sane way to do so is counting the elements and
     * select a random index. */
    listlen = 0;
    orighe = he;
    while(he) {
        he = he->next;
    listele = random() % listlen;
    he = orighe;
    while(listele--) he = he->next;
    return he;