Encodings flip under you
Each Redis type has multiple internal encodings chosen by size, and crossing a threshold silently rewrites memory layout and operation cost.
One loop, one command at a time. So the cost of a single command — and therefore everyone else's wait — depends on the SHAPE of the value the loop is touching.
Scene 03
Encodings flip under you
- Watch
- Try it
- Predict
- Capture
Watch a hash grow one field at a time. It starts as a single contiguous listpack — one allocation, ideal cache locality. When the entry count crosses the threshold, the layout morphs into a chained hashtable.
Highlighted lines are the ones running in the diagram right now.
def hset(key, field, value):h = lookupOrCreateHash(key)if h.encoding == 'listpack':# both knobs gate the encoding; either trips the flipif (h.entryCount + 1 > hash_max_listpack_entriesor len(value) > hash_max_listpack_value):tryConvertEncoding(h) # listpack -> hashtableif h.encoding == 'listpack':listpackUpsert(h.lp, field, value)else:dictUpsert(h.ht, field, value)h.entryCount += 1
def tryConvertEncoding(h):ht = dictCreate()# walk the contiguous listpack cell by cellfor field, value in listpackIter(h.lp):dictAdd(ht, field, value)listpackFree(h.lp)h.lp = Noneh.ht = hth.encoding = 'hashtable' # one-way; never reset on HDEL
def hget(key, field):h = lookupHash(key)if h is None: return Noneif h.encoding == 'listpack':# contiguous strip, no index — walk every cellfor f, v in listpackIter(h.lp):if f == field: return vreturn Noneelse:# bucket lookup, pointer chase, ~3x memoryreturn dictFetch(h.ht, field)
Where this sits in Build Redis
Scene 03 of 10, in the The loop act — One thread, one command — and the encoding under it.. Listpack ↔ hashtable, intset ↔ hashtable, embstr ↔ raw — crossing a threshold silently rewrites memory and op-cost.
Up next. Persistence — those carefully encoded bytes only live in RAM. Persistence is how Redis turns RAM into something that can survive a crash.
Designs that use this
- URL ShortenerShorten a long URL. Read-heavy. Don't collide.
- Distributed Rate LimiterEnforce a per-key request limit across a fleet of enforcers — accurately, in under a millisecond, without becoming the outage.
- Twitter / X TimelinePush or pull? Both. The canonical fanout problem.
- Uber / Lyft — Match Drivers and RidersMatch a rider to the closest acceptable driver in under 3 s. Geohash, S2, surge.