Systemsfor Aravinda
0 / 78 core
Week 12 · Production stories

Discord's message store

1 hours · core path

Read first: Partitioning and sharding, Indexes: B-trees and LSM trees, Caching

In one sitting

Discord stored messages in a Cassandra cluster of 177 nodes holding trillions of messages at the start of 2022, keyed by channel id and a time bucket. A hot channel was a hot partition that dragged the rest of its node, and the move to ScyllaDB waited on size and on reverse queries. Rust data services coalesce reads, and snowflake ids pack time, worker, process, and an increment into 64 bits.

Discord kept messages in a Cassandra cluster they called cassandra-messages. At the beginning of 2022 that cluster was 177 nodes and held trillions of messages. The interesting problem is smaller than the headline. One channel can be quiet, and another can be a firehose, and both are read as a recent window. A partition scheme that puts a whole channel on one node forever will eventually make that firehose the node. A scheme that scatters one channel’s messages at random makes the window read a scatter-gather. The key they published sits between those two.

The problem

Operating that cluster had become expensive in three concrete ways. Latency was unpredictable. The on-call was getting paged. Maintenance they needed to do was skipped because doing it cost too much. Those are not three unrelated complaints. Unpredictable latency on a store you are afraid to touch is what a hot partition feels like once the dataset is large enough that a repair or a move is its own incident.

The read is a window of one channel, usually the recent end of it. The write is an append of one message to one channel. Messages in the same channel and the same stretch of time want to live together, because that is the read. Messages from a later stretch can live somewhere else, because a channel that runs for years should not be one ever-growing partition.

Under those requirements, “add nodes” is not a strategy. Cassandra already spreads partitions across the cluster. A partition is still one partition. If the key is the channel, the busiest channel is one key no matter how many nodes you buy. The design work is the key, the read path on an LSM, and, later, a service in front that can notice when many clients are reading the same channel at once.

The id has to cooperate with that read. A message id that sorts roughly by time can be the cursor for “the next page.” A random id cannot, unless you keep a second order. Discord’s snowflake is the id they publish for that job, and its bit layout is specific enough to derive instead of memorize as a slogan.

The design

The partition key. The key is the channel id plus a time bucket. This is partitioning aimed at the query. All of one channel’s messages inside one window land in one partition, so a read of that window is a read of one partition. The next window is a different partition, so a channel’s entire history is not a single key that grows without a bound. A page that crosses a bucket boundary is more than one partition read. A page inside the bucket is one. Channel for locality, bucket for a bound.

Why a hot channel takes the node down with it. Cassandra stores partitions in an LSM. A read touches the memory table and, possibly, many files on disk. That is the read path from indexing: the recent writes are in memory, older writes are in immutable sorted files, and a point or a range may open more than one of them. A hot channel is a hot partition. Its reads pile onto the replicas that own that partition. Those replicas fall behind. Every other partition that happens to live on the same node waits behind that work. The quiet channel and the firehose share a disk, a CPU, and a queue. Buying another node moves some other partitions. It does not split this one. A hot key is not fixed by more partitions, and a time bucket only bounds how much of the channel sits in the key. Inside one bucket, a channel that is busy right now is still one partition.

The engine move, and why messages were last. They had already moved their other Cassandra clusters to ScyllaDB by 2020. ScyllaDB is Cassandra-compatible and written in C++. It does not have the JVM garbage-collection pauses that had been hurting them. A pause is the process stopping to reclaim memory. Requests on that node wait, and the wait shows up as a latency spike you did not put in your query plan. Removing that class of pause is a real change. It is not a change to the key.

The messages cluster waited. It was huge, 177 nodes and trillions of messages at the start of 2022, and reverse queries were not fast enough yet. A reverse query here means reading a window in the other order. Chat clients want the newest page, which is the opposite direction from “walk the partition in write order,” and that direction was slow. They did not move the largest cluster onto an engine that still could not serve the read they actually do. Compatible is not the same as fast for the query you have.

They did not stop at the swap. A faster engine under the same hot partition is still one node doing too much. They put Rust data services between the API and the database. Those services speak gRPC, which on this course is HTTP/2 plus a binary contract, the shape in networking. Routing uses consistent hashing on the channel id, so one channel’s reads hit the same service. Concurrent reads of that channel can be coalesced: one database read, shared with the waiters. That is the single-flight idea from caching. It cuts duplicate reads of a channel that many clients have open. It does not split the partition. The same hash that makes coalescing possible also pins the hot channel to one data service. You moved a copy of the hot key into the tier in front, on purpose, because coalescing needs a meeting place.

The snowflake. Discord’s developer reference describes the message id as 64 bits, laid out from the top.

42 bits  milliseconds since the Discord epoch
 5 bits  worker
 5 bits  process
12 bits  increment
-----------------
64 bits

epoch is 2015-01-01, as the millisecond value 1420070400000
shift aside the low 5 + 5 + 12 = 22 bits to recover the timestamp
timestamp_ms = high 42 bits + 1420070400000

The ceilings below are a derivation of that layout. They are not traffic numbers, and they are not a claim that any process mints ids at the ceiling.

2^5  = 32 worker ids
2^5  = 32 process ids
2^12 = 4096 increments in one millisecond, inside one process

4096 per millisecond × 1,000 = 4,096,000 ids per second
  that is the ceiling of a single process, not a measured rate

2^42 milliseconds = 4,398,046,511,104 ms
divide by 1,000 = 4,398,046,511 seconds
divide by 86,400 ≈ 50,903 days
a year is about 3 × 10^7 seconds, so
4,398,046,511 / (3 × 10^7) ≈ 147 years

The high 42 bits are time, so ids minted in a later millisecond sort after ids minted in an earlier one. Inside one millisecond the remaining bits are worker, then process, then a counter. Two messages minted in the same millisecond on different processes are ordered by those ids, not by a single global counter. That is still time-ordered enough to page a channel: the cursor “messages after this id” walks forward in time across milliseconds, which is the order a channel is read. It is not a total order of every keystroke in the company.

They are returned as strings because they do not fit in every language’s integer. If you parse the id into a number type that cannot hold 64 bits, you store a different integer than Discord minted. Two distinct messages can collapse to one value in your process, and a page cursor built from that value skips or repeats. Keep the id as a string until you are in a type that actually has 64 bits.

flowchart TD
  api[API]
  hash[Consistent hash of channel id]
  svc[Rust data service]
  key[Channel and time bucket]
  node[Message store node]
  api --> hash --> svc --> key --> node

The hash picks the data service so one channel can be coalesced. The key picks the database partition so one window is one read. Both arrows are a form of “same channel, same place.” Only the time bucket stops that place from being the channel’s entire life.

What they traded

Choice What you gain What you spend
Partition by channel and time bucket One channel’s window is one partition, and history is not a single unbounded key A hot channel inside one bucket is still a hot partition
Stay on Cassandra for messages while other clusters moved They kept a huge cluster put until the read worked Unpredictable latency, pages, and maintenance skipped because it was too costly
ScyllaDB, Cassandra-compatible, written in C++ The JVM garbage-collection pauses that had been hurting them are gone A swap of the largest cluster is its own risk, and the key does not change
Move messages last, after reverse queries were fast enough The newest-page read exists on the engine they were moving to The most painful cluster waited, by 2020 the others had already moved
Rust data services, gRPC, consistent hash on channel id Concurrent reads of one channel meet and can be coalesced Another hop to operate, and the hot channel sticks to one service too
Snowflake ids, time in the high bits A cursor that is time-ordered enough to page, returned as a string Same-millisecond ids are ordered by worker, process, and counter, not by a global sequence

The failure to picture is a busy channel sharing a node with boring ones. The firehose’s partition is in the memory table and in a stack of files. Each read of that window does real IO. The node falls behind. A quiet channel whose partition landed on that same node sees its latency move, even though nobody is reading it harder than yesterday. The dashboard for the quiet channel looks haunted. The cause is the neighbor. More nodes, added behind the same partitioner, reshuffle other keys and leave this bucket where it is.

The second failure is treating the engine swap as the repair. By 2020 the other Cassandra clusters had moved to ScyllaDB. Messages had not, because the cluster was huge and because reading a window in the other order was not fast enough. Moving earlier would have copied a bad read onto the new engine. Moving without the data services would have removed GC pauses and left the hot partition, and the coalescing, undone. They published both changes because they did not trust the swap alone. You should not trust it alone either when the key is the incident.

The third failure is parsing the snowflake. The id looks numeric. In a language whose integer cannot hold it, the low bits are the ones you lose, and the low bits are exactly the worker, the process, and the increment. You can turn two messages from the same millisecond into one id, then page from that id and skip a slice of the channel. Returning strings is the published fix. Re-parsing them “just for sorting” reintroduces the bug if the sort uses a narrow number type. Sort the string only if your string order matches the numeric order of a 64-bit value, or unpack the bits in a wide integer. The timestamp math above is how you unpack them when you genuinely need the time.

What to steal

Steal the key that matches the read, with a bound. “One channel, one window” is a partition a chat read can use. “One channel, forever” is a partition that becomes the channel’s popularity. You can copy that sentence into a schema review this week, on whatever database you already run. If you cannot say what the bucket is for, you do not have a bound, and a celebrity channel will eventually be your capacity plan.

Steal the refusal to confuse a faster engine with a split key. C++ instead of JVM pauses removes a stall you could see in latency. It does not move a partition. Coalescing on a consistent hash removes duplicate reads of the same channel, which is worth doing once many clients read one window, and it concentrates that channel on one service. Say both halves when you propose the hop. A team of five does not need Rust data services, gRPC, and a second hash ring to get there. A single process can coalesce in-flight reads of one channel with a map of waiters. Build that when you have measured duplicate reads, not before.

Steal the id layout if you mint ids yourself, and steal the string rule even if you do not. Forty-two bits of milliseconds since a fixed epoch, then worker, process, and increment, is enough to page by id because time is the high bits. Derive the ceilings before you quote them. 4,096,000 ids per second is what one process can number, not what your product does. And if the id does not fit in the language’s integer, it is a string on the wire. The unique id design you sketch in an interview should say the same thing: time-ordered enough for the cursor you need, wide enough for the language you have, and honest about not being a single global counter.

Leave the 177-node cluster in the writeup. Trillions of messages on that many nodes is the setting where skipped maintenance and a hot partition become the same outage. It is not a starting size. Start with the key, the window read, and an id you can page. Add a coalescing hop when one channel’s duplicate reads show up in a profile. Change engines when a measured stall, such as a garbage-collection pause, is the stall you actually have, and only after the query you depend on, including the reverse window, is fast enough on the new one.

Check yourself

The partition key is channel id plus a time bucket. Why can a hot channel still slow down unrelated channels on the same node after you add machines?

One bucket of one channel is one partition, and an LSM read of it touches the memory table and possibly many files. Those reads pile onto the replicas that own the partition, so that node falls behind. Other partitions on the node wait behind the same disk and CPU. Adding machines moves other partitions. It does not split this key. The bucket only bounds how much of the channel is in one partition, not how hot that partition can be.

Other Cassandra clusters had moved to ScyllaDB by 2020. Why was cassandra-messages still waiting at the start of 2022?

It was huge, 177 nodes and trillions of messages, and reverse queries were not fast enough yet. A reverse query reads a window in the other order, which is the newest-page read a chat client does. They waited until that read was fast enough, and they still put Rust data services in front because a database swap alone did not fix the hot partition.

Using the published snowflake layout, how many bits are time, worker, process, and increment, and what is one process allowed to mint in a single millisecond?

42 bits of milliseconds since the epoch 2015-01-01, whose millisecond value is 1420070400000, then 5 bits of worker, 5 bits of process, and 12 bits of increment. That sums to 64. The low 12 bits are 2 to the 12th, so 4096 ids in one millisecond inside one process. 4096 times 1000 is a ceiling of 4,096,000 ids per second for that process. That ceiling is a derivation of the layout, not a traffic measurement.

Why route data-service traffic by a consistent hash of channel id, and which problem does that leave in place?

One channel’s reads hit the same Rust service, so concurrent readers can share one database read instead of each issuing their own. That is coalescing. The hash also pins a hot channel to one service, and the database partition for that channel and time bucket is still one partition on one set of replicas. Duplicate reads get cheaper. The hot key does not split.

Based on: Discord's writeup of the message store; Discord developer reference for snowflake ids.