For par condicio: I worked at a similar optimization for Redis using different techniques (when I submitted the PR my colleagues informed me that ValKey and another Redis team was working at it, I was not aware: the amoung the three implementation we picked mine after extensive benchmarks) reaching memory savings that sometimes can be tens of percentage of less RAM compared to this ValKey optimization. So if you are exited for less memory for sorted Sets you should try both the implementations. We also got a lot more speed in many use cases compared to the skiplist.
It uses two techniques: B+ tree instead of sorted sets, but also the hash table side, the dictionary, is specialized for sorted sets and stores several items per allocation. The B+ tree leaves hold all the members and scores (also in clusters of many elements, 96 max or 4k: that's a big part of the win), rank lookup can skip many children because of meta data, which is part of the ability to go as fast or faster than Redis even if the memory is so much smaller. The hash table points to leaves in the B+ tree, does not have elements at all, and is heavily optimized to do just the minimum, a single byte tag is used as a speed optimization to optimized lookups in an optimistic way. Basically it is the sum of many different techniques conceived during the years and never adopted for fear of complexity (today no longer a problem), and newely discovered techniques.
P.S. I tried several variants with different representations, so this specific implementation is the Pareto frontier in speed/size of many, many attempts.
To be sure, you think these problems are tackleable now due to AI (my impression of your comment)? Or to advances in {yourself}/{else} in the ecosystem? How do you deal with managing the complexity now? Is it 'easier' because we as humans no longer need to do the decently complex step of writing most of it? Or iterations/... enabled by AI are able to reduce the long tails around experimenting/benchmarking with these kinds of complex structures?
Now this can be handled because of development speed but especially because the level of testing coverage you can get today with AI, and even static scrutiny, is immense. So before the frontier models of the latest months there was no way to do something like that without increasing the fragility of the implementation. Now it was possible to try tons of approaches, pick the best, iterate on testing a lot.
I have to say I was always on the fence about Bill Pugh (Mr Skiplist).
Some of his concurrency ideas were pretty good but Skip Lists were about the same time I was realizing that theoretical and practical design for performance had diverged and skip lists were a huge cache miss liability.
It didn't hurt that a few people I was aware had tried them had gone back to something else due to live performance analysis being negative or inconclusive (If you can't prove one thing is better than the other, you use the simpler one, and skiplists are not simple)
B+tree were designed around optimized IO in the era of magnetic storage, they're inherently cache-friendly. Skiplists are the same thing as a b+tree but the structure is inverted, which makes skiplists more to concurrent writer-friendly than b+trees. Different tradeoffs.
Yep. I’ve implemented b trees and skip lists a few times. I find skip lists to be a little easier to implement. But b trees seem to perform ~20% faster. I can’t think of any good reasons to use skip lists instead of b trees in high performance code.
Well, avoiding locks is one reason, since lockfree skiplists are fairly simple but lockfree b-trees essentially don’t exist. Concurrent b-trees using locks are pretty well-understood though and perform well.
The data structure is not a pure B+tree. They also strip common key prefix for node elements and store 4 bytes of remaining key data together with a pointer to the children to avoid key lookup in many cases. Plus they tune node sizes to match jemalloc allocation classes to minimize allocation overhead. I am not sure with such focus on cache friendliness the advantage of skip lists for writes still holds as they will still have more cache misses even on inserts.
If cache misses are a huge concern and we have a highly skewed distribution (mostly touching newer records), the splay tree starts to look interesting.
We don't like the O(n) worst case, but we really like that magical amortization property. There are some simple ways to avoid getting into a linear hot path.
Timsort and powersort both have O(k) operations which rely on k being approximately a cache line in size.
One of the last large dev blog entries for V8 was about how they got pointer compression to be performance neutral and that’s down to getting the translation down below the amortized cache hit penalty for 64 bit pointers. IIRC the JVM gets close to that as well.
Curious. Skiplists don't need back pointers. You can traverse a skiplist backward almost as fast as forward if you keep the "finger" around. The finger is the set of nodes from level-n down to level-0 that point as close to the goal node as possible without going beyond it. The ideal place to keep these nodes is on the stack. To traverse backwards, you do a conventional search for the starting node but every time you go down a pointer level, you push the last pointer on the stack first. Then back traversal becomes stack pops together with appropriate forward recursive calls when you pop back to a pointer that was too far to the left.
It's easier to convey the idea with code than english but I'm not typing the algorithm with my thumbs into my phone.
This is the standard LLM wall of irrelevant garbage that always makes me groan when I see it. There's a lot of words but it conveys very little useful information. This is exactly the type of thing that LLMs are terrible at and has negative ROI for human reviewers.
This is an LLM smell and, after having dealt with this sort of thing and realizing it’s usually low-signal high-noise, you end up ignoring this kind of thing outright.
I prefer to go straight to the code when reviewing. I’ll form my own opinion, then read the PR description, then do another, more detailed pass through the code.
>"fbtree combines the high fanout and contiguous storage of a conventional B+ tree with several optimizations designed for Valkey's workload and memory allocator, including feature-based lookups, SIMD searches, linked leaves, and fast paths for sequential inserts and pops. In a 5-million-member test, it reduced per-member memory overhead by 36–43%, saving up to 109 MB."
Nice!
At some point I'd love to see a "shoot-out" benchmark between different B+ Tree based database back-end engines, in terms of Insert, Update, Delete, (and simultaneous occurrences of all of the above) etc., but not just for a single thread -- across multiple threads, CPU's/GPU's, different cache hierarchies, etc., and for absolutely gargantuan amounts of data...
Which data structure and associated algorithms truly perform the best against a variety of truly heterogeneous (in this day and age, with all kinds of asymmetric hardware to choose from!) back-ends?
Anyway, we welcome Valkey to the list of contenders!
Like all things, it depends. If you don't need the latest and greatest features in upstream redis, and you don't want license headaches, Valkey is probably a good default. It's generally cheaper on hosting providers too - AWS will discount you ~20-35% for Valkey vs Redis.
I haven't checked the newest additions, there were some updates about adding login and encryption, but the latest innovation I use from redis is xstream, and almost all clones now support it.
And a moderate LLM subscription can readily generate a useful portion of this project overnight, which makes me concerned about their profitability in the long run.
I seem to remember it was xstream when it was first released. The commands all have a prefix X (XADD, XREAD, XTRIM) perhaps it got rebranded into just stream.
> if you modify an AGPL-licensed program and offer it as a service over a network, you are obligated to provide the source code of that modified program to anyone who interacts with it over the network
AGPL is in general banned in my company anywhere close to the developers. Too much risk we'd have to provide our trade secrets for everyone.
You might also want to try Lavik (https://github.com/eloqdata/lavik). I'm one of the authors. It's an open-source Redis-compatible server that uses NVMe storage while delivering in-memory-class performance. It's particularly fast for strings and hashes, though sorted sets aren't its strong suit yet.
Curious how rank queries (ZRANK, ZRANGE by index) perform after the switch. Skiplists made those cheap via span counters; does the B+tree keep per-node subtree counts to match?
From what I've seen on here many commenters didn't read the article, only the title (I've been guilty of this too). OP is maybe just adapting to HN culture.
Yes, that hardware is called "the memory cache". B-trees were invented because disk reads were very expensive. Now, memory cache fills are very expensive.
Binary trees have worse cache locality. The cost of accessing memory has grown so much compared to computation that supposedly slower "heavy weight" data structures are worth it now (as in the last 10-20 years).
I'm guessing their point is unlike binary trees which have two children per node, B trees can have as many children per node is best for cache locality/SIMD/etc. Which despite being "heavyweight" (wasted space if not all children per node are occupied) is faster in practice because it's cheaper to preload large unused blocks to cache rather than only access memory when it is needed.
Every node in a binary tree needs a value and two child pointers, though. That's asymptotically almost twice as many child pointers per value as a B-tree has.
The comment I replied to claimed that B-trees are "heavyweight" compared to binary trees. I thought it worth pointing out that the claim is only true for quite small trees.
A binary tree would be strictly worse than a skip list for cache line efficiency. Seeing as how skip lists were invented to improve on binary tree cache behavior.
Compute speed has been outpacing memory speed for decades now. So when you spend the cycles to fetch a cache line (64 bytes generally), you want to milk it for all its worth, to minimize time spent waiting on memory.
On a cold cache, you pay for each level of indirection, so you want to increase fan-out as much as possible. B-trees do that intrinsically.
We haven’t always treated memory as a series of block devices progressively closer to the core. I know Sun took a stab at providing NUMA memory regions that were physically closer to a bank of processors, with the notion that this would be straight working memory for those chips. I believe you need programming primitives to leverage this however and I don’t know what that looks like. But from DDR3 on we started doing something similar but a bit backward, and now even a full cache miss can result in an order of magnitude read/write speed variance depending on which bank of memory you’re writing to, and we still don’t have primitives to manage this. Just processor affinity.
I’m not convinced that dedicating 4GB to each processor isn’t the better solution. But it’s a chicken and egg because who would code to it? I think Rust could manage it via the borrow checker, but everyone else would be toast.
In my experience (embedded systems), most C++ developers aren't even aware of caches, let alone NUMA.
They just std::map and AoS and dynamic dispatch everywhere and then grumble "100% CPU usage" when troubleshooting performance problems with top. They might reach for a profiler once all hope is lost, but wouldn't know what to make of performance counters if I showed them some. People who have mechanical sympathy are the exception, not the norm.
Now, if I were to design a NUMA-aware programming model, I would probably expose paired processors and memory pools. Then, create threads assigned to processors and hand them an allocator, like how Zig manages memory allocations.
Sadly, a global heap (malloc/new) and nothing else is standard and that's one of the many, many legacies of 1970s Unix and POSIX we might not be able to get rid of... Most code nowadays either uses it directly or has bespoke hoops to let the user supply a different heap.
As a coding exercise I implemented a redis that utilized skiplists. I was excited to read this article. Turns out it's ai slop. Seriously people, stop it. This hurts to read.
For par condicio: I worked at a similar optimization for Redis using different techniques (when I submitted the PR my colleagues informed me that ValKey and another Redis team was working at it, I was not aware: the amoung the three implementation we picked mine after extensive benchmarks) reaching memory savings that sometimes can be tens of percentage of less RAM compared to this ValKey optimization. So if you are exited for less memory for sorted Sets you should try both the implementations. We also got a lot more speed in many use cases compared to the skiplist.
Is your implementation also a B+ tree? If so how does it use tens of percentage less memory? less metadata?
It uses two techniques: B+ tree instead of sorted sets, but also the hash table side, the dictionary, is specialized for sorted sets and stores several items per allocation. The B+ tree leaves hold all the members and scores (also in clusters of many elements, 96 max or 4k: that's a big part of the win), rank lookup can skip many children because of meta data, which is part of the ability to go as fast or faster than Redis even if the memory is so much smaller. The hash table points to leaves in the B+ tree, does not have elements at all, and is heavily optimized to do just the minimum, a single byte tag is used as a speed optimization to optimized lookups in an optimistic way. Basically it is the sum of many different techniques conceived during the years and never adopted for fear of complexity (today no longer a problem), and newely discovered techniques.
P.S. I tried several variants with different representations, so this specific implementation is the Pareto frontier in speed/size of many, many attempts.
EDIT: "b+ trees instead of skiplists" of course. Sorry, can't edit it anymore.
One (of many) questions,
To be sure, you think these problems are tackleable now due to AI (my impression of your comment)? Or to advances in {yourself}/{else} in the ecosystem? How do you deal with managing the complexity now? Is it 'easier' because we as humans no longer need to do the decently complex step of writing most of it? Or iterations/... enabled by AI are able to reduce the long tails around experimenting/benchmarking with these kinds of complex structures?
Now this can be handled because of development speed but especially because the level of testing coverage you can get today with AI, and even static scrutiny, is immense. So before the frontier models of the latest months there was no way to do something like that without increasing the fragility of the implementation. Now it was possible to try tons of approaches, pick the best, iterate on testing a lot.
Why do you think another option was chosen instead?
I have to say I was always on the fence about Bill Pugh (Mr Skiplist).
Some of his concurrency ideas were pretty good but Skip Lists were about the same time I was realizing that theoretical and practical design for performance had diverged and skip lists were a huge cache miss liability.
It didn't hurt that a few people I was aware had tried them had gone back to something else due to live performance analysis being negative or inconclusive (If you can't prove one thing is better than the other, you use the simpler one, and skiplists are not simple)
B+tree were designed around optimized IO in the era of magnetic storage, they're inherently cache-friendly. Skiplists are the same thing as a b+tree but the structure is inverted, which makes skiplists more to concurrent writer-friendly than b+trees. Different tradeoffs.
But more cache misses, due to the variable pointer length structure.
That cost varies from chip generation to generation, but it does seem to be the case that b trees win in more generations than they lose.
Yep. I’ve implemented b trees and skip lists a few times. I find skip lists to be a little easier to implement. But b trees seem to perform ~20% faster. I can’t think of any good reasons to use skip lists instead of b trees in high performance code.
Well, avoiding locks is one reason, since lockfree skiplists are fairly simple but lockfree b-trees essentially don’t exist. Concurrent b-trees using locks are pretty well-understood though and perform well.
The data structure is not a pure B+tree. They also strip common key prefix for node elements and store 4 bytes of remaining key data together with a pointer to the children to avoid key lookup in many cases. Plus they tune node sizes to match jemalloc allocation classes to minimize allocation overhead. I am not sure with such focus on cache friendliness the advantage of skip lists for writes still holds as they will still have more cache misses even on inserts.
If cache misses are a huge concern and we have a highly skewed distribution (mostly touching newer records), the splay tree starts to look interesting.
We don't like the O(n) worst case, but we really like that magical amortization property. There are some simple ways to avoid getting into a linear hot path.
Timsort and powersort both have O(k) operations which rely on k being approximately a cache line in size.
One of the last large dev blog entries for V8 was about how they got pointer compression to be performance neutral and that’s down to getting the translation down below the amortized cache hit penalty for 64 bit pointers. IIRC the JVM gets close to that as well.
> skiplists are not simple
Can you please clarify: Simpler in operation or simple in implementation? Or neither/both?
> Every node carries a backward pointer
Curious. Skiplists don't need back pointers. You can traverse a skiplist backward almost as fast as forward if you keep the "finger" around. The finger is the set of nodes from level-n down to level-0 that point as close to the goal node as possible without going beyond it. The ideal place to keep these nodes is on the stack. To traverse backwards, you do a conventional search for the starting node but every time you go down a pointer level, you push the last pointer on the stack first. Then back traversal becomes stack pops together with appropriate forward recursive calls when you pop back to a pointer that was too far to the left.
It's easier to convey the idea with code than english but I'm not typing the algorithm with my thumbs into my phone.
Tangentially related, the PR sections for the final PR in this feature is quite nice[0].
There is a reviewing guide with suggested reading order, clear design decisions, and scope boundaries for what is intentionally not included.
This is the type of thing LLMs are very good at and high ROI for human reviewers.
[0]: https://github.com/valkey-io/valkey/pull/4206
You really think that LLMs are “very good” at producing useful PR descriptions? I have had a very different experience.
OMG, I hate the LLM PR descriptions, the comments, the docstrings - anything to be read by a human that isn't code.
Have you read the code though?
The code isn't really much better, having reviewed a decent bit of it myself.
This is the standard LLM wall of irrelevant garbage that always makes me groan when I see it. There's a lot of words but it conveys very little useful information. This is exactly the type of thing that LLMs are terrible at and has negative ROI for human reviewers.
Starting with an unnecessary list of touched files before the Reviewing Guide. Talk about burying the lede!
Not sure about the name reviewing guide, but I do like the contents. Then again I know nothing about code base.
The summaries are often multiple times the size of the actual diff. I guess they’re useful if you can’t code.
This is an LLM smell and, after having dealt with this sort of thing and realizing it’s usually low-signal high-noise, you end up ignoring this kind of thing outright.
I prefer to go straight to the code when reviewing. I’ll form my own opinion, then read the PR description, then do another, more detailed pass through the code.
The snr of that file is very very low.
Dragonfly lead with this idea in 2024:
https://www.dragonflydb.io/blog/dragonfly-new-sorted-set
>"fbtree combines the high fanout and contiguous storage of a conventional B+ tree with several optimizations designed for Valkey's workload and memory allocator, including feature-based lookups, SIMD searches, linked leaves, and fast paths for sequential inserts and pops. In a 5-million-member test, it reduced per-member memory overhead by 36–43%, saving up to 109 MB."
Nice!
At some point I'd love to see a "shoot-out" benchmark between different B+ Tree based database back-end engines, in terms of Insert, Update, Delete, (and simultaneous occurrences of all of the above) etc., but not just for a single thread -- across multiple threads, CPU's/GPU's, different cache hierarchies, etc., and for absolutely gargantuan amounts of data...
Which data structure and associated algorithms truly perform the best against a variety of truly heterogeneous (in this day and age, with all kinds of asymmetric hardware to choose from!) back-ends?
Anyway, we welcome Valkey to the list of contenders!
Is valkey the recommended redis alternative these days ?
Like all things, it depends. If you don't need the latest and greatest features in upstream redis, and you don't want license headaches, Valkey is probably a good default. It's generally cheaper on hosting providers too - AWS will discount you ~20-35% for Valkey vs Redis.
I haven't checked the newest additions, there were some updates about adding login and encryption, but the latest innovation I use from redis is xstream, and almost all clones now support it.
And a moderate LLM subscription can readily generate a useful portion of this project overnight, which makes me concerned about their profitability in the long run.
what even is `xstream` ? is that a typo for `stream` ?
I seem to remember it was xstream when it was first released. The commands all have a prefix X (XADD, XREAD, XTRIM) perhaps it got rebranded into just stream.
Redis is available under the AGPL which is not a headache for most people.
Until they close it down again. Why would you trust someone after they've already screwed you over?
You do not have to trust them. They cannot revoke the license, and it can be forked again.
But it's a red flag for any company.
> if you modify an AGPL-licensed program and offer it as a service over a network, you are obligated to provide the source code of that modified program to anyone who interacts with it over the network
AGPL is in general banned in my company anywhere close to the developers. Too much risk we'd have to provide our trade secrets for everyone.
For software companies, especially big ones.
Yes
DragonflyDB has had this for years. You might disagree with the licensing choice but the technology is just better IMO.
(Disclosure, worked for them 3 years ago for a few months)
You might also want to try Lavik (https://github.com/eloqdata/lavik). I'm one of the authors. It's an open-source Redis-compatible server that uses NVMe storage while delivering in-memory-class performance. It's particularly fast for strings and hashes, though sorted sets aren't its strong suit yet.
For what it's worth, Fedora replaced redis with valkey about two years ago (https://fedoraproject.org/wiki/Changes/Replace_Redis_With_Va...).
Never could understand why sorted sets were implemented with skiplists instead of B+ trees in the first place.
I've long since moved to the MultiQueue algorithm for CPQs, seems like SkipList has vanishingly few use cases now...
Thanks Bill Pugh for skiplists, worked great for so long. Go terps. https://dl.acm.org/doi/10.1145/78973.78977
Curious how rank queries (ZRANK, ZRANGE by index) perform after the switch. Skiplists made those cheap via span counters; does the B+tree keep per-node subtree counts to match?
Redis historically used a skiplist to keep a sorted index. Valkey showed its inefficient and slow on modern hardware, migrating to a B+ tree instead.
Is this AI? Why do we need a summary of the actual article in a comment?
The actual article is AI too so this is just saving you time.
https://github.com/valkey-io/valkey-io.github.io/pull/665/co...
The PR for the article. I'm not convinced it's AI, but I didn't do a deep dive on the commit tree just poked around a bit.
From what I've seen on here many commenters didn't read the article, only the title (I've been guilty of this too). OP is maybe just adapting to HN culture.
There aren't many commenters at the time you posted this. Which makes this conversation feel even more artificial...
I meant in general on this site. Dislike the insinuation that I'm generative AI.
Oh it's been whole weeks since I was accused of being AI.
...sorry.
It all ends up back at B trees. Why does it always end up back at B trees?
At this point have we optimized hardware to assume B trees in a sort of self-fulfilling prophesy?
Yes, that hardware is called "the memory cache". B-trees were invented because disk reads were very expensive. Now, memory cache fills are very expensive.
My point, Mr Edge Lord, is that B Trees were invented in 1970 and the best we have managed since is either short-lived, or a refinement of B trees.
Binary trees have worse cache locality. The cost of accessing memory has grown so much compared to computation that supposedly slower "heavy weight" data structures are worth it now (as in the last 10-20 years).
A b-tree isn't a binary tree. B doesn't officially stand for binary either, see History[0].
[0] https://en.wikipedia.org/wiki/B-tree
I'm guessing their point is unlike binary trees which have two children per node, B trees can have as many children per node is best for cache locality/SIMD/etc. Which despite being "heavyweight" (wasted space if not all children per node are occupied) is faster in practice because it's cheaper to preload large unused blocks to cache rather than only access memory when it is needed.
Every node in a binary tree needs a value and two child pointers, though. That's asymptotically almost twice as many child pointers per value as a B-tree has.
It’s a good thing this article isn’t about binary trees then.
The comment I replied to claimed that B-trees are "heavyweight" compared to binary trees. I thought it worth pointing out that the claim is only true for quite small trees.
A binary tree would be strictly worse than a skip list for cache line efficiency. Seeing as how skip lists were invented to improve on binary tree cache behavior.
B trees are more friendly to being cache oblivious
Compute speed has been outpacing memory speed for decades now. So when you spend the cycles to fetch a cache line (64 bytes generally), you want to milk it for all its worth, to minimize time spent waiting on memory.
On a cold cache, you pay for each level of indirection, so you want to increase fan-out as much as possible. B-trees do that intrinsically.
Can’t imagine valley is going to have a cold cache. Cache eviction on the other hand…
We haven’t always treated memory as a series of block devices progressively closer to the core. I know Sun took a stab at providing NUMA memory regions that were physically closer to a bank of processors, with the notion that this would be straight working memory for those chips. I believe you need programming primitives to leverage this however and I don’t know what that looks like. But from DDR3 on we started doing something similar but a bit backward, and now even a full cache miss can result in an order of magnitude read/write speed variance depending on which bank of memory you’re writing to, and we still don’t have primitives to manage this. Just processor affinity.
I’m not convinced that dedicating 4GB to each processor isn’t the better solution. But it’s a chicken and egg because who would code to it? I think Rust could manage it via the borrow checker, but everyone else would be toast.
In my experience (embedded systems), most C++ developers aren't even aware of caches, let alone NUMA.
They just std::map and AoS and dynamic dispatch everywhere and then grumble "100% CPU usage" when troubleshooting performance problems with top. They might reach for a profiler once all hope is lost, but wouldn't know what to make of performance counters if I showed them some. People who have mechanical sympathy are the exception, not the norm.
Now, if I were to design a NUMA-aware programming model, I would probably expose paired processors and memory pools. Then, create threads assigned to processors and hand them an allocator, like how Zig manages memory allocations.
Sadly, a global heap (malloc/new) and nothing else is standard and that's one of the many, many legacies of 1970s Unix and POSIX we might not be able to get rid of... Most code nowadays either uses it directly or has bespoke hoops to let the user supply a different heap.
- valkey vs redis vs dragonfly 2027?
Do they provide their benchmark code?
As a coding exercise I implemented a redis that utilized skiplists. I was excited to read this article. Turns out it's ai slop. Seriously people, stop it. This hurts to read.
The PR (https://github.com/valkey-io/valkey/pull/4206) is much better.
Can I convince you to post this as a top level?