Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blog post about new hash table (WIP) #195

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
203 changes: 203 additions & 0 deletions content/blog/2025-03-20-new-hash-table.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
+++
title= "A new hash table"
date= 2025-03-20 00:00:00
description= "Designing a state-of-the art hash table implementation"
authors= [ "zuiderkwast", "SoftlyRaining"]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yall need author pages, or it won't render correctly.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll just blank out authors then and write my name in the bottom of the article text instead. 😆

Suggested change
authors= [ "zuiderkwast", "SoftlyRaining"]
authors= []

+++

Valkey is essentially a giant hash table attached to the network. A hash table
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably want a better hook. We can talk about how many caching workloads are bound on storing data, so being able to to store more data allows you to reduce the size of your clusters.

is the data structure that maps keys to values. When optimizing for latency, CPU
and memory usage, it's natural to look at the hash table internals. By replacing
the hash table with a different implementation, we have managed to reduce the
memory usage by roughly 20 bytes per key-value pair and improve the latency and
CPU usage by rougly 10% for instances without I/O threading.

Results
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A typical blog would leave the results till the end, and talk about the constraints up front.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just move the Results section to the end?

I'll keep brief text in the abstract above "we have managed to reduce the memory usage by roughly 20 bytes per key-value pair and improve the latency and CPU usage by rougly 10% for instances without I/O threading"?

-------

Memory usage for keys of length N and value of length M bytes. TBD.

| Version | Memory usage per key |
|------------|------------------------|
| Valkey 7.2 | ? bytes |
| Valkey 8.0 | ? bytes |
| Valkey 8.1 | ? bytes |

Comment on lines +18 to +25
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@SoftlyRaining Are you working on generating these numbers?

The benchmarks below were run using a key size of N and a value size of M bytes, without pipelining.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add something for set/zset/hash and see if we get even more performance and memory savings since those datatypes are hashtables inside of a hashtable. :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes... Feel free to replace these tables with some completely different tests.

There's a fixed overhead for the key and then per field-value. Still I'd like to see a table of memory savings per element/field/etc. for these types.

I want to do hash value embedding (to save the value pointer and an extra allocation) and Ran noticed that our embedded sds (key and field) are sds8 even when they should be sds5, so we could save a two more bytes for those. That's because they're copied from an EMBSTR robj value and those are always sds8. I have some idea to fix that too though.


| Command | Valkey 7.2 | Valkey 8.0 | Valkey 8.1 |
|-------------------------|------------|------------|------------|
| SET | Xµs, Y QPS | ? | ? |
| GET | Xµs, Y QPS | ? | ? |
| ... | ... | ? | ? |

The benchmark was run on an xxxx using yyyy, without I/O threads.

Background
----------

The slowest operation when looking up a key-value pair is by far reading from
the main RAM memory. A key point when optimizing a hash table is therefore to
make sure we have as few memory accesses as possible. Ideally, the memory
reading is already in the CPU cache, which is much faster memory that belong to
the CPU.
Comment on lines +39 to +43
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this background is OK, but I think it would be beneficial to show the previous implementation, and then explain how we iterated on it to the new one. Then it becomes easier to show the memory accesses that are getting removed. You already show the previous design later on, so we can probably move it earlier.

A good general framing is, show the current state (the dict), highlight the gaps (lots of memory accesses and allocations), introduce a new concept that solves that (cache friendly), then discuss the solution. Most of that content is here, just needs a little bit of moving around.


When optimizing for memory usage, we also want to minimize the number of
allocation and pointers between them, because a pointer is 8 bytes in a 64-bit
system. If we save one pointer per key-value pair, for 100 million keys that's
almost a gigabyte.

When a computer loads some data from the main memory into the CPU cache, it does
so in blocks of one cache line. The cache-line size is 64 bytes on almost all
modern hardware. Recent work on hash tables, such as "Swiss tables", are highly
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably link the swiss table design notes or youtube video here.

optimized for cache lines. When looking up a key, if it's not found where you
Comment on lines +52 to +53
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
modern hardware. Recent work on hash tables, such as "Swiss tables", are highly
optimized for cache lines. When looking up a key, if it's not found where you
modern hardware. Recent work on hash tables, such as "Swiss tables", are highly
optimized to store and access data within a single cache line. When looking up a key, if it's not found where you

first look for it (due to a hash collission), then it should ideally be found
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
first look for it (due to a hash collission), then it should ideally be found
first look for it (due to a hash collision), then it should ideally be found

First introduction of concepts such as hash collisions. I mentioned earlier it would be helpful to give an overview of the current design, probably can walk through these concepts.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it's hard to know how much of computer science lecture we have to give. We'll have to assume some basic knowledge of what a hash table is, right?

within the same cache line. If it is, then it can be found very fast once this
cache line has been loaded into the CPU cache.

Required features
-----------------

Why not use an open-source state-of-the-art hash table implementation such as
Swiss tables? The answer is that we require some specific features, apart from
the basic operations like add, lookup, replace, delete:
Comment on lines +61 to +63

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another reason: Swiss table is very fast, but it stores the elements directly in a contiguous array, which requires that the elements all be the same size. Because our elements vary in size, we had to choose a different design - we chose cache-line sized buckets with element pointers. (This idea was mentioned at the end of the swiss table talk - up to you if you want to make that reference though.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, you can store pointers in a Swiss table, just like how we store pointers in our bucket layout. The pointers are the fixed-size elements, no?

I don't think it allows a custom key-value entry design like we do though. It can be either a set or a map (key and value) IIUC.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could have picked an off-the-shelf implementation even if we couldn't embed key and value the way we do, as long as would be better than dict. It's good to use a battle-tested ready-to-use one too. It's easier to get it right, and less work... I think scan and incremental rehashing were clearly blockers though.


* Incremental rehashing, so that when the hashtable is full, we don't freeze the
server while the table is being resized.

* Scan, a way to iterate over the hash table even if the hash table is resized
between the iterations. This is important to keep supporting the
[SCAN](/commands/scan/) command.

* Random element sampling, for commands like [RANDOMKEY](/commands/randomkey/).

These are not standard features, so we could not pick an off-the-shelf hash
table. We had to design one ourselves.

The hash table used until Valkey 8.0, called "dict", has the following memory
layout:

```
+---------+
| dict | table
+---------+ +-----+-----+-----+-----+-----+-----+-----
| table 0 --------->| x | x | x | x | x | x | ...
| table 1 | +-----+-----+--|--+-----+-----+-----+-----
+---------+ |
v
+-----------+ +-------+
| dictEntry | .--->| "FOO" |
+-----------+ / +-------+
| key -----'
| | +-------------------+
| value ----------->| serverObject |
| | +-------------------+
| next | | type, encoding, |
+-----|-----+ | ref-counter, etc. |
| | "BAR" (embedded) |
v +-------------------+
+-----------+
| dictEntry |
+-----------+
| key |
| value |
| next |
+-----|-----+
|
v
...
```

The dict has two tables, called "table 0" and "table 1". Usually only one
exists, but both are used when incremental rehashing is in progress.

It is a chained hash table, so if multiple keys are hashed to the same slot in
the table, their key-value entries form a linked list. That's what the "next"
pointer in the dictEntry is for.

To lookup a key "FOO" and access the value "BAR", Valkey still had to read from
memory four times. If there is a hash collission, it has to follow two more
pointers for each hash collission and thus read twice more from memory (the key
and the next pointer).

In Valkey 8.0, an optimization was made to embed the key ("FOO" in the drawing
above) in the dictEntry, eliminating one pointer and one memory access.
Comment on lines +118 to +124
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have a full blog post dedicated to embedding the key, so let's just start with the state of the world in 7.2.


Design
------

In the new hash table designed for Valkey 8.1, the table consists of buckets of
64 bytes, one cache line. Each bucket can store up to seven elements. Keys that
map to the same bucket are all stored in the same bucket. The bucket also has a
metadata section which contains a one byte secondary hash for each key. This is
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to explain a bit about what the secondary hash is doing here, it's not really explained what it is or how it solve hash collisions.

I'm not sure we did any testing, but this is also really good for caching workloads, since we save a memory access most of the time when there is a cache miss. A common cache hit rate is like 80%, so that 20% gets a nice speed boost as well.

used for quickly eliminating hash collissions when looking up a key. In this
way, we can avoid comparing the key for a mismatching key, except once in 256.

We eliminated the dictEntry and instead embed key and value in the serverObject,
along with other metadata for the key.

```
+-----------+
| hashtable | bucket bucket bucket
+-----------+ +-----------------+-----------------+-----------------+-----
| table 0 -------->| m x x x x x x x | m x x x x x x x | m x x x x x x x | ...
| table 1 | +-----------------+-----|-----------+-----------------+-----
+-----------+ |
v
+------------------------+
| serverObject |
+------------------------+
| type, encoding, |
| ref-counter, etc. |
| "FOO" (embedded key) |
| "BAR" (embedded value) |
+------------------------+
```

Assuming the hashtable and the table are already in the CPU cache, looking up
key-value entry now requires only two memory lookups: The bucket and the
serverObject. If there is a hash collission, the object we're looking for is
most likely in the same bucket, so no extra memory access is required.

If a bucket becomes full, the last element slots in the bucket is replaced by a
pointer to a child bucket. A child bucket has the same layout as a regular
bucket, but it's a separate allocation. The length of these bucket chains are
not bounded, but long chains are very rare as long as keys are well distributed
by the hashing function. Most of the
keys are stored in top-level buckets.

```
+-----------+
| hashtable | bucket bucket bucket
+-----------+ +-----------------+-----------------+-----------------+-----
| table 0 -------->| m x x x x x x x | m x x x x x x c | m x x x x x x x | ...
| table 1 | +-----------------+---------------|-+-----------------+-----
+-----------+ |
Child bucket v
+-----------------+
| m x x x x x x c |
+---------------|-+
|
Child bucket v
+-----------------+
| m x x x x x x x |
+-----------------+
```

Hashes, sets and sorted sets
----------------------------

The nested data types Hashes, Sets and Sorted sets also make use of the new hash
table. The memory usage is reduced by roughly 10-20 bytes per entry. Memory and
latency/throughput results are WIP.

Iterator prefetching
--------------------
Comment on lines +194 to +195
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is technically a separate point. It addresses some of the content of the blog, but ultimately feels a bit random at the end. Maybe we drop it and write another followup blog on memory prefetching?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could include it in the 8.1 overview blog post. I'm not sure anyone wants to write a prefetching blog post specifically.


Iterating over the elements in a hash table is done in various scenarios, for
example when a Valkey node needs to send all the keys to a newly connected
replica. The iterator functionality is improved by memory prefetching. This
means that when an element is going to be returned to the caller, the bucket and
its elements have already been loaded into CPU cache when the previous bucket
was being iterated. This makes the iterator 3.5 times faster than without
prefetching.