DEV Community

Chen Yuan
Chen Yuan

Posted on Originally published at dispatch-blog.hashnode.dev

Valkey Killed the Skiplist: What a 61-Way B+ Tree Buys Your Sorted Sets

For most of two decades, one data structure owned a strangely specific job: keeping a sorted set sorted inside Redis, and later Valkey. Ask how ZADD, ZRANGE, or ZRANK found their way through millions of members, and the answer was always the same probabilistic tower of linked nodes. In Valkey 9.2, currently in release-candidate testing, that answer changes. The skiplist backing large sorted sets is gone, replaced by a high-fanout B+ tree variant called fbtree, short for Feature B+ Tree.

The official numbers attached to the swap are hard to ignore. In a five-million-member test with 20-byte members, per-member index overhead fell from 50.3 bytes to 28.5 bytes on sequential inserts, a 43 percent reduction worth roughly 109 MB on that single key. Random inserts still saved 36 percent. Throughput on ZADD score updates rose 105 percent, and ZREM climbed 76 percent. Yet the more interesting story is not that a B+ tree beat a skiplist. It is why the skiplist was ever competitive, why it quietly stopped being competitive on modern hardware, and what fbtree's design says about where in-memory databases are heading.

The hidden tax in a sorted set

A large sorted set in Valkey is really two structures sharing one key. A hashtable maps each member to its score for O(1) point lookups, and an ordered index answers rank and range questions. Small sets never touch either one: below the listpack threshold, members live sequentially in one compact contiguous block, which is why the 9.2 change leaves small sets completely untouched.

Once a set outgrows that threshold, the old design promoted it to a skiplist. The skiplist's elegance is that it needs no rebalancing: each node flips a weighted coin to decide how many levels it joins, and the expected structure stays balanced forever. The bill arrives in memory. Every node stores one element, and every node is its own allocation, scattered wherever the heap placed it. The official design notes put the overhead at roughly 37 bytes per node before the member string itself: an 8-byte backward pointer, an average of 1.33 extra levels at 16 bytes each for the forward pointer and span value, plus the 8-byte score.

Here is that arithmetic in one place:

# Skiplist per-node index overhead, from the Valkey 9.2 design notes
backward_ptr = 8          # bytes
avg_extra_levels = 1.33   # 25% chance of gaining each level
per_level = 8 + 8         # forward pointer + span value
score = 8

overhead = backward_ptr + avg_extra_levels * per_level + score
print(overhead)           # about 37 bytes, member string not included

# On a 5,000,000-member set that is ~185 MB of pure index plumbing.
print(overhead * 5_000_000 / 1024 / 1024)
Enter fullscreen mode Exit fullscreen mode

For a 20-byte member, the index describing the ordering cost nearly twice the data being ordered. That is the tax the new structure was built to repeal.

Why the skiplist lost

Raw bytes are only half the problem. The other half is latency hiding inside every lookup. Modern CPUs serve L1 cache hits in about a nanosecond, while a trip to DRAM costs on the order of a hundred. Skiplist traversal is a chain of dependent reads: you cannot know which node to visit next until the current one arrives from memory, and each node lives in an unpredictable location. The probabilistic leveling that makes inserts cheap also gives the structure an effective branching factor of about four, so a large set means many levels of waiting.

The 2025 study the Valkey team cites, "Bridging Cache-Friendliness and Concurrency," measured traditional skiplists at roughly 2.4 to 4.8 times more cache misses than a comparable B-tree, with two to eight times lower throughput across its tested workloads. Those are different implementations than Valkey's, but the mechanism transfers directly. On Hacker News, where the announcement drew 177 points, long-time practitioners were blunt: skip lists were always a cache-miss liability on modern hardware, an idea from an era when theoretical and practical performance had not yet diverged this far.

A B+ tree attacks both halves at once. Packing many entries per node slashes per-member pointer overhead, and reading one contiguous node replaces a chain of dependent fetches with one fetch plus cheap scanning inside a few cache lines, which hardware prefetchers handle well.

fbtree: a B+ tree shaped by the allocator

fbtree keeps entries sorted in fixed-size nodes with a fanout of 61. That number is not arbitrary. Leaf and inner nodes are sized to land exactly on jemalloc allocation classes, so a 512-byte leaf holds up to 61 value pointers with no slack wasted to the allocator's rounding. On supported 32-bit builds, the inner node rounds up to the 1280-byte class instead. Sixty-one members now share a single allocation instead of sixty-one separate ones.

The second decision is what a leaf actually stores. Rather than keeping the score and member apart and chasing pointers between them, fbtree packs them into one value: the normalized 8-byte score followed immediately by the member bytes. Everything a comparison needs sits in one place, and one more layer of indirection disappears.

The shallower shape matters as much as the denser nodes. Both structures are O(log n) in theory, but a tree that branches 61 ways reaches five million members in about three levels, while the skiplist's branching factor of four needs far more hops, each one a potential dependent fetch.

Feature bytes: SIMD at the routing layer

The design's namesake trick lives in the inner nodes. In a B+ tree keyed by variable-length strings, descending means comparing the lookup key against each child's anchor, the largest member stored beneath that child, and reading those anchor strings costs memory fetches of its own.

fbtree stores each anchor alongside a small four-byte "feature," and because sibling anchors usually share a common prefix, that prefix is factored out and stored once. The four feature bytes per child are then comparable in parallel with SIMD instructions, often identifying the correct child before its node is ever fetched. When the features collide, they still narrow the range that needs a full binary search. It is a Bloom-filter-like sketch, except the sketch exists to steer traversal rather than to answer membership.

The remaining optimizations target specific commands. Leaves are doubly linked, so ZRANGE walks sideways from leaf to leaf instead of climbing back up, and while the CPU works through up to 61 entries in one leaf, the next leaf can already be on its way. The leftmost and rightmost leaves are cached, keeping ZPOPMIN and append-style inserts at O(1) parity with the skiplist rather than regressing to O(log n). Range deletions remove a contiguous run without rebuilding the surrounding structure.

The benchmark table, with its asterisks

The throughput numbers deserve both the headline treatment and the fine print. Measured on a Graviton3 c7g.metal with 64 cores, nine I/O threads, a pipeline depth of ten, and a three-million-member set, repeated five times with confidence intervals at or below two percent for every command except ZRANDMEMBER:

Command Workload Throughput change
ZADD score update, all hits +105%
ZREM 50/50 random add/remove +76%
ZCOUNT score-range count +27%
ZRANK point rank lookup +19%
ZRANGE 100-element rank scan +6%
ZRANDMEMBER 100 random samples +2%
ZSCORE point score lookup +2%
ZRANGEBYSCORE 100-element score scan +1%
ZPOPMIN pop min plus append roughly 0%

The pattern is the point. ZADD and ZREM reposition elements inside the ordered index, so they collect the full benefit of the shallower tree and fewer pointer updates. Range commands gain less because once traversal gets cheap, producing and returning elements dominates the cost. ZSCORE and ZRANDMEMBER barely move for a simpler reason: they answered through the hashtable all along and never touched the skiplist.

Two asterisks are worth repeating verbatim. The benchmarks were measured on the pull request's working branch, oi/pr3-fbtree-v2, and were not rerun on the merged commit. And the memory savings are per member, not per byte stored, so the relative win is largest for sets of many small members and shrinks as members grow. The underlying change itself is substantial: PR #4206, merged in August 2026, touched 36 files with over 9,100 additions, and reviewers on Hacker News singled out its unusually explicit review guide and scope boundaries.

What actually changes on your servers

Functionally, nothing. Every sorted set command keeps its name, arguments, and behavior, which is exactly the contract an internal representation swap should honor. The one visible difference is introspection:

127.0.0.1:6379> ZADD bigz 1 "member-a"
(integer) 1
127.0.0.1:6379> OBJECT ENCODING bigz
"listpack"

# ... after the set crosses the listpack threshold on 9.2:

127.0.0.1:6379> OBJECT ENCODING bigz
"btree"
Enter fullscreen mode Exit fullscreen mode

If your monitoring, tests, or tooling assert on the literal string "skiplist," that is the one place to update before upgrading. Small sets are unaffected in both directions: under the defaults shipped in valkey.conf, zset-max-listpack-entries 128 and zset-max-listpack-value 64, they were listpacks before and they stay listpacks now. Those thresholds remain the knobs to tune only after measuring your real dataset, as the config file itself warns.

How to test it before GA

Valkey 9.2 is still a release candidate, and the team is explicitly asking for workload testing before general availability, especially from operators whose traffic leans on ZADD, ZREM, ZRANK, or ZCOUNT against large sets. A meaningful before-and-after check needs only three ingredients: your member size distribution, your insert order, and steady-state memory readings.

# Fill a large set with pipelined random-score writes
valkey-benchmark -n 1000000 -P 10 -r 1000000 \
  ZADD bigz __rand_int__ member:__rand_int__

# Then compare index cost across builds with:
127.0.0.1:6379> MEMORY USAGE bigz
(integer) ...
127.0.0.1:6379> OBJECT ENCODING bigz
"btree"
Enter fullscreen mode Exit fullscreen mode

Divide MEMORY USAGE by ZCARD on each build and compare against the official deltas: 50.3 bytes per member on the skiplist build, 28.5 on fbtree with sequential inserts, 32.0 with random order. If your members are larger than 20 bytes, expect the relative saving to shrink accordingly, and if your access pattern is update-heavy, watch ZADD and ZREM latency rather than range scans. Report what you find: the whole point of the RC window is surfacing regressions while they are still cheap to fix.

The pattern behind the swap

The skiplist was never a bad choice. It was a good answer to a 1990s hardware question, when a pointer chase cost roughly what an arithmetic operation cost and simplicity of concurrent design was worth real money. Hardware moved, and the cost model inverted: computation is nearly free, while waiting on memory dominates everything. The Valkey change is one more entry in a long migration, from pointer-heavy structures toward flat, wide, cache-resident layouts, the same migration that rewrote hash tables, database buffer managers, and language runtimes over the past decade.

What makes this instance worth studying is the discipline around it. The team benchmarked through the full server rather than in a microbenchmark vacuum, added optimizations until fbtree matched or beat the skiplist on every tested command, kept the operator-visible surface unchanged, and shipped the change behind a release candidate with an explicit request for adversarial workloads. When your fastest path is the one nobody notices, that is what a mature infrastructure project looks like.


Originally published on Dispatch.

Top comments (0)