Summary#
Discord is a chat, voice and video service for communities, from a group of five friends to a single server with millions of members. Its engineering blog is a record of a small team running into very large numbers: messages that went from millions to trillions, WebSocket sessions that went from thousands to more than ten million at once, and voice calls that went past two million concurrent users. This page reads 22 Discord engineering posts and follows each system from its first design to the one that replaced it.
The posts form six families: message storage (MongoDB to Cassandra, Cassandra to ScyllaDB, the Rust data services, automating ScyllaDB, super-disks), search (indexing billions and then trillions of messages on Elasticsearch), the real-time gateway (scaling Elixir to 5 and then 11 million concurrent users, Rust sorted sets, Go to Rust for Read States, cutting WebSocket traffic by 40%, push bursts with GenStage, Midjourney-scale servers), voice and video (2.5 million concurrent voice users, moving voice to the edge, end-to-end encryption with DAVE), media and ML (resizing 150 million images a day, multi-GPU training), and engineering productivity (tracing Elixir, API cost attribution, client performance, cloud development environments). All Discord facts below come from the fetched posts. The math, analogies and worked examples marked "handbook's illustration" are this handbook's own.
Why It Exists#
A chat system looks simple in an interview: clients hold a WebSocket, messages go into a database, and a pub/sub layer fans them out. Discord's posts show what that picture hides once the numbers grow:
- Chat history is kept forever and read at random. A message from three years ago can be loaded by a jump link, a search result or a pinned message. The storage layer must serve old and new data with the same predictable latency.
- Communities are wildly uneven. Most servers are tiny, but a few have hundreds of thousands or millions of members. One busy channel can become a hot partition, and one big server can make every message a fan-out to millions of sessions.
- The gateway is stateful. Each connected user holds a session with presence, subscriptions and buffered events. Restarting or moving millions of sessions is itself a load event.
- Voice is latency-bound, not throughput-bound. A call has to stay under a few hundred milliseconds end to end, so servers must sit close to users, and security cannot add delay.
- A small team runs it. The first storage post notes there were only four backend engineers and no dedicated operations staff. Many choices favour systems that heal themselves and need little care.
The textbook pages (chat system, Cassandra, pushing realtime updates, Elasticsearch) explain each idea in isolation. Discord's posts show how they behave at trillions of rows and millions of connections, and what each fix cost.
For each post the page asks:
- Assumptions. What traffic, latency, consistency and maintenance conditions did the authors assume?
- Production architecture. What did Discord actually build?
- Overlooked constraints and trade-offs. What is easy to miss when copying the idea?
- Sacrifice. What did Discord give up to get the benefit?
How It Works#
The diagram shows where each family sits on the path of a message. A client holds a WebSocket to the Elixir gateway, which owns the user's session. Sending a message goes through the API to the data services, which write to the message database. The guild process for that server then fans the event out to every session that should see it. Search indexing reads the same messages from a queue. Voice and video take a separate path to media servers near the user.
The lessons below follow the six families in order. Each one covers a single post, or two closely linked posts, and ends with what the design gave up.
Family 1: Message storage
Lesson 1: How Discord stored billions of messages, MongoDB to Cassandra#
Assumptions. The first Discord was built in under two months in early 2015 on a single MongoDB replica set. The team knew it was temporary: they avoided MongoDB sharding, which they judged complex and unstable, and planned from the start for a later move. Messages had one compound index on channel_id and created_at. By about November 2015 the store held 100 million messages, the data and index no longer fit in RAM, and latency became unpredictable. Daily volume grew from 40 million messages a day to 100 million and then past 120 million. Discord had also decided to keep all history forever.
Understanding the workload first. Before choosing a database, the team studied how messages were read:
- Reads were very random, and the read/write ratio was about 50/50, unusual for a social product.
- Voice-heavy servers send almost no text, perhaps a message every few days and under 1,000 a year. Loading 50 of their messages means many random disk seeks, and each seek evicts something useful from the disk cache.
- Private text servers send 100,000 to 1 million messages a year, mostly read when recent. They have few members, so their data is rarely in cache.
- Large public servers have thousands of members and millions of messages a year, read heavily and usually from the last hour, so their data stays in cache.
- Planned features (jumping to mentions from the last 30 days, pinned messages, full-text search) would add more random reads.
Requirements. Linear scalability with no manual re-sharding; automatic failover; low maintenance; proven technology; predictable performance (an alert fired when API p95 passed 80 ms, and the team did not want a Redis or Memcached message cache); not a blob store, because appending to serialized blobs at thousands of writes per second would be slow; and open source. Cassandra was the only option that met all of these.
The data model. Cassandra is a "KKV" store. The partition key decides which nodes hold the data and where it sits on disk. The clustering key identifies and sorts rows inside a partition, so a partition behaves like an ordered dictionary. Messages could not cluster on created_at, because two messages can share a timestamp. But every Discord ID is a Snowflake, a 64-bit ID that sorts by time, so the key became (channel_id, message_id), and loading a channel became a range scan.
The first import produced warnings about partitions over 100 MB. Cassandra claims to support 2 GB partitions, but large partitions cause GC pressure during compaction and cluster expansion, and a single partition cannot be spread across nodes. A channel can live for years, so partitions had to be bounded. Discord added a time bucket: about 10 days of messages per bucket kept even the busiest channels under 100 MB. The key became ((channel_id, bucket), message_id), with the bucket derived from the Snowflake. To read recent messages, the service walks buckets from now back towards the channel's creation (the channel ID is a Snowflake too) until it has enough messages. Quiet channels need several bucket queries, but busy channels, which are most of the reads, usually find enough in the first.
CREATE TABLE messages (
channel_id bigint,
bucket int,
message_id bigint,
author_id bigint,
content text,
PRIMARY KEY ((channel_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);Dark launch and eventual consistency. Discord ran double reads and writes to MongoDB and Cassandra before switching. Errors appeared at once: author_id was null on some rows, though it was required. The cause was Cassandra's write model. Reading before writing is expensive, so every write is an upsert, and conflicting writes on different nodes are resolved by last write wins per column. If one user edited a message while another deleted it, the edit's upsert of the text column survived the delete, leaving a row with only the primary key and the text. Writing the whole message back on every edit would risk resurrecting deleted messages and create more conflicts. Discord chose to detect corrupt rows (a required column, author_id, being null) and delete them.
Tombstones. Because deletes must replicate even to nodes that are down, Cassandra records a delete as a tombstone, a marker that reads skip over and that compaction removes after a grace period (10 days by default). Writing null is the same as deleting, so it also creates a tombstone. The message schema had 16 columns, but the average message set only 4, so every insert was writing about 12 tombstones for nothing. The fix was to write only non-null values.
Performance. Writes were under 1 ms and reads under 5 ms, steady for a week of testing, including a jump to a message a year back in a channel with millions of messages. MongoDB was phased out within a week.
The big surprise. About six months later Cassandra became unresponsive, running 10-second stop-the-world GC pauses. One channel took 20 seconds to load. It belonged to a large public server whose moderators had deleted millions of messages through the API, leaving one. Loading that channel made Cassandra scan millions of tombstones, creating garbage faster than the JVM could collect it. Two fixes followed: tombstone lifetime was cut from 10 days to 2, which is safe because repair (Cassandra's anti-entropy process that makes replicas agree) runs nightly; and the query code started tracking empty buckets so it would not scan them again.
State at the time. A 12-node cluster, replication factor 3, nearly 1 TB of compressed data per node. Plans: Cassandra 3's storage format for more than 50% less space, 2 TB per node, and maybe ScyllaDB, because repairs made the nodes CPU bound at night. Discord also considered archiving idle channels to Google Cloud Storage but hoped never to need it. Over time all live production data moved to Cassandra.
Overlooked constraints.
- The grace period is a correctness setting. Tombstones must outlive the repair interval, or a replica that missed a delete can bring the data back. Cutting it to 2 days was safe only because repair ran every night.
- Upserts make partial writes visible. In a last-write-wins store, concurrent column updates can produce a row nobody wrote. You need a validity rule, as Discord did with author_id.
- Buckets trade read cost for partition size. Ten-day buckets fit busy channels; quiet channels pay with extra queries, which is why the empty-bucket cache matters.
What Discord sacrificed. Strong consistency and simple deletes. It accepted eventual consistency, corrupted rows that had to be cleaned up on read, and a delete model where removing data creates more data. In return it got linear scale, self-healing nodes and steady single-digit millisecond reads with four backend engineers.
Deep Dive: choosing a bucket size and pricing a tombstone scan, with numbersShow
Bucket size. The goal is to keep the largest channel's partition under a target, say 100 MB. Suppose the busiest channel writes 20 messages per second at peak and averages 8 per second over a day (handbook's illustration). That is 8 × 86,400 ≈ 690,000 messages a day. At about 150 bytes per stored message after compression, one day is about 104 MB. So for that channel, even one day would break the target, while a typical busy channel at 0.1 messages per second makes 8,640 a day, or about 1.3 MB, and ten days is 13 MB. Discord's ten-day choice was based on the largest channels at that time. The general rule is bucket = target size ÷ (peak sustained write rate × row size), and it has to be revisited as the biggest channels grow, because a bucket size cannot change without rewriting data.
Reads for a quiet channel. A channel that gets one message a week has about 1.4 messages per ten-day bucket. Loading the latest 50 means walking about 35 buckets, each a separate partition read of maybe 1 ms, so about 35 ms of database time. That is the cost of bucketing for quiet channels. Caching "known empty" buckets and the newest non-empty bucket per channel cuts this sharply.
The tombstone scan. Say a channel had 2 million messages and 1,999,999 were deleted within the grace period. A read for the latest 50 now has to step over about 2 million tombstones. If each costs about 1 microsecond of CPU and 100 bytes of temporary objects, the read burns 2 seconds of CPU and creates about 200 MB of garbage. A few users refreshing the channel multiplies that, and the JVM spends its time in long GC pauses. Cassandra warns at 1,000 tombstones per read and fails the query at 100,000 by default, which shows how far outside normal use this case was. Shortening the grace period helps only if repair runs more often than the grace period; otherwise it risks "zombie" data returning.
Lesson 2: Why Cassandra hurt at trillions, and the Rust data services in front of ScyllaDB#
Assumptions. By early 2022 the cluster called cassandra-messages had grown from 12 nodes to 177 nodes holding trillions of messages. The schema was unchanged: partition by (channel_id, bucket), cluster by message_id, replication factor 3, with reads and writes at quorum (two of three replicas must answer). The team wanted a database whose maintenance would not grow with its size. Instead the on-call team was paged often, latency was unpredictable, and maintenance jobs were being skipped because they were too expensive to run.
Why it hurt.
- Reads cost more than writes. A write appends to the commit log and an in-memory memtable, which later flushes to an immutable on-disk SSTable. A read may have to check the memtable and several SSTables and merge the results.
- Hot partitions. The newest bucket of a popular channel takes almost all of that channel's live reads. A server with hundreds of thousands of members can send orders of magnitude more traffic than a group of friends, and it all lands on the same three replicas. The partition was hot because the data was popular, not because the buckets were too big. Splitting it further would make the main query, reading a channel in order, harder.
- Hot spots spread. Those three nodes also held thousands of quiet channels. With quorum reads, any query that needed an overloaded node waited for it, so one busy channel slowed unrelated users across the cluster.
- Compaction debt. Compaction merges SSTables so reads touch fewer files. The cluster kept falling behind. More uncompacted files made reads slower, slower reads left less capacity for compaction, and the backlog grew. Running compaction harder would only fight live traffic for the same CPU and disk.
- The "gossip dance". To catch up, operators took a node out of rotation so it could compact without traffic, brought it back to receive hinted handoff (writes other nodes had stored for it while it was away), and repeated node by node.
- Garbage collection. Much time went into JVM heap and GC tuning. The worst runs of back-to-back GC pauses forced an operator to reboot a node and nurse it back to health.
ScyllaDB. ScyllaDB is a Cassandra-compatible database written in C++. It keeps CQL and the data model, so the schema could stay, and it has no garbage collector. Its shard-per-core design gives each CPU core its own slice of data and its own request queue, which isolates work better and speeds up repairs. Discord moved every other database to ScyllaDB by 2020, and kept the biggest one for last to gain experience first. One blocker was reverse queries, scans in the opposite order to the table's sort, such as reading messages oldest first. They were too slow, and the ScyllaDB team made them fast before the migration.
Data services. A faster database would still face thousands of readers on one partition. So Discord added data services between the API monolith and the databases, written in Rust on the Tokio async runtime. Each has about one gRPC endpoint per database query and deliberately no business logic. Their main feature is request coalescing: the first request for a row starts a worker task that queries the database; identical requests that arrive while it runs subscribe to that task instead of sending their own query, and every subscriber gets the same result. Upstream, requests are routed by consistent hashing on a routing key, the channel ID for messages, so every request for one channel reaches the same instance, where coalescing can work.
// Request coalescing: share one in-flight query per key (sketch)
const inFlight = new Map<string, Promise<Message[]>>();
async function getMessages(channelId: string, bucket: number): Promise<Message[]> {
const key = channelId + ":" + bucket;
const running = inFlight.get(key);
if (running) return running; // join the query already running
const p = db.queryMessages(channelId, bucket)
.finally(() => inFlight.delete(key)); // remove once done, success or failure
inFlight.set(key, p);
return p;
}Why not a cache? A cache would also catch requests that arrive after the first query finishes, so its hit rate is higher. But it brings expiry and invalidation, and a chat message can be edited or deleted at any moment. Coalescing never serves an old result. It only shares work that is already in progress. Discord gave up some hit rate for much simpler consistency.
The data services shipped while Cassandra was still primary. Hot partitions still happened, but less often, which bought time to prepare the ScyllaDB cluster.
Overlooked constraints.
- Coalescing needs routing. Two identical requests on different instances cannot be merged. Consistent hashing by channel makes them meet, but it also makes one instance hot for a hot channel, so that instance needs headroom.
- A failure is shared too. If the one coalesced query fails or times out, every waiting caller fails together. Errors must not be cached in the in-flight map.
- A faster engine does not remove hot keys. ScyllaDB makes each read cheaper; only reducing the number of reads, by coalescing, routing or caching, removes the hot spot.
What Discord sacrificed. An extra network hop and a new fleet to run, plus a second language in the stack. It also gave up a cache's higher hit rate, on purpose, to keep reads always fresh.
Deep Dive: how much request coalescing saves on a hot channel, with numbersShow
Take an @everyone announcement in a server with 500,000 members (handbook's illustration). Suppose 20% open the channel within 60 seconds. That is 100,000 reads, about 1,667 per second, all for the newest bucket of one channel.
Without coalescing, all 1,667 reads per second go to the same three replicas. At quorum each read touches two of them, so each replica handles about 1,100 reads per second for one partition, on top of its normal work, and each read may merge a memtable and several SSTables.
With coalescing, requests that arrive while a query is in flight join it. If one query takes about 5 ms, then at 1,667 requests per second there are about 1,667 × 0.005 ≈ 8 requests in each 5 ms window. Only the first in each window reaches the database, so database reads fall to about 1 per 5 ms, or 200 per second. That is an 8 times reduction from coalescing alone. In general, if arrivals are λ per second and the query takes t seconds, the database sees about min(λ, 1/t) reads per second for that key, once λ × t is greater than 1.
The effect grows as load grows. At 10,000 requests per second, the database still sees about 200 per second, a 50 times reduction. That is exactly when it matters, because hot keys appear during spikes. This is also why coalescing works best when the query is slow compared with the gap between requests, and does nothing for a key read once a minute. For that, a cache with a short TTL would help, at the cost of staleness.
Quorum spread. Without coalescing, the slow replica holds up every quorum read that needs it, including those for quiet channels on the same node. Cutting its load from 1,100 to about 130 extra reads per second keeps its queue short, which is what keeps unrelated users' p99 low.
Lesson 3: Migrating trillions of messages with no downtime#
Assumptions. The migration had two requirements: no downtime, and speed, because the team was still fighting fires on Cassandra. The new ScyllaDB cluster used Discord's super-disk storage (local SSDs mirrored by RAID to a persistent disk; see Lesson 5).
The first plan. To get value early, Discord would start dual-writing new data to both databases and use a time cutover: new data read from ScyllaDB, history migrated behind it. ScyllaDB's Spark migrator needed a lot of tuning and then estimated three months.
The second plan. The team realised they had just written a fast Rust database library for the data services. In an afternoon they extended it into a migrator that:
- Reads the source database by token ranges (slices of the hash ring).
- Checkpoints finished ranges locally in SQLite, so a crash restarts from the last range, not from zero.
- Writes the data into ScyllaDB as fast as it can.
The new estimate was nine days, short enough to drop the time-cutover plan and switch everything at once. It peaked at 3.2 million messages per second. Near the end it sat at 99.9999%: the last few token ranges kept timing out because they held huge runs of tombstones that Cassandra had never compacted away. Compacting those ranges finished the job in seconds.
Validation and cutover. A small percentage of reads went to both databases and the results were compared automatically. With ScyllaDB carrying full production traffic well, the team made it primary in May 2022.
Results.
| Metric | Cassandra | ScyllaDB |
|---|---|---|
| Nodes | 177 | 72 |
| Disk per node | about 4 TB average | 9 TB |
| Historical message fetch p99 | 40 to 125 ms | 15 ms |
| Message insert p99 | 5 to 70 ms | 5 ms |
During the 2022 World Cup final, each goal showed up as a spike in the message-send graph, and the database handled every one without trouble.
Overlooked constraints.
- Dual writes plus a backfill can race. If the migrator copies an old version of a row after a newer dual write, the newer write can be lost. Cassandra and ScyllaDB resolve this with write timestamps: copying with the original timestamps means the newer write still wins.
- Old garbage blocks migrations. Uncompacted tombstones made the last 0.0001% the hardest. Migrations read everything, including data the live system skips.
- Checkpointing changes the risk. A nine-day job that cannot resume is a nine-day bet. Range-level checkpoints made failures cheap.
What Discord sacrificed. It skipped the safer, slower, incremental cutover and bet on one fast switch, backed by shadow-read validation. It also built its own migrator instead of using the vendor's tool, which was a cheap bet only because the library already existed.
Deep Dive: migration throughput, from three months to nine daysShow
Nine days at full speed gives a sense of the data size. If the migrator averaged about 1.5 million messages per second, well below its 3.2 million peak (handbook's illustration), nine days is 1.5 million × 86,400 × 9 ≈ 1.2 trillion messages. That is consistent with "trillions" as a lower bound.
Why was the Rust tool so much faster? Spark adds a general-purpose job layer, serialization between stages and JVM overhead. A purpose-built migrator using the same async driver as production can keep thousands of requests in flight per process. Throughput by Little's law is concurrency ÷ latency. With 5,000 writes in flight across the fleet at 2 ms each, it can do 2.5 million writes per second. The limit then becomes the target cluster's write capacity and the source's read capacity, not the tool.
Token ranges give parallelism and resumability. With the ring split into, say, 100,000 ranges, each worker takes a range, copies it and records it as done. A crash loses at most the ranges in flight. The long tail at the end is typical: most ranges are similar, but a few hold pathological data, here tombstone runs, and they set the finish time. Spotting slow ranges and handling them separately is a standard migration move.
Lesson 4: Automating ScyllaDB clusters with the Scylla Control Plane#
Assumptions. Discord's Persistence Infrastructure team, seven people, runs Elasticsearch, Postgres and ScyllaDB. ScyllaDB stores messages, channels, servers and most user data: dozens of clusters with hundreds of nodes. The routine work is constant: rolling restarts after config changes, cluster expansion, OS upgrades across hundreds of nodes without downtime, and shadow clusters. A shadow cluster is a short-lived, full replica of a production cluster that receives the same reads and writes as production, made possible by the data services (Lesson 2). New ScyllaDB versions, OS images and hardware are tried on a shadow first, because some bugs appear only at Discord's load, sometimes only once every node runs the new version. Setting one up by hand took about a day and a half.
What was wrong with the scripts. Years of Python and bash scripts, written under pressure, had three faults:
- Unsafe. Easy to run in the wrong order or on the wrong nodes, with no precondition checks.
- Unrecoverable. A failure in the middle, say steps 7 to 12, meant starting over.
- Hard to extend. A new operation meant copying and editing an old script rather than composing pieces.
Goals for SCP. An extensible task framework that new authors can use without learning the internals; configurable parallelism, such as "never run this in two zones at once"; safety by default, with declared preconditions, automatic retries of transient failures and persisted state; and incremental delivery, shipping small usable pieces and adjusting.
The design: tasks, workflows, jobs.
- Tasks are single units of work, such as "drain this node", "check repair status" or "run cleanup". Node tasks act on one node; cluster tasks coordinate many. A task is a Rust trait with a name, a list of preconditions, and an execute method. Every task must be idempotent, because retries are the main way SCP handles failure.
- Conditions are special tasks that block until a state is reached, by polling ScyllaDB's API or Prometheus metrics until a check passes or times out. For example, after a restart, wait until compactions settle. A fixed sleep is either too short (pressure cascades across the cluster) or too long (a 30-node rolling restart takes all day). Conditions make the wait explicit, observable and tunable.
- Workflows are YAML: a sequence of tasks with retry counts, abort rules and parallelism settings. YAML lets operators tune retries and concurrency without recompiling, and template variables scope a workflow to nodes or zones at run time.
- Jobs are one run of a workflow against one cluster, optionally targeting a node list or a zone. Two settings control spread: concurrency_unit groups nodes, for example by zone, so a task never runs in two zones at once; concurrency_limit caps how many nodes run at once within a group.
# Join new nodes one at a time, one zone at a time
- task: node-workflow
name: Join nodes to cluster
concurrency_unit: zonal
concurrency_limit: 1
node_tasks:
- task: send-webhook-message # warn on-call before each join
- task: salt-highstate # configure the node
- task: wait-for-conditions
conditions:
- condition: is-up-normal
success_window_seconds: 60 # must stay healthy for a full minute
poll_interval_seconds: 5
timeout_seconds: 86400 # bootstrapping can take up to a dayResumability. Long jobs get interrupted: a node becomes unreachable, SSH times out, someone closes a terminal. SCP stores every job's state in a local SQLite file: which tasks finished on which nodes, which were running, which failed. On resume it skips finished tasks and retries the interrupted ones. A file next to the binary was chosen over a distributed store for simplicity: no extra dependency, state survives restarts, and the files are small enough to inspect by hand.
Error classes. Recoverable errors, such as a network timeout, are retried as the workflow says. Unrecoverable errors, such as data corruption or an unsafe cluster state, stop the job and send a webhook to an ops channel in Discord, tagging the operator. Marking everything recoverable is tempting, but a retry loop against a broken cluster can do real harm. The webhook changed the experience: a two-hour rolling restart across 30 nodes became "start it and wait to be pinged" instead of watching a terminal.
Adding nodes. ScyllaDB's old rule of joining one node at a time is kept: nodes join zone by zone, each waiting until it has finished bootstrapping and has been continuously healthy for 60 seconds, with up to 24 hours allowed.
Results. SCP now runs new-cluster setup, expansion, rolling Ubuntu upgrades, rolling restarts, scylla.yaml changes, binary cycling, SIGHUPs and cleanups. A 36-hour operation now takes under two hours, mostly waiting for nodes to bootstrap. Next steps: one workflow for the full shadow-cluster lifecycle, and joining nodes in small batches with repairs in between, so repair coverage never falls far behind.
Overlooked constraints.
- Idempotency is the price of retries. A task like "add node" must check whether the node is already in the ring before acting, or a retry can corrupt the cluster.
- Zone-aware concurrency is about quorum. With replication across three zones, touching two zones at once can drop two replicas of some data and lose quorum. The concurrency unit encodes that rule so nobody has to remember it.
- Local state is a single point of failure. A SQLite file on the operator's machine is fine for a seven-person team, but if the machine dies mid-job, the state goes with it. The team kept the option of moving to a distributed store later.
What Discord sacrificed. Time spent building a framework instead of just running operations, and a deliberately simple state store. It also kept slow, serial node joins, giving up faster expansion for safety.
Deep Dive: what a rolling restart costs, and why conditions beat sleepsShow
Take a 30-node cluster across 3 zones (handbook's illustration). Each node needs about 1 minute to drain and restart, then a variable time for compactions to settle: usually 2 minutes, sometimes 8.
Fixed sleep. To be safe, an operator sleeps 8 minutes after every restart. Total time = 30 × (1 + 8) = 270 minutes, or 4.5 hours. If the sleep is cut to 2 minutes, the run takes 90 minutes, but on the nodes that need 8 minutes the next restart begins while compactions are still heavy, and read latency rises across the zone.
Condition check. Wait until "compactions nominal" has held for 20 seconds, polling every 5. Expected wait is about 2.3 minutes on normal nodes and 8.3 on slow ones. If 10% are slow, the total is 30 × 1 + 27 × 2.3 + 3 × 8.3 ≈ 117 minutes. That is under 2 hours, close to the fast-sleep time, while being as safe as the slow sleep.
Zone parallelism. Nodes in the same zone share replicas only with other zones, so with replication factor 3 across 3 zones, restarting two nodes in the same zone at once still leaves two replicas of every row available. With concurrency_limit set to 2 within a zone, the total time roughly halves to about an hour. Restarting nodes in two zones at once could take two replicas of the same row offline, and quorum reads for that row would fail. That is the whole case for making zone the concurrency unit.
Lesson 5: Super-disks, local SSD speed with network disk durability#
Assumptions. Discord's ScyllaDB clusters served about 2 million requests per second, with workloads that are read-heavy. It runs mostly on Google Cloud. Databases run requests in parallel, so disk latency is hidden at low load. But concurrency is limited. Once the database must wait for an outstanding disk read before issuing the next, reads back up, queries slow and, at worst, time out while still queued. That is what Discord saw: a growing queue of disk reads.
The two disk types.
| Property | Persistent Disk | Local SSD |
|---|---|---|
| Connection | Over the network, from nearby | NVMe on the host |
| Read latency | about 1 to 2 ms | about 0.5 ms or less |
| Durability | Replicated; survives host failure | Lost if the disk or host fails |
| Snapshots | Point-in-time snapshots | None |
| Resize | Online | Fixed 375 GB each |
Discord's tests found Local SSDs unreliable enough that it would not trust them alone for critical data, and snapshots were needed for backups. So nearly all servers used Persistent Disks.
What could be given up. Write latency matters less than read latency for these workloads, and online resizing was not needed because storage growth could be planned. Requirements: stay in GCP, keep snapshots for backups, put low read latency first, and lose no uptime.
First try: a write-through cache. Linux offers block-level caches (dm-cache, lvm-cache, bcache), with the SSD as cache and the Persistent Disk as storage. The problem was bad sectors. A bad sector on the cache SSD failed the whole read, instead of re-reading from the Persistent Disk and repairing the cache. ScyllaDB shuts down on I/O errors to protect data, so a single bad sector would take a node out.
The solution: md RAID with write-mostly. Linux's md software RAID can mark a RAID1 member as write-mostly: it gets every write but is read only when no other member can serve. That fits a network disk exactly.
- Several 375 GB Local SSDs are combined into one RAID0 stripe, because each database needs a terabyte or more. RAID0 loses everything if one SSD fails, but GCP moves the whole VM to new hardware when any Local SSD fails, wiping all of them anyway, so parity RAID would add cost without benefit.
- The RAID0 array and a Persistent Disk form a RAID1 mirror, with the Persistent Disk marked write-mostly.
- Reads come from the SSDs. Writes go to both. If an SSD sector is bad, md reads from the Persistent Disk and can rewrite the sector. If the host dies, the Persistent Disk still has everything and can be snapshotted.
Results. At peak, disk operations no longer queued and query latency stayed flat. Fewer outstanding reads meant more queries per server, so fewer servers. The post notes that cloud disks behave nothing like data-centre disks, and that disk latency should have been watched from the start. Several edge cases needed more than a single md configuration; the post promised a follow-up on them.
Overlooked constraints.
- Writes still wait for the slow disk. RAID1 acknowledges a write only when both members have it, so write latency stays at network-disk speed. That was acceptable only because Discord's workload is read-heavy and writes are absorbed by the commit log and memtable.
- Rebuilding the SSD side is a full copy. After a host migration wipes the SSDs, the RAID0 must be resynced from the Persistent Disk, and reads fall back to the slow disk until it finishes.
- Snapshots are crash-consistent only. A Persistent Disk snapshot captures what the disk had at that moment. Database-level consistency still needs flushes or the database's own backup tool.
What Discord sacrificed. Online resize, write latency improvements, and simplicity: an md stack to understand and debug, and cloud-specific failure modes. It gave up flexibility it did not need for the read latency it did.
Deep Dive: why 1.5 ms of disk latency becomes a queue, with Little's lawShow
Suppose one node must serve 20,000 reads per second, and 30% miss the cache and go to disk (handbook's illustration). That is 6,000 disk reads per second.
By Little's law, outstanding disk reads = arrival rate × latency. On a Persistent Disk at 1.5 ms, that is 6,000 × 0.0015 = 9 reads in flight on average. On local NVMe at 0.15 ms, it is about 1.
Now suppose the database keeps at most 16 disk reads in flight per shard group. At 9 average, bursts often reach 16, and any request beyond that waits. As the load grows to 10,000 disk reads per second, the Persistent Disk needs 15 in flight on average, right at the limit, so queues form, and queue time adds to latency, which raises the in-flight count further. That is the runaway Discord saw. On the SSD, 10,000 × 0.00015 = 1.5 reads in flight, far below any limit.
The same law shows the value in hardware. If the limit is 16 in flight and the target is 50% utilisation, the Persistent Disk node handles about 8 ÷ 0.0015 ≈ 5,300 disk reads per second, while the SSD node handles 8 ÷ 0.00015 ≈ 53,000. In practice the CPU becomes the limit first, but the point holds: lower latency means more queries per server, which is why super-disks also cut cost.
Family 2: Search
Lesson 6: Indexing billions of messages on Elasticsearch#
Assumptions. Millions of users sent billions of messages a month, and search was one of the most requested features. The requirements:
- Cost-effective. Search is an extra feature, so it should cost no more than storing the messages.
- Fast and intuitive.
- Self-healing, because there was no operations team.
- Linearly scalable: add nodes to add capacity.
- Lazily indexed: index a server only when someone first searches it, and be able to rebuild any server's index on the fly.
Build or buy. Every managed search product Discord looked at would have blown the budget by a huge margin, and the team did not want users' messages leaving its own infrastructure. Between the open-source options, Elasticsearch beat Solr because Solr needs ZooKeeper for discovery (Discord ran etcd and did not want another system), Elasticsearch rebalances shards automatically, it has a structured query DSL, and the team knew it.
Many small clusters, sharded by the application. Stories of painful large Elasticsearch clusters led to a key decision: do the sharding and routing in the application, across a pool of small clusters. A cluster outage then affects only the servers on it, and a broken cluster can simply be thrown away, because those servers will be re-indexed lazily at their next search. Discord's "Shard" is a (cluster, index) pair, not an Elasticsearch shard.
Components.
- A message queue of new messages, and index workers that pull batches and bulk insert them. Elasticsearch prefers bulk writes, so messages become searchable after a short delay. That is acceptable, because people mostly search older messages.
- Historical index workers, on the existing Celery task system, that walk a server's past messages.
- A shard mapping from Discord server to Shard, stored in Cassandra as the source of truth and cached in Redis, so workers can look up many at once with MGET.
- A load-aware shard allocator: a Redis sorted set of Shards scored by load. A new server goes to the lowest score. Each allocation adds to the score, and each indexed message has a small chance to add to it too, so fuller Shards are picked less often.
- etcd for discovery: Elasticsearch nodes announce themselves, so no topology is hard-coded.
- A search API that checks permissions so users only see messages they may read.
The index design. Each index has one primary shard (the application already shards), one replica to survive a node failure, a 60-minute refresh interval, and one document type. Messages are not stored raw. Each is turned into searchable fields: author, channel, mentions, whether it has a link, an embed or a file, and so on. There is no timestamp field, because the Snowflake ID already holds the time, so "before", "on" and "after" filters are ID ranges. The fields are kept only in the inverted index. The only stored fields are the message, channel and server IDs. Results are then loaded from Cassandra, which the UI needs anyway to show two messages before and after each hit. This saves disk but means Elasticsearch cannot highlight matches, so the client does highlighting with its own tokenizers.
A library, not a service. Search was shipped as a library used by the API workers and index workers, with a small surface area: queue a message for indexing or deletion, bulk index, and run a historical index job. A historical job does a fixed unit of work, 500 messages by default, and returns a cursor to the next batch. Large servers are indexed in two phases: an initial phase covering the last 7 days, after which search is available, and a lower-priority deep phase for all history.
The refresh surprise. The first production test, a 3-node cluster indexing the 1,000 largest servers, showed far too much CPU and disk use. Overnight, disk use shrank sharply. The cause was Elasticsearch's default 1-second refresh: each refresh writes a new Lucene segment and opens it for search. Across a thousand indexes, that produced masses of tiny segments, which background merges later combined. With refresh effectively turned off, CPU fell to almost nothing.
Refresh on demand. But search still has to see recent messages. Discord moved refresh control into the application with a Redis map, keyed by Shard, of server IDs that have new, unrefreshed messages:
- Indexing: take N messages, route them by server, bulk insert, then mark those servers dirty in their Shard's map, expiring after 1 hour.
- Search: find the Shard, check whether this server is dirty, and if so refresh the index and mark the whole Shard clean, then run the query. The hourly auto-refresh stays on as a backstop: if the Redis map is lost, the system corrects itself within an hour.
Results. In use since January, the system grew to 14 nodes in 2 clusters (n1-standard-8, 1 TB SSD each), almost 26 billion documents in about 16,000 indices, and indexing peaks of about 30,000 messages per second, at 5 to 15% CPU. Four metrics decide when to grow: heap free (running out forces constant stop-the-world GCs and, eventually, a crash), disk free (on GCP disks can grow without a reboot, so disk alone means bigger disks, not more nodes), CPU at peak, and I/O wait. Future work included limiting master-eligible nodes as clusters grow, and moving indices between clusters to shed load or give very busy servers their own index.
Overlooked constraints.
- Lazy indexing makes the first search slow. The initial 7-day phase is a compromise: the user gets results quickly, but early results miss older history.
- Refreshing a shared index costs everyone. Refreshing a Shard for one busy server makes a new segment for all servers in that index. Clearing the whole Shard's dirty flag at once limits that to one refresh per search burst.
- Throwing a cluster away is only cheap if re-indexing is. Rebuilding many large servers at once would load Cassandra and the workers, so lost clusters need a rebuild rate limit.
What Discord sacrificed. Real-time search (new messages appear after a short delay), server-side highlighting, and the convenience of Elasticsearch's own sharding. In exchange it got small, disposable clusters at a cost below message storage.
Deep Dive: segments, refresh and merge cost, with numbersShow
Why a 1-second refresh is expensive here. Each refresh of an index that received new documents creates one Lucene segment. With 1,000 actively written indexes refreshing every second, that is up to 1,000 new segments per second, 3.6 million per hour (handbook's illustration). Each segment has fixed costs: file handles, per-segment data structures in memory, and future merge work. Merging rewrites data, so a document may be copied several times as small segments are merged into larger ones. With a merge factor of 10, a document passes through about log base 10 of (final size ÷ first segment size) merge levels, often 4 to 6, so the disk writes each byte 4 to 6 times. Tiny segments make this worse, because they reach the large tiers through more steps.
With a 60-minute refresh, the in-memory buffer fills and flushes in large segments instead, and many indexes are never refreshed at all in an hour unless someone searches them. If only 5% of servers are searched in a given hour, then 95% of refresh work disappears.
Cost of on-demand refresh at query time. A refresh of a small dirty index takes tens of milliseconds. If a busy server is searched 10 times a minute and receives messages constantly, the first search after new messages pays the refresh, then later searches find the Shard clean. The extra latency is paid at most once per burst of searches.
Why not store the message in Elasticsearch? If each message averages 150 bytes of stored source, 26 billion documents would add about 3.9 TB before replication, and 7.8 TB with one replica. The 14-node fleet had 14 TB of disk in total, so storing the source would have used over half of it. Fetching from Cassandra, which already had to be read for context, was the cheaper choice.
Lesson 7: Indexing trillions of messages, cells, PubSub and Big Freaking Guilds#
Assumptions. The 2017 design (Lesson 6) sharded messages by guild (Discord's internal name for a server) or by DM channel, across two clusters, with a queue feeding bulk-indexing workers. Years later the same design showed five cracks:
- The Redis queue dropped messages. When indexing backed up, usually because an Elasticsearch node had failed, the Redis queue filled, maxed its CPU and started dropping messages.
- Bulk indexing failed as a unit. A batch of 50 messages could belong to 50 different indices on 50 nodes. If any one operation failed, the whole batch was retried. With 100 nodes and batches of 50, one failed node makes about 40% of batches fail, because 1 − (99/100)⁵⁰ ≈ 0.39.
- Big clusters cost too much. Clusters passed 200 nodes. More nodes meant more fan-out per batch, more frequent node failures and more cluster state for the master to manage. Masters ran out of memory, causing indexing failures, backlogs, slow queries and timeouts.
- No safe upgrades. Draining 200-node clusters would take too long, so OS and Elasticsearch versions fell behind. Patching Log4Shell (disabling JNDI lookups with log4j2.formatMsgNoLookups) required taking search fully offline to restart every node.
- Indices hit Lucene's document limit. Each Elasticsearch shard is one Lucene index, which holds at most about 2 billion documents. A full index rejects all writes. The first fix was working with the Safety team to delete spam guilds, but real communities would eventually pass 2 billion messages too.
The new design.
- Elasticsearch on Kubernetes using the Elastic Cloud on Kubernetes (ECK) operator. Discord had run only stateless services on Kubernetes before. The operator declares cluster topology and config, and handles OS upgrades and safe rolling restarts.
- Cells of small clusters. Many small clusters, grouped into logical cells, keep cluster state small. Each index stays within the guideline of about 200 million messages and 50 GB.
- Dedicated node roles in each cluster: master-eligible nodes with guaranteed resources for coordination; stateless ingest nodes that pre-process and route, and scale with load; and data nodes with enough heap for indexing and queries. Each role runs on its own machine type and node pool.
- Zone resilience: 3 master-eligible nodes (one per zone), at least 3 ingest nodes (one per zone), and shard allocation awareness so an index's primary and replica sit in different zones, with forced awareness balancing indices across zones.
- Google Cloud PubSub instead of Redis for the indexing queue. It guarantees delivery and tolerates large backlogs, so an Elasticsearch failure now slows indexing instead of losing messages. Discord later used PubSub for other jobs, such as task scheduling.
- Batching by destination. A Rust message router streams from PubSub, computes each message's Destination (cluster plus index), and sends it over a channel to a Tokio task for that destination, created on first use. Each task collects chunks for one index and bulk inserts them. A node failure now affects only batches for that node.
New features from cells. Cells made it possible to index the same data along a different dimension. Cross-DM search needs all of a user's DMs together, but DMs were sharded by channel, and fanning a query out to every DM would be far too expensive. Since every message was being re-indexed anyway, DMs are now sharded by user_id in a separate user-dm-messages cell, while guild messages stay sharded by guild_id in a guild-messages cell. Each DM is indexed twice, once per recipient, so DM storage doubles.
Big Freaking Guilds (BFGs). Most guilds stay on an index with one primary shard, so a query talks to one node with no fan-out. A guild near the 2-billion limit gets an index with several primary shards in a dedicated BFG cell. For BFGs the parallel query across shards is worth the coordination cost, and moving them out also stops their expensive queries from slowing small guilds on the same index. The re-index runs live:
- Detect a guild approaching the Lucene limit on index-a.
- Create a new BFG index with twice the primary shard count.
- Dual-index new messages to both.
- Backfill all history into the new index, while queries still use index-a.
- Switch queries to the new index.
- Once it is proven, stop writing to index-a and delete the guild's old documents there.
Results. Trillions of messages indexed, at double the old indexing throughput; median query latency from 500 ms to under 100 ms, p99 from 1 s to under 500 ms; 40 clusters with thousands of indices; upgrades and rolling restarts automatic, with no user impact.
Overlooked constraints.
- Batch composition decides blast radius. Bulk APIs are efficient, but a batch that spans many nodes fails if any node fails. Group by destination before batching.
- Queues need durability that matches the backlog. An in-memory queue is fine until the consumer stalls, which is exactly when you need it most.
- Hard limits hide in the engine. The Lucene document limit is not an Elasticsearch setting you can raise. Watch per-index document counts and migrate before the wall.
What Discord sacrificed. Storage (DMs indexed twice), a full re-index of every message, and the operational learning curve of running stateful systems on Kubernetes. It also accepted multi-shard queries for a small set of guilds.
Deep Dive: the failure math of mixed batches, and how many shards a BFG needsShow
Mixed batches. With N nodes, one failed, and a batch of b messages spread uniformly, the chance a batch touches the failed node is 1 − (1 − 1/N)^b. For N = 100 and b = 50, that is 1 − 0.99⁵⁰ ≈ 39.5%. For N = 400 nodes and b = 50, it falls to about 11.8%, but more nodes also means node failures happen more often. With k nodes down at once, the chance becomes 1 − (1 − k/N)^b. During a zone outage that takes 33 of 100 nodes, it is effectively 100%: every batch fails and the whole queue stalls. With destination batching, a batch touches one index, so the share of failed batches equals the share of data on the failed nodes, here 1% for one node and 33% for a zone, and the rest keep flowing.
Retries make it worse. If 40% of batches fail and are retried in full, the healthy nodes receive their part of each failed batch again, so load on the healthy part of the cluster rises by up to 40% right when the cluster is degraded.
Sizing a BFG index (handbook's illustration). Suppose a guild has 3 billion messages and grows by 2 million a day. The guideline is about 200 million documents per shard. 3 billion ÷ 200 million = 15 shards today. With two years of growth, 2 million × 730 ≈ 1.5 billion more, so plan for 4.5 billion ÷ 200 million ≈ 23 shards. Doubling from 16 to 32 shards leaves room and keeps each shard far below the 2-billion Lucene limit. Each query now fans out to 32 shards in parallel; if each answers in 40 ms and coordination adds 20 ms, the query takes about 60 ms plus the slowest shard's tail, which is why multi-shard indexes are reserved for the guilds that need them.
Family 3: The real-time gateway
Lesson 8: Scaling Elixir to 5 million concurrent users#
Assumptions. Discord was built on Elixir, a language running on the Erlang VM (BEAM), chosen for highly concurrent real-time work. About two years in, it had nearly 5 million concurrent users and millions of events per second. Most of Discord is pub/sub: each connected user gets a session process (a GenServer, one lightweight Erlang process) behind the WebSocket. Sessions talk to guild processes on remote Erlang nodes. Anything published in a guild, such as a message or a presence change, is fanned out to every connected session in it. The design was made for groups of 25 or fewer, but servers grew to 30,000 concurrent users, and at peak guild processes fell behind their message queues. Engineers had to switch off features that produced events.
Problem 1: fan-out cost. Sending a message between Erlang processes was not cheap. One send/2 call took 30 to 70 µs of wall time, because the sender gets de-scheduled. With 30,000 sessions, one publish took 0.9 to 2.1 seconds. An Erlang process is effectively single-threaded, and spawning a new process per publish would break ordering, because clients depend on events arriving in order (linearizability).
Manifold. Manifold spreads the send work to the receiving nodes. The guild process groups session PIDs by their remote node and sends one message per node to a Manifold.Partitioner there. The partitioner hashes PIDs with phash2, splits them into one group per CPU core, and hands each group to a worker that delivers locally. The guild process now calls send/2 only as many times as there are nodes. Ordering holds because each PID always maps to the same worker. It was a drop-in replacement for send/2, and it also cut network traffic between nodes, since one message per node replaces thousands.
Problem 2: shared data lookups. Discord routes entities to nodes with a consistent hashing ring. The ring was owned by one Erlang process through a C port. During reconnect bursts that process could not keep up, and the system overloaded. The cost was simple to estimate: a session node holds up to 500,000 sessions, the average user is in 5 guilds, and one request/reply to another process costs about 12 µs. Reconnecting a whole node meant 500,000 × 5 × 12 µs = 30 seconds of ring lookups.
- ETS (Erlang's built-in mutable table in C) cut reads to about 7 µs, but data is copied in and out, and the ring is large: still 17.5 seconds.
- mochiglobal uses a VM trick: a function that always returns the same constant has its data placed in a read-only shared heap, readable without copying. Compiling a module at run time that returns the ring cut a lookup to 0.3 µs, so 750 ms in total. Rebuilding the module takes up to a second, which is fine because the ring rarely changes. Discord ported it to Elixir as FastGlobal, avoiding atom creation.
Problem 3: stampedes and limited concurrency. Faster lookups removed the back-pressure that had been protecting the next stage. Now nearly 5 million sessions could stampede ten guild registry processes, one per guild node. A timed-out call left its request in the registry's queue, and the session retried after a backoff, so requests piled up without end. Blocked sessions grew their own mailboxes until the Erlang VM ran out of memory, and the outage cascaded. Discord did not want a circuit breaker, because a burst of timeouts would stop all attempts for a while. Instead it built a Semaphore on ets.update_counter, an atomic conditional increment in ETS with write concurrency. A session tries to acquire a slot; if too many calls are in flight, it gives up immediately rather than queueing a call that would time out. Shortly after, the presence services crashed for an unrelated reason, and the session services did not budge. Presence rebuilt within minutes.
Overlooked constraints.
- Removing one bottleneck exposes the next. The slow ring lookup had acted as a rate limiter. Speed it up, and the registry behind it melts. Every speed-up needs a look at what it now overloads.
- A timed-out call is not a cancelled call. In Erlang, as in most RPC systems, the request may still be in the server's queue. Retrying adds more work to a server that is already behind.
- Ordering limits parallelism. Manifold keeps per-session order by always sending a PID through the same worker. Any parallel fan-out must keep a fixed key-to-worker mapping, or clients see events out of order.
What Discord sacrificed. Some idiomatic purity: run-time module compilation and shared-heap tricks are unusual Erlang. The semaphore also rejects requests that might have succeeded, trading some failed work for a system that cannot spiral.
Deep Dive: fan-out cost, before and after ManifoldShow
Before. A guild with 30,000 online sessions publishes one event. At 30 to 70 µs per send, that is 0.9 to 2.1 seconds of the guild process's time. If the guild produces 2 events per second at peak (typing, presence, messages), it needs 1.8 to 4.2 seconds of work per second, which is more than one core can give. The mailbox grows without bound.
After. Suppose the 30,000 sessions are spread over 20 session nodes (handbook's illustration). The guild process sends 20 messages, about 20 × 50 µs = 1 ms per event. The guild can now publish hundreds of events a second. The delivery work, 30,000 local sends, is split over 20 nodes and, within each, over the cores: 1,500 sessions per node across 16 cores is about 94 sends per worker, about 5 ms.
Network. Each event payload, say 500 bytes, used to cross the network 30,000 times, which is 15 MB per event, or 30 MB per second at 2 events per second. With Manifold it crosses 20 times, 10 KB per event. That is the traffic drop Discord saw on guild nodes.
The semaphore limit. If a registry process handles one lookup in 100 µs, it serves 10,000 per second. Letting each session node keep at most, say, 100 calls in flight to each registry, with timeouts of 5 s, bounds the queue at 100 × number of session nodes. A call that cannot get a slot fails in microseconds and can retry later, instead of adding to a queue that would take seconds to drain.
Lesson 9: Using Rust to scale Elixir for 11 million concurrent users#
Assumptions. Discord changed the Member List (the panel of members on the right) to send updates only for the visible part of the list, rather than for every member. That cuts network traffic, CPU and battery use. But the server must now keep, per guild, a sorted set of hundreds of thousands of members, take many changes per second, and report the index where each item was inserted or removed, so clients can update the visible window.
Why Elixir struggled. Elixir's data is immutable. A change creates a new structure, so adding a member to a list of 100,000 means building a list of 100,001. Benchmarks:
| Approach | Small set | 250,000 items, worst case |
|---|---|---|
| Sorted List wrapper | 500 to 3,000 µs at 5,000 items | about 170,000 µs, insert at end |
| Erlang ordsets | 0.008 to 288 µs | about 27,000 µs |
| Skip-list of small ordsets, called Cells | 5,000 µs at the end, but 19,000 µs at the start | |
| OrderedSet with Cells that grow and split | 4 to 34 µs | 4 µs at the start, 640 µs at the end |
| Rust SortedSet NIF | 0.4 to 2.85 µs first prototype | 0.61 to 3.68 µs, up to 1,000,000 items |
MapSet was ruled out first because it does not keep order. The skip-list design chained small ordsets in Cells that record their first item, last item and count, so a lookup walks Cells and then does a fast ordset operation. Its new worst case, inserting at the front, cascaded: each full Cell pushed its last item into the next. Letting Cells swell and split turned that cascade into a single split, but it still only scaled to about 250,000 members.
The Rust NIF. BEAM has three kinds of functions: ordinary Erlang or Elixir functions, built-in functions (BIFs), and NIFs (Native Implemented Functions) written in C or Rust and loaded into the VM. A badly written NIF can crash the whole VM or stall its schedulers. Rustler makes NIFs safe: Rust's guarantees prevent crashes and memory leaks. A one-week spike showed 0.4 to 2.85 µs per insert. The full version, supporting most Erlang terms, measured 0.61 to 3.68 µs across sets from 5,000 to 1,000,000 items. Every operation finishes far under 1 ms, the limit beyond which a NIF should yield to the BEAM scheduler, so no special yielding code was needed. To callers it looks like an ordinary Elixir module. It now powers every guild, from three friends to 200,000 players, with no extra memory pressure, and Discord released it as open source.
Overlooked constraints.
- NIFs run on the scheduler. A NIF that runs for milliseconds blocks a BEAM scheduler thread and hurts every process on it. Keep NIF calls short, or use dirty schedulers or yielding.
- Mutable state inside an immutable language. The Rust set is a resource the guild process owns. Elixir's usual "copy on change" safety no longer protects it, so only the owning process should touch it.
- Index reporting is what makes windowed updates possible. A plain sorted set is not enough. The client needs positions so it can patch only the visible slice.
What Discord sacrificed. A second language and toolchain in the core real-time path, and the risk that native code brings to the VM, reduced by Rustler but not removed. In return, the guild hot path got about 100 to 1,000 times faster in the worst case.
Deep Dive: why the sorted set needs to be fast, with numbersShow
Take a guild with 200,000 online members (handbook's illustration). People come online, go offline, change status and change roles. If 2% of members change state each minute, that is 4,000 changes a minute, about 67 per second. Each change is a remove plus an insert in the sorted set, so about 134 operations per second.
With OrderedSet at a worst case near 640 µs, that is 134 × 0.64 ms ≈ 86 ms of the guild process's time per second, close to 9% of one core, before any other guild work. During a raid, a big announcement or a reconnect wave, changes can grow 10 to 50 times, which is 0.9 to 4.3 seconds of work per second. The guild falls behind and every event in it is delayed.
With the Rust set at under 4 µs, 134 operations take about 0.5 ms per second, and even a 50 times burst needs only about 27 ms per second.
Why the index matters. A client viewing members 0 to 99 should get an update only when a change falls in or above that window. With the index, the server can tell which clients' ranges are affected and send them "insert at 37" or "delete at 52". Without it, the server would have to send the whole list or resend whole ranges, which for 200,000 members at about 50 bytes each is about 10 MB.
Lesson 10: Why Discord switched Read States from Go to Rust#
Assumptions. The Read States service tracks which channels and messages each user has read. It is on the hot path: it is used on every connect, every message sent and every message read. There is one Read State per user per channel, billions in total, each with counters that must update atomically and often reset to zero, such as the @mention count. Each server keeps an LRU cache holding millions of users and tens of millions of Read States, taking hundreds of thousands of updates per second. Cassandra backs the cache: a Read State is written on eviction, and every update schedules a write 30 seconds later, giving tens of thousands of database writes per second.
The Go problem. The Go version (built with Go 1.9.2; 1.8 and 1.10 were tried too) was fast most of the time, but showed latency and CPU spikes about every 2 minutes. The code allocated very little, so the spikes were not from garbage volume.
- Go forces a GC at least every 2 minutes, whatever the heap growth.
- Tuning GC percent changed nothing, because the service did not allocate fast enough to trigger GCs more often.
- The spike was large because the collector had to scan the whole LRU cache to prove what was still referenced. The cost was proportional to live memory, not garbage.
- Splitting it into many smaller partitioned LRU caches shrank the spikes, but a smaller cache meant more misses and database loads, so p99 latency rose. The team settled on a compromise size and moved on.
The Rust rewrite. Rust has no garbage collector. Its ownership model tracks at compile time who can read and write memory, and frees memory the moment it is no longer used. An evicted Read State is freed at once, with no background scan. At the time, async Rust was only on the nightly compiler, and Discord chose to run nightly until async was stable. The bet worked. The post adds that Discord had reached 250 million+ users with fewer than 50 engineers, partly by adopting promising new technology early (Elixir, React, React Native, ScyllaDB).
The port began as a rough translation and got smaller: Rust's generics removed code Go needed for lack of them, and Rust's thread-safety checks removed manual cross-goroutine memory protection. With only basic tuning, Rust matched Go's latency with no spikes. After profiling it beat Go on latency, CPU and memory, through:
- a BTreeMap instead of a HashMap in the LRU cache, to save memory;
- a metrics library using modern Rust concurrency;
- fewer memory copies.
Rollout was one canary node (which found a few missing edge cases), then the whole fleet. Then, since a bigger cache no longer meant longer GCs, the cache capacity was raised to 8 million Read States per server, with more memory per machine. Average response time fell to microseconds, and the worst @mention time to milliseconds. Later, upgrading Tokio to 0.2 reduced CPU for free.
Overlooked constraints.
- GC cost follows live data, not garbage. A cache-heavy service is the worst case for a tracing collector, because the cache is exactly the live memory it has to scan. Low allocation does not help.
- Cache size and GC were coupled. In Go, the right cache size for hit rate was the wrong one for pause time. Removing the GC removed the trade-off.
- Write-behind needs a durability story. A Read State lives in memory for up to 30 seconds before reaching Cassandra. If a node crashes, those updates are lost, which is acceptable for "last read" markers but would not be for payments.
What Discord sacrificed. A mature async ecosystem (nightly Rust for a while), and the cost of a rewrite. The post itself warns against rewriting things in Rust without a reason; here the reason was a measurable latency problem in a small, self-contained service.
Deep Dive: why the 2-minute GC spike was so large, with numbersShow
Suppose one Go server holds 30 million Read States at about 100 bytes each, plus map and pointer overhead, about 5 GB of live heap (handbook's illustration). A tracing GC must mark every reachable object. If marking runs at roughly 1 GB per second per core and Go uses about 25% of the cores for background marking, an 8-core machine gives 2 cores, so marking 5 GB takes about 2.5 seconds. During that time the GC also steals time from the program, through assist work and write barriers, so request latency rises. That is the regular spike.
Shrinking the cache. Cutting the cache to 1 GB of live heap cuts marking to about 0.5 seconds, so spikes shrink. But if the hit rate falls from 98% to 90%, and a miss costs a 2 ms Cassandra read, the average extra latency per request rises from 0.02 × 2 = 0.04 ms to 0.10 × 2 = 0.2 ms, and p99 is now set by misses.
In Rust, eviction frees memory at once at a cost of tens of nanoseconds per object, spread evenly over time. With no collector, an 8 million entry cache costs nothing extra at the tail. That makes the cache size a pure memory-versus-hit-rate choice, which is the trade-off you want to be making.
Lesson 11: Reducing WebSocket traffic by 40 percent#
Assumptions. Clients receive real-time updates through the gateway WebSocket. Since late 2017 it was compressed with zlib, shrinking messages 2 to 10 times. Discord wanted to cut bandwidth further, mainly on iOS and Android, expecting a faster-feeling app. Zstandard (zstd) promised better ratios, faster compression and dictionaries. A 2019 attempt (desktop only) used too much RAM. Most gateway payloads are small and well structured, which seemed ideal for dictionaries.
Dark launch. Adding zstd to the desktop, iOS and Android clients would take about a month before any real measurement. Instead, the gateway compressed a small share of production traffic with both zlib and zstd, recorded metrics, and threw the zstd output away. That let the team iterate in days. The metric was compression ratio = uncompressed size ÷ compressed size.
First result: worse. Plain zstd lost to zlib. A user_guild_settings_update scored 13.95 with zlib against 12.26, and a MESSAGE_CREATE averaged about 250 bytes with zlib but over 750 with zstd. The reason: zlib ran in streaming mode, with one compression context for the life of the connection, so each new message could refer to bytes from earlier ones. Zstd was compressing each message alone, with no history, which is hopeless for payloads of a few hundred bytes. The Elixir bindings did not support streaming, so Discord forked ezstd (chosen because it had dictionary support), added streaming, and contributed it back. With streaming, MESSAGE_CREATE's ratio rose from about 6 to almost 10, its size fell from 270 to 166 bytes, and compression took less than half as long per byte.
Tuning. Three zstd parameters trade ratio for memory and speed: chainlog, hashlog and windowlog, each a power of two. Discord chose level 6, chainlog and hashlog 16, windowlog 18, slightly above defaults, so that one context per connection still fits comfortably in a gateway node's memory.
Dictionaries: tried and dropped. A dictionary pre-seeds the compressor, which helps most for the first few KB of a stream. Both sides need the same dictionary, so Discord trained two with zstd --train (one for JSON, one for ETF, the Erlang binary format clients can choose), using 120,000 anonymised messages, since dictionaries contain fragments of their training data and would ship inside clients.
- The READY payload (sent on connect, with guilds, settings and read states) went from 2,517,725 bytes to 306,745 with default zstd, and to 306,098 with the dictionary: only about 600 bytes better.
- TYPING_START: 636 bytes went to 466 without the dictionary and 187 with it.
- In production the gains were mixed, and for MESSAGE_CREATE the dictionary made things worse. The small win did not justify the extra complexity in the gateway and clients, so dictionaries were dropped.
Buffer upgrades: tried and reverted. Traffic is diurnal, and long-lived WebSockets do not suit normal autoscaling, so gateway nodes have spare memory off-peak. A feedback loop on each node watched memory and upgraded a share of new connections to larger buffers (each of the three parameters plus one, roughly doubling context memory). It reached only about 30% upgrades instead of the expected 70%. The cause was memory fragmentation: the BEAM held much more system memory than the connections needed, because the zstd contexts (C code in a NIF) are allocated through driver_alloc. Tuning allocator settings might have fixed it, but the effort and complexity were not worth it, so the loop was removed.
Rollout. The gains were big enough to ship to desktop too. Bindings were zstd-jni on Android, zstd-safe in Rust on desktop, and new bindings written for iOS. Since a mistake could make Discord unusable, the rollout was behind an experiment for quick rollback, validation of lab results and checks on baseline metrics. It reached all users on all platforms over a few months.
Passive Sessions V2. The dark-launch metrics showed something unexpected: PASSIVE_UPDATE_V1 was about 2% of dispatches but over 30% of gateway bytes. A passive session is how a client stays lightly synced with a server it is a member of but is not looking at: instead of the full firehose of messages, it gets periodic updates of channels, members and members in voice, and is upgraded to a normal session when the user opens the server. V1 sent the whole list each time, even if one item changed. V2 sends only the delta. Passive updates fell from 35% to 5% of gateway bandwidth, about 20% of the total.
Overlooked constraints.
- Streaming compression costs memory per connection. Every WebSocket keeps a compression context for its whole life. With millions of connections, context size, not CPU, sets the limit, which is why parameter choices were bounded by node memory.
- Measurements find more than you set out to measure. The biggest single win, passive session deltas, came from looking at per-dispatch byte counts collected for a different project.
- Process memory is not live memory. A control loop based on OS memory usage will be fooled by allocator fragmentation. It needs the allocator's own statistics, or a safety margin.
What Discord sacrificed. More memory per connection than plain zlib defaults would use, a forked library to maintain upstream, and new iOS bindings. It also knowingly left the dictionary and buffer-upgrade gains on the table to keep the gateway simple.
Deep Dive: why streaming matters for small messages, and what deltas saveShow
Compression needs context. LZ-style compressors such as zlib and zstd replace repeated byte sequences with back-references to earlier data. In a 270-byte MESSAGE_CREATE, there is little repetition inside the message itself, but field names such as "channel_id", "author", "content" and "timestamp" appear in every message. With a context kept across the stream, the second message can point back to those names in the first, so each name costs a few bytes instead of its full length. Without context, the compressor also pays frame headers and setup on every message, which is why plain per-message zstd came out three times larger than streaming zlib.
Memory per connection (handbook's illustration). A zstd window of 2 to the 18th power is 256 KB of history. Hash and chain tables of 2 to the 16th entries at 4 bytes each are 256 KB each. A rough upper bound for one context is about 768 KB, though actual use depends on how much of the window has filled. On a node with 100,000 connections, full contexts would need about 75 GB, which shows why window and table sizes had to be chosen with node memory in mind, and why upgrading each by one, doubling them, was only possible off-peak.
Delta updates. Suppose a passive session for a server with 2,000 channels and members in voice receives a full snapshot every 10 seconds, about 40 KB compressed. That is 4 KB per second per passive session. A user in 50 large servers with passive sessions would get 200 KB per second, mostly redundant. If on average 1% of items change per interval, a delta is about 400 bytes, a 99% saving for that dispatch. Across the gateway, passive updates fell from 35% to 5% of bandwidth.
Lesson 12: Push notification bursts of over a million per minute with GenStage#
Assumptions. One summer, the r/Overwatch server passed 25,000 concurrent users and Pokémon GO servers multiplied. Burst notifications, for example a mention to a big server, slowed the mobile push system and sometimes stopped it. Pushes arrived late or not at all. Pushes are sent only to users who are not active in the app. The bottleneck was sending to Google's Firebase Cloud Messaging.
The fix. Switching from HTTP to Firebase's XMPP interface raised throughput at once, but XMPP allows at most 100 pending requests per connection: with 100 in flight, you must wait for an acknowledgement before sending another. The system had to keep every connection under that limit during bursts.
GenStage is an Elixir behaviour for passing events between processes with back-pressure. Stages are producers, consumers or both; a stage that only produces is a source, one that only consumes is a sink. Discord used two:
- Push Collector (producer), one per machine, which collects push requests.
- Pushers (consumers), many per machine, each with its own XMPP connection. A Pusher demands at most 100 requests, and asks for more only when Firebase acknowledges one.
Back-pressure means the collector never sends a Pusher work it did not ask for, so no connection is ever over its limit. Load shedding handles what back-pressure pushes upstream: the collector has a bounded buffer (GenStage's buffer_size option). Normally it is empty. In a huge burst, about once a month, it fills and the collector drops new push requests.
An incident. In the first burst after launch, the rate rose, the buffer blipped and drained, then filled because Pushers could not keep up, peaked and shed some requests for about a minute, and the system was back to normal about five minutes after the burst began. Users saw no impact apart from a few dropped notifications. Without shedding, the collector might have fallen over and the system might not have recovered. Push volume more than doubled after that.
Overlooked constraints.
- Back-pressure moves the queue; it does not remove it. Bounded demand protects Firebase connections but pushes the backlog to the collector, which then needs its own limit.
- Dropping is a product decision. Discord judged a few lost pushes acceptable for notifications. The same design would be wrong for messages, which must never be dropped.
- The external limit sets capacity. Throughput per connection is at most 100 ÷ round-trip time. More throughput needs more connections, not faster code.
What Discord sacrificed. Guaranteed delivery of every notification during extreme bursts. It gave that up to keep the push system alive and fast for everyone else.
Deep Dive: sizing pushers with the 100-pending limitShow
Throughput per XMPP connection = pending limit ÷ round-trip time. If Firebase acknowledges in 50 ms on average, one connection sends at most 100 ÷ 0.05 = 2,000 pushes per second (handbook's illustration). A million pushes a minute is about 16,700 per second, so the fleet needs at least 9 connections, and about 15 to 20 to allow for slower acknowledgements and failures.
Burst behaviour. Suppose a burst arrives at 40,000 pushes per second for 60 seconds, while 20 connections drain 40,000 per second at 50 ms but only 20,000 per second if Firebase slows to 100 ms. In the slow case the excess is 20,000 per second, and a buffer of 200,000 fills in 10 seconds. After that, half the incoming pushes are dropped until the burst ends. This matches the shape of Discord's incident: fill, shed, recover.
Why not an unbounded buffer? At 20,000 extra per second for 60 seconds, the backlog would be 1.2 million pushes, about 1.2 GB at 1 KB each, held in one Erlang process. Draining it at the spare rate after the burst would take minutes, and pushes delivered minutes late are worth little. A bounded buffer gives fresh notifications priority over stale ones.
Lesson 13: MaxJourney, a million and more online users in a single server#
Assumptions. Each guild has one Elixir process as the routing point for everything in it. Each connected client has a session process. The guild tracks member sessions and fans every action out to them, and sessions forward over WebSockets. Some actions go to everyone; others need permission checks using the user's roles and the channel's settings. The guild cannot simply be split into many processes, because some features need a full view, such as who is in a voice channel or channel member lists. Midjourney has over 10 million members, with over 1 million online at any time.
Fan-out is quadratic. Activity grows with the number of people online, and so does the work per action. If 1,000 people each post once, that is 1 million deliveries. With 10,000 it is 100 million; with 100,000 it is 10 billion. Some operations also get slower as a server grows, which hurts responsiveness as well as throughput.
Measure first.
- Wall-time sampling: take about a thousand stack traces of a process with Process.info, 100 ms apart, which takes a couple of minutes and shows what it is doing.
- Per-message-type instrumentation of the guild event loop: count, min, max, average and total time for each type. Anything under 1% of total time can be ignored unless it is bursty. Graphs by type showed each optimisation's effect, for example on presence updates.
- Heap analysis: erts_debug.size is too slow for large objects, so Discord wrote a helper that samples large maps and lists to estimate memory. It showed which fields matter for GC and which do not.
Passive sessions. Users in many servers often never open most of them. A passive connection gets only limited updates until the user clicks in, with no per-message permission checks. About 90% of user-guild connections in large servers were passive, cutting fan-out work by 90%. Because work is quadratic, a 10 times reduction in work allows only about a √10 ≈ 3 times larger community.
Relays. Relays sit between the guild and sessions. Each holds up to 15,000 sessions and does the fan-out and permission checks for them, so one guild can use many cores and machines. This took the team to communities in the hundreds of thousands. It meant deciding which operations must stay in the guild, which must be in relays and which can be in either. Shared fan-out logic became a library; voice state is simply proxied by relays to the guild. At first each relay held the full member list, which was simple, but at Midjourney scale there were dozens of copies of tens of millions of members in RAM, and creating a relay stalled the guild for tens of seconds while it serialized them. Relays now get only the small share of members they need.
Keeping the guild responsive. For responsiveness, the useful metric was per-call duration, not total time.
- Workers plus ETS. Rare operations that walk all members, such as working out who can see an @everyone ping, could take seconds. Elixir processes do not share heaps, so the member list moved to ETS, a shared in-memory table. The guild keeps only a small set of recent changes in its own heap. Expensive jobs go to worker processes that read the ETS table while the guild keeps working. A smaller heap also means faster GC. The same trick speeds guild hand-offs between machines for deploys and maintenance: a worker copies most members, which can be several GB, while the old guild keeps running, saving minutes of stall per hand-off.
- Manifold offload. A separate sender process does the Manifold sends to relay nodes, so the guild does less work and is shielded from BEAM back-pressure when a network link backs up. At first it made things much worse. Tracing every GC with erlang.trace showed full GCs triggered by the virtual binary heap, a limit meant to free off-heap binaries promptly. The guild kept doing full GCs to reclaim a few hundred KB while copying a multi-GB heap. Raising the process flag min_bin_vheap_size to a few MB stopped it, and offload then gave a clear win.
Overlooked constraints.
- Quadratic work means each fix buys less than it seems. A 10 times cut in work gives only a 3 times larger server. Long-term scaling needs changes to the shape of the work, such as relays and passive sessions, not just faster code.
- A single ordering point remains. The guild still sequences events, so its per-event cost sets the ceiling. Everything that can leave it must leave it.
- GC heuristics can turn small savings into large costs. A heuristic built for small heaps did huge work on a multi-GB heap. Large-heap processes need their GC flags reviewed.
What Discord sacrificed. Simplicity: a guild is now a guild process, many relays, ETS tables and worker processes, with logic split across them. Passive users also see some server state with a delay until they open the server.
Deep Dive: the quadratic fan-out math, and what relays and passive sessions buyShow
Let n be the number of online members, and suppose each sends messages at rate r. Total messages per second = n × r. Each message is checked for and delivered to roughly n sessions, so deliveries per second ≈ n² × r.
At Midjourney scale (handbook's illustration). With n = 1,000,000 and r = 0.001 messages per second per person (one message every 17 minutes), there are 1,000 messages per second. Each fans out to 1 million sessions: 1 billion deliveries per second. If a permission check plus enqueue takes 1 µs, that is 1,000 core-seconds per second, so about 1,000 cores of work.
Passive sessions remove about 90% of recipients: 100 million deliveries per second, about 100 cores. Relays split that across machines: at 15,000 sessions per relay, there are about 67 relays for 1 million sessions, and with 90% passive, each relay serves about 1,500 active sessions per message, so about 1.5 ms of work per message per relay at 1 µs per session. With 1,000 messages per second, each relay needs about 1.5 cores. The guild process itself sends one message per relay node per event through the sender, perhaps 67 sends at 50 µs, about 3.4 ms per event, 3.4 seconds of work per second for 1,000 events, too much for one process at that message rate. In this illustration the guild, not the relays, becomes the limit, so every microsecond of per-event cost left inside the guild matters, and any per-event work that can move out of it, such as the sends moved by Manifold offload, has to move. The single ordering point is the final limit.
Square-root rule. If capacity is fixed at C deliveries per second, the largest n is about √(C ÷ r). Cutting work per delivery by 10 times multiplies C by 10 and the largest n by √10 ≈ 3.16, which is the 3 times figure in the post.
Family 4: Voice and video
Text chat tolerates a second of delay. Voice does not. Once the delay between mouth and ear grows past roughly 150 to 200 ms one way, people start talking over each other, and the call stops feeling like a room. The four lessons in this family show how Discord built a voice system for millions of simultaneous users, moved it onto a new kind of network, and then encrypted every call end to end without losing the features that need a server in the middle.
Lesson 14: Handling 2.5 million concurrent voice users with WebRTC#
Assumptions. In September 2018 Discord described a voice and video system serving more than 2.6 million concurrent voice users. The authors set out several working assumptions:
- Every call is a group call. Even a two-person DM call is built as a multiparty, client-server call, because channels with hundreds of listeners and a few active speakers are normal. Peer-to-peer mesh calls, where each person sends to everyone else, need upload bandwidth that grows with the number of people, so they break down past a handful of participants.
- Traffic is bursty and mostly silent. In a large channel only a few people speak at once. Most clients send nothing most of the time.
- Users must stay hidden. Gamers attract denial-of-service attacks. If clients connected to each other directly, every participant would learn every other participant's IP address.
- Latency matters more than perfect delivery. A lost voice packet is better skipped than resent, so media runs over UDP.
The architecture. WebRTC is the open standard browsers use for real-time audio and video. It bundles codecs, jitter buffers, echo cancellation, and a connection setup process. Discord used the browser's WebRTC stack on the web, but on desktop, iOS and Android it built one shared C++ media engine on top of the WebRTC native library. Owning the engine let them add features a browser cannot offer: their own volume control without the operating system's automatic "ducking" of other audio, raw audio access for voice activity detection and for sharing game audio and video, using less CPU and bandwidth during silence, push-to-talk that works system-wide even when Discord is not focused, and extra per-packet information such as a "priority speaker" flag. The cost is that every WebRTC upgrade has to be merged by hand into a customized fork, which the authors called painstaking.
The protocol shortcuts. Standard WebRTC connects peers in three steps. SDP (Session Description Protocol) is a text blob describing codecs and streams, often around 10 KB in each direction. ICE (Interactive Connectivity Establishment) tries many network paths to punch through NAT routers. DTLS-SRTP negotiates encryption keys and then encrypts media. Discord removed most of this on native clients:
- No SDP. Native clients call the lower-level webrtc::Call API directly. A join exchanges about 1,000 bytes: the server's address and port, the encryption method and key, the codec, and stream identifiers.
- No ICE. Every client talks to a Discord relay server, never to another client, so there is no path search. One known server address is more reliable behind NAT, and client IPs stay private. Clients send periodic pings so firewalls keep the UDP mapping open.
- Salsa20 instead of DTLS-SRTP. Encryption plugs in through webrtc::Transport, using a key handed out at join time.
- Silence means no packets. Clients stop sending entirely when the user is quiet. Both the sender and the receiver must therefore accept that a stream can stop at any moment, and the server must rewrite sequence numbers so the gaps do not look like packet loss.
Browsers cannot skip these steps, so they still use SDP, ICE, DTLS and SRTP, but the client synthesizes the SDP locally from a small exchange of under 1,200 bytes. The backend bridges the two worlds: a browser user and a desktop user in the same channel hear each other because the server translates between transports and encryption schemes.
The backend. Three kinds of services cooperate:
- Gateway holds each client's main WebSocket, which carries the user's voice state (which channel they are in, muted, deafened).
- Guilds owns each server's state. All voice channels in one guild are placed on the same voice server, which keeps placement simple.
- Voice servers are made of a signaling component and a homegrown C++ SFU. An SFU (Selective Forwarding Unit) receives each speaker's stream once and forwards copies to listeners without decoding or mixing them, which is far cheaper than mixing. The signaling part creates stream IDs and keys and forwards speaking indicators. The SFU forwards media, drops packets from server-muted users, translates between native and browser transports, and reads RTCP receiver reports (feedback packets saying how much arrived) to tell senders how much video bandwidth is available.
Signaling is written in Elixir, like the rest of Discord's real-time systems. Voice servers report health and load to etcd, a consistent key-value store. The Guilds service watches etcd, picks the least-loaded voice server in the guild's region, pushes the current voice states to it, and tells clients where to connect. The client then opens a second WebSocket, directly to the voice server, for voice signaling, and starts sending UDP media.
Failover. Every call is started and restarted by the client, which keeps the server side simple:
- SFU crash. The signaling component restarts the SFU and rebuilds its state. Clients do nothing; they lose a few packets. The same mechanism lets Discord update SFU binaries with no downtime.
- Whole server failure. The server stops answering health pings and is removed from etcd. The client sees its voice WebSocket drop and asks, through the gateway, for the server to be pinged. Guilds confirms the failure, picks a new server, pushes voice states to it, and clients reconnect.
- DDoS. An attack shows up as a sudden rise in incoming packets. The server is treated as failed, clients move, and the server rejoins the pool once the attack ends. Because clients only know the address of the current voice server, attackers must find each new one.
- Region change. Moving a guild to another region uses the same reassign-and-reconnect path.
Scale in 2018. Gateway and Guilds ran on Google Cloud. Voice ran on more than 850 servers in 13 regions spread across more than 30 data centres, on physical machines rented from a handful of providers with heavy redundancy. Peak load was over 2.6 million concurrent voice users, more than 220 Gbps of egress and 120 million packets per second. The team planned to use quality metrics to detect problems automatically, and at the time video was offered only in DMs, with Scalable Video Coding and hardware encoding for screen share on the roadmap. A handful of engineers covered the client, the server and operations.
Overlooked constraints.
- Packets per second, not bandwidth, is often the bottleneck. Voice packets are small, so a server hits its kernel and NIC packet limits long before it fills its network link.
- Server-side features force a server in the media path. Server mute, DDoS shielding and IP privacy all need a relay that sees traffic, which is the main reason Discord could not use pure peer-to-peer.
- A fork is a long-term tax. Each feature added to the custom media engine makes every future WebRTC merge more expensive.
What Discord sacrificed. Standards compliance and simple upgrades: native clients speak a custom protocol, so Discord owns the media engine forever. Placing a whole guild on one server is simple but means one very busy guild can concentrate load. And relaying everything through Discord means Discord pays for every byte of media egress.
Deep Dive: per-server and per-user voice numbersShow
These are the handbook's illustrations, derived only from the totals in the post.
Users per server. 2.6 million users ÷ 850 servers ≈ 3,060 concurrent users per voice server on average. Real load is uneven, so busy servers carry more.
Egress per user. 220 Gbps ÷ 2.6 million ≈ 85 kbps per user. A single Opus voice stream at typical quality is about 32 to 64 kbps. An SFU sends each listener one stream per active speaker, so 85 kbps on average suggests listeners usually hear one or two speakers at once, plus overhead and some video.
Packets per user. 120 million packets per second ÷ 2.6 million ≈ 46 packets per second per user. Opus usually sends one packet every 20 ms, so 50 packets per second per active stream. An average near 46 fits "each listener receives roughly one active stream most of the time".
Why the SFU wins over mixing. A mixer (MCU) decodes every speaker, adds the audio, and re-encodes a custom mix per listener, because each listener must not hear themself. With k speakers and n listeners that is k decodes and n encodes per 20 ms frame. Opus encoding costs on the order of 1 to 2% of a core per stream (handbook's illustration), so 3,000 listeners would need 30 to 60 cores of encoding alone. An SFU only copies bytes and rewrites headers, which costs microseconds per packet.
Silence suppression savings. In a 20-person channel where 2 people speak at a time, sending only from speakers cuts upstream packets by 90%. Downstream, each listener gets 2 streams instead of 19. Without suppression, the SFU would forward 20 × 19 = 380 streams; with it, about 2 × 19 = 38. That tenfold cut is what makes 1,000-person channels practical.
Why skip SDP. 10 KB each way versus 1 KB is small for one call, but every reconnect after a failover repeats it. If 100,000 users move at once after a server dies, that is about 2 GB of SDP traffic versus 200 MB, and more importantly fewer round trips before audio returns.
Lesson 15: Moving Discord voice to the edge#
Assumptions. For most of its history, Discord could place a voice server in only about 30 cities, the places where large cloud and hosting providers had data centres. Users in Reykjavik or Auckland routed hundreds or thousands of kilometres to the nearest region, and every kilometre added latency to every packet. Light in fibre travels about 200 km per millisecond, so 1,000 km adds about 5 ms each way before any router queueing. Starting in 2025, Discord moved voice and video onto Cloudflare's edge network, which runs in over 300 cities. A year in, more than 80% of voice and video traffic ran there, and over 70% of migrated regions showed year-over-year quality gains. Frankfurt saw average ping down 34% and packet loss down 42% compared with the previous vendor. The working assumption was simple: closer servers make better calls.
Surprise 1: Iceland and call placement. In late February 2025, Discord put voice servers in Cloudflare's Reykjavik PoP (point of presence, a small edge site). Calls with only Icelandic users improved: ping fell 9% and packet loss 11%. But mixed calls got worse. Ping for non-Icelandic users on calls hosted in Iceland rose 2.7 times, and packet loss rose 9%. The cause was the placement model from Lesson 14: one SFU hosts the whole call, and everyone connects to it for the call's lifetime. One Icelandic user calling three friends in Germany could pull the call to Reykjavik, and three people suffered so one could gain. The lesson was that for mixed-region calls, host placement matters more than coverage. Discord changed the plan: replace existing regions one at a time first, and leave new coverage such as Reykjavik for later, paired with smarter placement.
Surprise 2: Rotterdam and peering. In late April 2025, Rotterdam traffic moved to Cloudflare's Amsterdam PoP. Most ISPs looked fine. Within hours, users on Orange, one of France's largest ISPs, saw call latency above one second at peak, and freeze ratio regressed 30%. The fault was the network path: Orange reached Cloudflare through Telia's transit backbone, and the Telia-to-Orange handoff was already saturated at peak. (Transit is paid carriage across another network; peering is a direct link between two networks.) Every megabit Discord moved made it worse. About ten days in, Discord drained Rotterdam's Cloudflare hosts and fell back to the prior vendor. Cloudflare began direct peering talks with Orange and suggested SFUs in Paris and London for shorter paths. From then on, rollouts were paced by peering analysis, not by capacity: a region waited until Cloudflare's links to its major ISPs had headroom.
Discovery: hosts dial in. On the old fleet, Discord provisioned a host and registered it. Cloudflare's scheduler starts and reclaims machines on its own timeline, so a host can appear with no warning. Discord built a discovery service where each voice host registers on start, re-registers periodically, and unregisters on shutdown. Registrations live in Valkey (the open-source Redis fork), in a managed Google Cloud memory store, with a ten-minute TTL, so a host that stops checking in disappears on its own. The old etcd-based discovery from Lesson 14 had been built for a much smaller fleet. At 25,000 voice hosts on Cloudflare, discovery latency was climbing, and one large rollout could have broken it. New hosts went to Valkey, the legacy SFU records were moved with double writes through the cutover, and etcd was retired.
Hosts as spot instances. Cloudflare's platform was built for short-lived V8 isolates (the lightweight sandboxes behind Workers), not for long-lived UDP sessions. A voice host holds a stateful control plane (who is in the call, who is muted, where streams go) and a stateless media plane (the UDP packets). Restarting the host drops the call. Cloudflare's scheduler can also reclaim a running host when it needs the capacity, and containers are rebooted at least once a month for maintenance. Discord adapted in two ways:
- Recreate, not restart. Every code change recreates the container from a new image. A deployer asks Cloudflare to recreate hosts still on the old image and polls until each returns.
- Delayed exit. Recreating a whole PoP at once could briefly drop the host count to zero. The container supervisor catches the shutdown signal and delays the real exit by five minutes, so replacements come up first and reconnecting calls land on new hosts in the same region instead of bouncing to another one.
Density: two, four, eight workers. The first container ran four worker processes per host, the density that worked elsewhere. In early May 2025, US East showed steady packet loss of 1.5 to 2%, against under 0.5% on the prior provider. On bare metal, each worker had its own NIC transmit queue. Cloudflare's container runtime did not yet expose multi-queue NICs, so all four workers shared one queue, and the kernel dropped UDP packets at the send buffer during peaks. Discord halved density to two workers, and loss returned to parity, at the cost of fewer calls per host. Cloudflare shipped a UDP buffer fix by early June, four workers were piloted in Amsterdam, and by late September eight workers per host became the global default.
The 25-second hangs. Some voice instances, most often in Los Angeles, froze for over 25 seconds and left nothing in their logs. Cloudflare's kernel team had seen VM-level I/O stalls from another customer too. The cause was page cache buildup on newer disks: Discord's write-heavy workload filled the cache with dirty pages, the kernel eventually flushed several GB at once, and every other writer on the block device waited for the flush. PoPs with newer hardware ran more Discord load, so they stalled more. Cloudflare first tuned the kernel to flush dirty pages more often, then changed the sync I/O path in its VMM (virtual machine monitor). Discord's part was reporting the symptom with enough telemetry to correlate against host metrics.
The European ping spikes. In late 2025 Bucharest and Stockholm moved onto a new Rust-based SFU on Cloudflare. Peak-hour ping climbed, and by February client ping spiked above half a second, with reports of robotic audio reaching support and Reddit. Discord shifted some European traffic away while the two companies debugged for several weeks. Routing, peering and DDoS theories all failed.
- The probe. Discord's health-check packets carry a fixed payload signature. Cloudflare's performance team wrote an eBPF program (a small, safe program loaded into the kernel) that timestamped every health-check as it passed through the host network stack. Comparing arrival and departure times showed the physical-to-virtual NIC path and back were clean. The time was being lost inside the VM, in Discord's own process.
- Write starvation in the app. With direct access to a container, Cloudflare saw futex stalls up to 860 ms. Per-thread sampling showed one thread pinned at 100% of a core during every spike, while socket receive buffers grew. The SFU ran eight worker threads, each with its own UDP socket, a single-threaded Tokio runtime (Tokio is Rust's main async runtime) and a select! loop over two futures: recv, which reads packets, and a flush timer, which sends queued packets. When the receive buffer is never empty, recv is always ready, so the loop keeps choosing it and the flush timer never runs. Tokio's cooperative budget of 128 polls is meant to stop this, but at peak 128 polls pass in microseconds and recv is still ready afterwards. The metric media_batch.latency_microseconds, how long a packet waits before flush, rose to hundreds of milliseconds against a baseline near 1 ms. The fix was a 9 ms send budget: if 9 ms passed since the last flush, recv is disabled for that poll so the flush runs. It shipped in early March 2026, and p99 latency dropped at once.
- Softirq noisy neighbour. Spikes remained at peak. Cloudflare's VMs exposed a single virtio-net queue, so all receive softirq work (the kernel's deferred packet processing) for the VM ran on one vCPU. When a worker thread was scheduled on that vCPU, softirq processing preempted it in bursts. Flame graphs showed net_rx_action and local_bh_enable frames lining up with the spikes. Discord used taskset in the container entrypoint to pin workers away from the vCPU handling the receive IRQ, and Receive Packet Steering to spread softirq work across other cores. The next peak showed no spikes, and European traffic moved back. Cloudflare was migrating to a hypervisor with multi-queue virtio-net, which would let Discord drop the affinity workaround.
Results. Against the previous vendor, packet loss fell 20 to 60% across several regions in Europe and Latin America, and in Santiago the expand ratio (how often the receiver stretches audio frames to hide gaps) fell 40%. Reykjavik and Auckland, the regions that motivated the move, were still ahead, along with the call-placement work Iceland had shown was needed. The rollout rule going forward: slow ramps with metrics in the loop, peering analysis first, and joint debugging when something is surprising.
Overlooked constraints.
- The closest server is not the best host for a group. With a single-host call, placement must minimize the worst or the total participant latency, not the creator's.
- The internet between ISP and edge is part of your system. Capacity in the PoP means nothing if the transit link into it is full at peak.
- Real-time media exposes scheduling details HTTP hides. Shared NIC queues, single-queue virtio, softirq placement and dirty-page flushes are invisible to a web app that tolerates 50 ms jitter, and fatal to a voice call that does not.
What Discord sacrificed. Control and speed. Discord gave up stable, self-chosen hosts for a scheduler that can reclaim machines, so it had to build discovery, recreate-based deploys and delayed exits. The rollout slowed from "large regions in months, done by year-end" to region by region with peering checks. Per-host density dropped for weeks during debugging. And some fixes depended on another company's kernel and hypervisor teams.
Deep Dive: placement math, the starvation budget, and the TTLShow
Where to host a mixed call (handbook's illustration). One user in Reykjavik and three in Frankfurt. Suppose one-way latency is 2 ms from each user to their local PoP and 25 ms between Reykjavik and Frankfurt. Media goes speaker → host → listener.
- Host in Reykjavik: a Frankfurt-to-Frankfurt path costs 25 + 25 = 50 ms plus access, about 54 ms, and three of the four users pay it for every conversation among themselves.
- Host in Frankfurt: Frankfurt-to-Frankfurt is about 4 ms, and only paths that involve the Icelander cost about 29 ms. Averaged over the 12 speaker-listener pairs, Frankfurt hosting gives about (6 × 4 + 6 × 29) ÷ 12 ≈ 16.5 ms, while Reykjavik hosting gives about (6 × 54 + 6 × 29) ÷ 12 ≈ 41.5 ms. A simple rule, "host where the median participant is" or "minimize the sum of pair latencies", picks Frankfurt. That is the placement logic Iceland made the case for.
Why 128 polls is not a time budget. If recv with a ready buffer takes about 1 µs per poll, 128 polls are 128 µs. After yielding, the runtime polls again, and recv is still ready. A count budget limits how long one task runs before it yields, but in a single-task select! loop there is nothing else to yield to, so starvation continues. A time-based budget, such as "flush at least every 9 ms", bounds the worst-case send delay directly. At 50 packets per second per stream, 9 ms is less than half a 20 ms packet interval, so a forced flush adds at most about one packet of delay.
Why NIC queue sharing loses packets. A send buffer of B bytes drains at the NIC rate R. If four workers send bursts that together exceed B before the queue drains, the kernel drops the excess. Halving the workers halves the arrival rate into the shared queue, which matches what Discord saw: loss returned to normal at two workers.
Choosing a 10-minute TTL. A heartbeat every T seconds with TTL L means a dead host can stay listed for up to L. Calls placed on it in that window fail and reconnect, so L trades stale entries against write load. With 25,000 hosts re-registering every 60 seconds, that is about 417 writes per second, trivial for Valkey. Clients also detect dead hosts directly through their own pings, so a long TTL costs a reconnect, not an outage.
Lesson 16: DAVE, end-to-end encryption for every call#
Assumptions. Lesson 14's SFU sees every packet, and transport encryption protects media only between the client and Discord's server. Anyone with access to the server could, in principle, read the media. In August 2023 Discord said it was experimenting with end-to-end encryption (E2EE) for voice and video. In September 2024 it launched the DAVE protocol for desktop and mobile, for a platform of about 200 million monthly users. During 2025 it extended DAVE to browsers, game consoles, bots and apps, and its Social SDK. In early March 2026 the migration finished: every voice and video call in DMs, group DMs, voice channels and Go Live streams is end-to-end encrypted by default, except Stage channels. Text messages are not end-to-end encrypted, and Discord said it had no plan to change that, because many text features assume the server can read messages.
The five goals behind the design were:
- Truly private. Only participants can decrypt media. Keys differ per call and change whenever someone joins or leaves, so a newcomer cannot decrypt earlier media and a leaver cannot decrypt later media.
- Open and auditable. The protocol whitepaper and the client library libdave are public, and Trail of Bits reviewed both the design and the implementation. Discord's bug bounty covers DAVE.
- Every platform. Browsers are the hardest, because Discord can only use the WebRTC APIs a browser exposes.
- Invisible to users. No key management, no "primary device", and no audible glitch when the protocol changes under a live call.
- Scales to any call size, fast. No forced downgrade for big calls, and an initial time-to-media of a few hundred milliseconds for a reasonably sized call.
The four parts.
-
WebRTC encoded transforms. WebRTC's encoded transform API lets an app insert a function after the encoder on the sender and before the decoder on the receiver. DAVE encrypts each encoded frame there with a per-sender symmetric key that all participants know and Discord does not. There is a catch: after the transform, WebRTC's codec-specific packetizer splits the frame into RTP packets, and it must still be able to read parts of the frame. So the sender's transform is codec-aware. It leaves codec metadata ranges in the clear and checks that the ciphertext does not contain byte sequences that the codec reserves, such as start codes that would confuse the depacketizer. Discord expected WebRTC's API to evolve so this work could be simplified later.
-
Key exchange with MLS. Messaging Layer Security (MLS, standardized as RFC 9420 in 2023) is a protocol for a group to agree on shared secrets that change as members come and go. Each client is a member of an MLS group and derives a per-sender media key from it. Discord's existing voice gateway also acts as the MLS delivery service (it routes MLS messages between members) and the external sender (it proposes adding and removing members). A join or leave moves the group to a new epoch, and all per-sender keys change. Discord chose MLS over pairwise schemes because a group approach scales better. The client-to-SFU transport encryption stays in place, so the SFU still forwards only traffic from authenticated participants, while the media inside each packet is unreadable to it.
-
Identity keys and verification. Each device creates an ECDSA P-256 identity key pair, chosen for WebCrypto compatibility and for a future move to non-extractable keys held in a TPM. Public keys are shared before joining the MLS group; private keys never sync between a user's devices. Members of an epoch can compare an exported value called the epoch authenticator, shown as the Voice Privacy Code (and a Stream Privacy Code for Go Live). Matching codes mean everyone has the same group state and nobody is impersonated. Each pair of users can also compare a pairwise Verification Code. By default identity keys are ephemeral, new for every call, so codes change across calls. Users can opt in to a persistent per-device key, which lets others keep a verification across calls but reveals that the same device is used again. Discord made persistence opt-in to keep the default private.
-
Protocol versions and transitions. During rollout, a call could use E2EE only if every member supported it. One older client forced the call back to transport-only encryption, and the call upgraded again when that client left. The voice gateway coordinates every transition: it announces a change, members prepare the new MLS group or version and report ready, and the gateway tells everyone to switch once all are ready. For a short, bounded window, receivers accept media under either the old or new context, so nobody hears a gap.
Reaching 100%. The hardest part of the second phase was platform diversity: one call can mix a laptop, a phone, a PlayStation, an Xbox and a web browser. On the web, the team found a Firefox bug that broke DAVE in real calls. Rather than work around it or drop Firefox, they worked with Mozilla on the Firefox code base and helped get a fix merged. To finish, Discord required every client to support DAVE before joining a call, and then began removing the unencrypted fallback code, so a downgrade will no longer be possible. Call quality stayed at the previous level. Stage channels are excluded because they are broadcast spaces for large audiences rather than personal conversations.
Overlooked constraints.
- The slowest client sets the security of the whole call. Mixed-version calls must fall back, so the rollout is not finished until the last old client is forced to upgrade, and the fallback path is itself attack surface until it is deleted.
- Encrypting inside a media pipeline is codec work. The packetizer must still parse frames, so a generic "encrypt the bytes" step would break video. Each codec needs its own rules about what stays in the clear.
- Rekeying is on the critical path. Every join and leave triggers an epoch change. In a busy voice channel with people coming and going, rekey speed matters as much as encryption speed.
What Discord sacrificed. Server-side visibility of call media: features that would need the server to hear or see the call cannot be built on the SFU. Simplicity: every client on every platform carries MLS, codec-aware transforms and transition logic. Some metadata is still visible, because the SFU sees who sends packets, when and how many, and the transport layer still authenticates participants. Stage channels and text were left out, a deliberate scoping choice.
Deep Dive: why group key exchange beats pairwise keys, and what an epoch change costsShow
Pairwise versus group (handbook's illustration). With pairwise keys, each sender must encrypt or wrap its key separately for each of the other n − 1 members, and a full mesh holds n × (n − 1) ÷ 2 pairwise secrets. At n = 100 that is 4,950 secrets and 99 key deliveries per sender on every change. MLS arranges members as leaves of a binary tree (the TreeKEM idea in RFC 9420). A member who updates its key sends new secrets along its path to the root, which takes about log₂ n encryptions, so roughly 7 for 100 members and 10 for 1,000. Adds and removes are similar in the common case, though removals can leave "blank" nodes that make later operations costlier until the tree is refreshed.
Forward secrecy and post-compromise security. Because each epoch derives new secrets and old ones are deleted, a key stolen today cannot decrypt last week's epoch (forward secrecy). Because the next update replaces the stolen key, an attacker who once stole a device key loses access after the next epoch (post-compromise security). Discord's "newcomer cannot read past media, leaver cannot read future media" goal is these properties applied to joins and leaves.
Time-to-media budget. Suppose the gateway round trip is 60 ms and an MLS commit plus processing takes 20 ms per client (handbook's illustration). A join needs: the proposal (one way, 30 ms), the commit from an existing member (60 ms round trip through the gateway), the welcome to the newcomer (30 ms), a ready round (60 ms) and an execute message (30 ms), about 210 ms plus processing, around 250 ms. That is in line with the "few hundred milliseconds" target. The overlap window, when both old and new keys are accepted, hides this from listeners already in the call.
Per-frame cost. At 50 Opus frames per second and a symmetric AEAD cipher running at several GB per second on a modern CPU, encrypting a 100-byte frame takes well under a microsecond, and an authentication tag adds a handful of bytes per frame. On a 1080p video stream at 30 frames per second and 4 Mbps, that is about 17 KB per frame, still microseconds. The expensive part of E2EE is coordination, not ciphering.
Verification code math. If the displayed code carries about 30 decimal digits of the epoch authenticator (handbook's illustration), an attacker trying to make two groups show the same code by chance faces odds near 1 in 10^30. That is why comparing a short code out of band proves the groups match.
Family 5: Media and machine learning
Chat apps are also image apps and, increasingly, ML apps. These two lessons show the same instinct from different decades: find where the CPU or GPU time really goes, then build only the thin layer that fixes it.
Lesson 17: Resizing 150 million images a day with Go and C#
Assumptions. Discord saw over a hundred million images a day. Two rules shaped the service:
- Never let clients fetch third-party images directly. If a message embeds a link to an image on someone's server, a client that loads it directly reveals its IP address to that server. Discord must fetch on the user's behalf.
- Never send full-size images when a thumbnail will do. Large images waste bandwidth, especially on mobile.
So Discord needs a proxy that fetches remote images, resizes them, and serves the result.
Image Proxy, the first version. A Python service fetched a URL, resized the image with pillow-simd (a fork of the Pillow library using x86 SSE vector instructions), and returned it. In front of it sat a cache: HAProxy routed each request by a hash of the URL to an Nginx caching tier, so the same image always hit the same cache node, and Nginx did request coalescing, collapsing simultaneous misses for the same URL into one resize. This scaled into millions of users. Its weak point was uneven work distribution: some requests took several seconds, and throughput suffered.
Media Proxy, the rewrite. Discord was trying more Go and chose this simple, easy-to-compare service for a rewrite, adding a new feature: extracting the first frame of MP4 and WebM videos. Benchmarks were discouraging. Go was faster than Python at HTTP, but no Go resizing package consistently beat pillow-simd, and resizing was most of the work. So Discord built Lilliput, its own Go library, a Cgo wrapper (Go's bridge to C code) around OpenCV:
- Mature C libraries handle codecs: libjpeg-turbo for JPEG and libpng for PNG, with OpenCV's vectorized resize.
- It was written to create almost no Go garbage, so the garbage collector stays idle.
- Discord forked OpenCV slightly so it could read image headers before decompressing, and reject images that are too large before spending memory on them. This blocks "decompression bombs", small files that expand to gigabytes of pixels.
- fasthttp handles the HTTP client and server.
Lilliput matched or beat pillow-simd on the cases Discord cared about.
Three bugs before launch.
- A 16-byte leak per request. Media Proxy keeps large static pixel buffers, two per CPU, so a 32-core host starts at several GB. A tiny leak took hours to exhaust memory, so it was hard to tell a leak from normal high usage. Xcode's Instruments Leaks tool showed the size and rough location, and review found it.
- Half-glitched images. Sometimes half an image looked right and half was garbage. Discord built a high-throughput simulator that acted as both client and image host and added random delays to its responses. That reproduced the bug reliably: a race on the output buffer, where a second JPEG was written into the buffer before the first had finished sending. The glitched images were two JPEGs on top of each other.
- Crashes from fuzzing. Running AFL (American Fuzzy Lop, a coverage-guided fuzzer) against Lilliput found several crashes from uninitialized variables. A service that decodes arbitrary internet files must survive any input.
Results. Media Proxy needed 60% fewer instances for the same requests, with much tighter latency. Over 90% of CPU went to decompress, resize and compress, inside already-optimized libraries, so there was little left to gain. It created almost no garbage. Median resize time was 25 ms and median total response 85 ms, for more than 150 million images a day, on an autoscaled Google Compute Engine group of n1-standard-16 machines peaking at 12 instances on a typical day. Lilliput was released under the MIT license.
GIFs and video. OpenCV does not handle animated GIFs, so Lilliput gained a giflib wrapper. A GIF frame uses a palette of up to 256 colours, but resizing works in RGB. Rather than computing new palettes, Lilliput keeps each frame's palette and maps resized RGB pixels back through a lookup table keyed on truncated RGB bits. It preserves colours and runs fast, but it can only produce a GIF from a GIF. Discord also patched giflib to decode one frame at a time, so it can decode, resize and encode each frame before the next, keeping memory predictable at the cost of carrying some GIF state across frames. This fixed glitches and transparency errors in animated Nitro avatars that the old proxy produced. A libavcodec wrapper extracts the first frame of MP4 and WebM files, giving video previews and unblocking the in-client video player.
Overlooked constraints.
- The language is rarely the bottleneck for compute-heavy services. The win came from the C libraries and from avoiding garbage, not from Go itself. Go only had to stay out of the way.
- Input from the internet is hostile. Header checks, fuzzing and memory limits are core design, not polish.
- Static buffers hide leaks. When a service starts at several GB on purpose, slow growth is hard to see. Leak detection needs a tool, not a dashboard.
What Discord sacrificed. Memory safety at the boundary: Cgo brings C's bugs, such as the leak and the uninitialized variables, into a Go service. It also took on maintenance of an OpenCV fork and a patched giflib, plus a GIF path that can only output GIFs.
Deep Dive: sizing the media proxy and the value of URL-hash routingShow
Throughput per machine (handbook's illustration). 150 million images a day is about 1,740 per second on average. With a 3 times peak factor, about 5,200 per second. At a median of 25 ms of CPU per resize, one core does about 40 resizes per second. Twelve 16-vCPU machines give 192 vCPUs, roughly 96 physical cores, about 3,840 to 7,700 resizes per second depending on how hyperthreads count. That fits only because the cache in front absorbs repeats: if most requests are cache hits, the proxy sees just the misses.
Why hash routing matters. With N cache nodes and random routing, a popular image would be cached on every node, and the first request on each node would miss: N resizes for one image. With routing by URL hash, the image lives on one node and causes one resize. Cache memory also holds N times more distinct images. Coalescing then handles the burst: if 500 clients ask for a new meme in the same 100 ms, the node sends one request to Media Proxy and holds the other 499. The cost is hot keys: one viral image always lands on one node, which must serve it from memory. Plain modulo hashing also reshuffles most keys when a node is added; consistent hashing avoids that.
Why 60% fewer instances. If the Python service spent part of its time in the interpreter, HTTP handling and garbage collection, and the Go service spends over 90% inside the codecs, the useful fraction of each core went up. Going from about 36% to over 90% useful work gives 2.5 times more throughput per core, which is 60% fewer machines for the same load.
Decompression bomb. A 10,000 × 10,000 pixel image is 100 megapixels, 400 MB as RGBA, yet can compress to a few hundred KB. Reading the header first lets the proxy refuse it before allocating anything.
Lesson 18: From single node to multi-GPU clusters with Ray#
Assumptions. Discord's ML grew from simple classifiers to models serving hundreds of millions of users. Training began needing several GPUs, datasets outgrew single machines, and compute demand outpaced the infrastructure. The team's assumption was that access to distributed compute is necessary but not sufficient: unless it is easy, ML engineers will not use it well.
Where they started. Ray is an open-source framework for distributed Python: it schedules tasks and actors across a cluster and has libraries for training, tuning and batch inference. Early adopters at Discord ran Ray clusters by hand from the open-source docs. That unblocked them, but cluster configs were not standardized, resource requests were inconsistent, and there was no scheduling or monitoring. Every team solved the same problems separately. Discord decided to build a Ray platform.
Step 1: one CLI command. Instead of dozens of YAML templates, one for each GPU shape, a single parameterized template generates the full cluster spec at runtime. Engineers ask for a GPU type, worker count and memory. The CLI fills in the Kubernetes configuration and security settings and manages the cluster from creation to deletion. Configs became consistent and requests matched real hardware.
Step 2: orchestration. Scheduled retraining runs on Dagster + KubeRay + Ray:
- Dagster (a data-pipeline orchestrator) defines workflows, configs and dependencies. Engineers launch jobs on a schedule or through the Launchpad UI with structured, schema-validated configs such as model name, dataset window or GPU pool, so jobs do not fail on missing parameters.
- KubeRay (the Kubernetes operator for Ray) creates Ray clusters on demand with the right service account and GPU node pool, using the same logic as the CLI.
- Ray runs the training, evaluation or batch inference.
The flow is: launch in Dagster, Dagster submits a job spec to the Ray job operator, KubeRay creates the cluster in the right namespace and node pool, Ray spreads the work over GPUs, and logs and metrics flow back to Dagster. The gains are predictable runs from versioned configs, reproducibility because resources are tied to pipeline definitions, and visibility without SSH into pods. The ad relevance model, one of the most GPU-heavy, retrains daily with no hand-tuning.
Step 3: observability. X-Ray is a web UI listing active clusters, owners, machine types and status, with links to dashboards and interactive notebooks.
The proof: Ads Ranking. This model chooses which Quest (a sponsored in-app campaign) a user is most likely to want. Before Ray, the team was limited to XGBoost (gradient-boosted trees), with no sharding, no multi-GPU training and no way to retrain at the needed cadence. With Ray it moved to sharded neural networks on multi-GPU clusters. Players joining Quests doubled, and coverage grew from about 40% to nearly 100% of ad traffic. Discord describes this as a +200% improvement in business metrics, and the model retrains daily. One engineer built a full testing framework in a day from the open-source Ray and Dagster docs, with no help. Teams in Ads, Safety, Shop and others now use the platform.
Overlooked constraints.
- GPU node pools are scarce and expensive. A platform must tie each cluster to an owner and tear it down when done, or idle GPUs eat the budget.
- Config errors are the most common failure. Schema validation at launch catches them before a cluster starts, which saves the minutes it takes to provision GPU nodes.
- Ad-hoc success does not scale. Each team's hand-run cluster worked for that team but multiplied support load.
What Discord sacrificed. Flexibility for consistency: engineers get a set of supported shapes and paths rather than any Ray config they like. The platform team owns a CLI, templates, Dagster integration and X-Ray, and must keep up with Ray and KubeRay releases.
Deep Dive: when to shard a model, and what a daily retrain costsShow
Why one GPU stops being enough (handbook's illustration). Recommendation models often hold huge embedding tables, one vector per user or item. With 200 million users and 128-dimension float32 embeddings, the user table alone is 200 million × 128 × 4 bytes ≈ 102 GB. Optimizers such as Adam keep two more values per parameter, tripling that to about 300 GB. A single 80 GB GPU cannot hold it, so the table must be sharded across GPUs (model parallelism), while the dense layers are copied to each GPU and trained on different data (data parallelism).
Data parallel scaling. If one GPU processes a day of training data in 16 hours, 8 GPUs ideally take 2 hours. In practice, gradient synchronization adds overhead. With 85% scaling efficiency, it takes about 2.35 hours, which makes a daily retrain practical where a 16-hour job would leave no time for evaluation and retries.
Cost of a daily retrain. 8 GPUs × 2.35 hours ≈ 19 GPU-hours a day. At a cloud price on the order of a few dollars per GPU-hour (handbook's illustration), that is tens of dollars a day, small next to a doubling of Quest participation. The real cost is engineering time, which is exactly what the CLI, Dagster configs and X-Ray reduce.
Why trees hit a ceiling. XGBoost works well on dense tabular features, but it cannot learn embeddings for millions of sparse IDs. Hashing IDs into features loses information. Neural models with embeddings let the model learn similarity between users and Quests it never saw paired, which plausibly explains the jump in coverage from 40% to nearly all traffic.
Family 6: Engineering productivity
The last family is about seeing and steering the system: tracing a message through millions of processes, knowing which endpoint costs what, keeping the client fast as features pile up, and giving engineers environments that start in minutes.
Lesson 19: Tracing Elixir systems without melting everything#
Assumptions. Each guild runs as its own Elixir process and fans every action out to session processes. When a guild cannot keep up, it feels laggy or goes offline, and on-call engineers need to know why and how users were affected. Their existing tools each fell short:
- Metrics show how often each action type runs and how long it takes. They point to bursts, but like a car's temperature gauge they do not show what the user experienced.
- "Guild timings", a custom tool, records how much of each minute a guild spends on each action type into an in-memory store. It is detailed but so voluminous that data is rotated quickly for all but the largest guilds, and it stops at the guild, missing downstream effects.
Distributed tracing fills the gap. A span is a timed region of code; spans nest into a tree called a trace. The context is the current trace and span, kept in per-process state, and passing it with each call lets other services attach their spans to the same trace. In Discord's example, the Python API's dispatch span took 1.69 ms, then the guilds service spent 357 µs fanning the message out to sessions, and each session recorded its own forwarding span. The trace also showed that the guild broadcast runs asynchronously from the API call. Traces often reveal surprises like work that was meant to be parallel running in series.
The Elixir problem. HTTP and gRPC carry context in headers, and the API already sent it to the guilds service in gRPC headers. Elixir processes, though, send each other raw messages with no metadata layer. The team needed a way to attach context that was:
- ergonomic, so developers never pack or unpack it by hand,
- usable for both plain messages and GenServer calls and casts (GenServer is Elixir's standard server-process abstraction; call is request-response, cast is fire-and-forget),
- rolled out with no downtime, with a runtime switch, because nodes are deployed gradually and old and new code must talk to each other.
Transport and the Envelope. Discord built a small library, Transport, using the OpenTelemetry Erlang/Elixir library. Its core is the Envelope, a struct holding the original message plus a trace_carrier field containing the serialized context. wrap_message builds an Envelope from the current context. handle_message accepts any message: if it is an Envelope, it extracts the context, runs the handler and detaches the context; if it is a plain message, it wraps it in an empty Envelope first. Drop-in call and cast functions wrap before sending. Services that already had their own send helper simply call wrap_message inside it. Because receivers accept both forms, each service could switch senders over by configuration, and mixed versions during a deploy worked. When an Envelope arrives from a different code version, the receiver rebuilds the struct with default values for any fields it does not know, so adding optional fields stays safe.
Sampling extreme fan-outs. Discord uses head sampling: the decision to trace is made when the root span starts, and every child inherits it through the context. That is fine for request-response services but explodes with fan-out: one sampled message in a guild with a million online users would create a million session spans. The first fix, a second flat random sample in the sessions service, was too aggressive for small fan-outs, which often had no session spans at all. So the guild added an optional approximate_num_recipients field to the Envelope, and each session looks up a keep-rate from it: 100% for one recipient, 10% for 100 recipients, down to 0.1% at 10,000 or more. Every fan-out then yields roughly the same small number of session spans, enough to show how it performed.
Three overhead fixes. Tracing cannot measure its own cost, so the team used other tools.
- Do not send unsampled context. After tracing reached the guilds service, some guilds with millions of members fell behind. Stack traces captured about every 100 ms showed much of the time going to unpacking trace context. With a sample rate under 1%, over 99% of unpacks only said "not sampled". Discord stopped sending context unless the trace was sampled. This slightly changes head sampling: a process that receives no context cannot tell it is inside an unsampled trace and may start its own root, producing partial traces. Discord accepted that, since full end-to-end traces can still be found by querying for spans from all services.
- No new root spans after fan-out. Instrumenting session fan-out raised sessions-service CPU by 10 percentage points, because with so many sessions, many independently chose to start new sampled traces. Forbidding sessions from starting root spans for post-fan-out messages, while still letting them continue existing traces, brought average CPU back from 55% to 45%.
- Check the sampled bit before parsing. Reading context from gRPC headers immediately doubled CPU. An engineer who had spent Hack Week on OpenTelemetry's in-progress Erlang/Elixir profiler found that 75% of gRPC handling time went to unpacking context (14.9 of 18.9 traced seconds in the presence service). The W3C trace-context header ends with a flags byte whose lowest bit means "sampled". Reading just that byte and skipping the full parse when it is zero returned CPU to normal.
// Sketch of the two cheap sampling checks (original illustration, not Discord's code).
// traceparent looks like "00-<32 hex trace id>-<16 hex span id>-01"
function isSampled(traceparent: string): boolean {
const flags = parseInt(traceparent.slice(-2), 16); // last byte only
return (flags & 1) === 1; // lowest bit = sampled
}
// Keep-rate for a session span, by approximate fan-out size.
function sessionKeepRate(recipients: number): number {
if (recipients <= 1) return 1.0;
if (recipients >= 10000) return 0.001;
return Math.min(1, 10 / recipients); // 100 recipients gives 0.1
}
function onFanoutMessage(env: { carrier?: string; recipients: number }) {
if (!env.carrier || !isSampled(env.carrier)) return untraced(); // skip parse
if (Math.random() >= sessionKeepRate(env.recipients)) return untraced();
return continueTrace(env.carrier); // never start a new root span here
}The payoff. In a later incident where a guild fell behind, traces showed members' sessions took almost sixteen minutes to connect to the degraded guild. Most guilds reported connect spans within a few milliseconds; the bad one showed none for sixteen minutes. Users saw that guild as offline and could not even open it. Metrics alone could not have measured that user impact.
Overlooked constraints.
- Observability has a cost proportional to fan-out. A tracing design that is cheap per request can be ruinous per delivery.
- The unsampled path dominates. At 1% sampling, the 99% path must be nearly free. Optimizing span capture matters less than skipping work when nothing is captured.
- Message formats change during deploys. Any new metadata wrapper must accept old and new formats at once.
What Discord sacrificed. Strict head-sampling semantics: some traces are now partial, because downstream services can start roots of their own. Detail in big fan-outs, where 0.1% of sessions represent the rest. And a custom library, Transport, that every service must adopt.
Deep Dive: span budgets for fan-out samplingShow
Without the second layer (handbook's illustration). Say 1,000 messages per second enter a large guild with 1 million online sessions, and 1% are head-sampled. Each sampled message makes 1 million session spans: 10 sampled messages × 1 million = 10 million spans per second from one guild. At 1 µs to create a span and about 500 bytes to export it, that is 10 core-seconds per second and 5 GB per second of telemetry.
With size-based keep rates. At 0.1% for 10,000 or more recipients, each sampled message keeps 1,000 session spans, so 10,000 spans per second, a 1,000 times cut. A 100-recipient message keeps about 10; a 1-recipient DM keeps 1. Spans per message stay in the range of 1 to 1,000 whatever the fan-out size. That is enough to estimate fan-out latency percentiles: with 1,000 samples, the p99 estimate rests on about 10 points, rough but useful, and smaller fan-outs can be pooled across many messages.
Why skipping unsampled parsing pays. If parsing a context string costs 5 µs and a guild handles 100,000 messages per second, parsing alone costs 0.5 core-seconds per second, half a core inside one single-threaded process. At 1% sampling, skipping the 99% unsampled cases cuts that to 5 ms per second. For a process whose whole job is to keep up, that half a core is the difference between keeping pace and falling behind.
Flag-byte sieve. Reading two hex characters and testing one bit is a few nanoseconds. If 75% of gRPC handling went to parsing, and 99% of requests are unsampled, the sieve removes about 74% of handler time, which roughly matches CPU halving back to normal after it had doubled.
Lesson 20: Cost attribution in Discord's API#
Assumptions. Discord's API is one Python code base with over 1,700 endpoints and about 700 background tasks, continuously deployed to several hundred Kubernetes deployments through phased rollouts. Each deployment runs the same code but serves a different slice of HTTP traffic or tasks. Latency, throughput and error metrics were good. What was missing was cost: how much does sending and reading messages cost to host, or starting a stream, or gifting Nitro, and did last week's change move a team's spend? (The post notes that its numbers and code are illustrative.) Constraints:
- The cloud bill stops at the deployment. Splitting deployments further just for cost tracking was not acceptable; there were already too many.
- One worker juggles many features at once. API workers use gevent green threads: a request waiting on a downstream call yields to another. So one process runs many features' code interleaved.
Features as code. Engineers defined feature groups that cluster endpoints and tasks. For example, the chat group contains features such as messaging (tier S), text-in-voice (tier B) and typing-indicator (tier E). Each feature has a name, an owning team, a tier for how critical it is (used to set and enforce SLOs), and a group. Definitions live in code and are generated into other languages for other services. Every route and task declaration gains a feature argument, and when a request starts, the API stores its feature and tier in a Python ContextVar (a per-task variable that follows green threads correctly).
Cost per deployment. A raw cloud bill line gives cost per SKU (VM, disk, network), per hour, per cluster. Turning on cost allocation in GKE, or split cost allocation in EKS, adds a deployment or pod tag to each line. Teams that own a whole service can stop at Kubernetes labels. Discord needed to split each deployment further.
Two wrong ways to split.
- Equal cost per request. Divide deployment cost by request count. But sending a message does more work than marking one unread, and the same endpoint varies with its input: an accidental @everyone in a 200,000-member server is far more work than a DM.
- Latency as a proxy. Most request time is spent waiting on downstream services, which uses no CPU. Worse, with green threads one CPU-bound request delays all others in the process, so slow-but-innocent requests would be charged for time another request spent running, like getting a speeding ticket while a friend was driving.
Profiling to the rescue. What matters is CPU time per feature. Discord already ran a sampling profiler in every API process. It uses ITIMER_VIRTUAL, a timer that counts only on-CPU time, so a SIGVTALRM signal fires about 10 times per second of CPU. The handler walks the current stack and records it in "folded" form (frames joined by semicolons, plus a count), and every 5 seconds the batch goes to Pyroscope, an open-source continuous-profiling database. The change was small: the signal handler also reads the current feature and endpoint from the ContextVars and labels the sample with them. Because the timer only fires while code is running, each sample lands on the request that was actually on the CPU, which solves the green-thread blame problem.
From profiles to dollars. Every hour a script queries Pyroscope grouped by feature and endpoint, sums samples, and computes each one's share of the deployment's CPU for that hour (for example, create_message 28.6% and load_messages 54.0% of one deployment's CPU in one hour, in the post's illustrative data). The rows go to the data warehouse and to Datadog. A new pipeline joins them with the per-deployment billing data, giving CPU and cost by feature group, feature or endpoint over time. Teams can see the cost of scaling an experimental endpoint to all users and decide when optimization is worth the time.
-- Hourly cost per feature: billing per deployment joined with CPU share per feature.
SELECT b.usage_hour,
b.k8s_deployment,
p.feature,
p.endpoint,
SUM(b.total_cost) * p.cpu_share AS attributed_cost
FROM billing_by_deployment AS b
JOIN cpu_share_by_feature AS p
ON p.deployment = b.k8s_deployment
AND p.hour = b.usage_hour
GROUP BY b.usage_hour, b.k8s_deployment, p.feature, p.endpoint, p.cpu_share;
-- cpu_share = samples for feature and endpoint / all samples in deployment that hourOverlooked constraints.
- CPU is not the whole bill. Memory, disk and network are charged too, and a memory-heavy feature with little CPU gets undercharged. CPU share is a strong proxy for compute-bound Python workers, not a universal rule.
- Shared code needs ownership metadata. Without a feature tag on every route and task, a monolith's cost cannot be split. The tags also feed SLO tiers, so one investment serves two purposes.
- Sampling needs volume. At 10 Hz, a rarely called endpoint collects few samples per hour, so its share is noisy. Hourly aggregation over hundreds of processes provides that volume.
What Discord sacrificed. Precision for zero deployment changes: costs are estimates built from statistical samples and a CPU proxy, not metered exactly. Profiling overhead is paid all the time in production. And idle or overhead time, such as interpreter startup or GC outside any request, must be either left unassigned or spread out by some rule.
Deep Dive: how accurate is 10 Hz sampling?Show
Samples per hour (handbook's illustration). A deployment of 200 pods, each with 4 busy Python worker processes, collects about 10 samples per CPU-second. If workers are 60% busy, each gives about 6 samples per wall-clock second, 21,600 per hour. Across 800 workers that is about 17 million samples per hour for the deployment.
Error for a small feature. Sampling is a binomial process. If a feature truly uses a share p of CPU and N samples are taken, the standard error of the estimated share is √(p(1 − p) ÷ N). For p = 0.1% and N = 17 million, that is about √(0.001 ÷ 17,000,000) ≈ 7.7 × 10⁻⁶, under 1% relative error. Even at a single pod, 21,600 samples give a relative error near 21% for a 0.1% feature, which is why aggregation across the deployment matters.
Turning share into dollars. If messages-production costs 9 VMs × 1.536 dollars ≈ 13.82 dollars in one hour (the post's illustrative billing line), and create_message used 28.6% of CPU, its share is about 3.95 dollars per hour, roughly 2,900 dollars per month for that one deployment. A team that sees that number can decide whether a week of optimization pays off.
Why green threads break latency-based blame. Two requests share a process. A spends 2 ms on CPU and 100 ms waiting on a database. B spends 50 ms on CPU in one go. If A's database reply arrives while B is running, A waits 50 ms more and its latency becomes 152 ms. By latency A looks three times as costly as B, yet by CPU it costs 25 times less. The CPU-time timer charges each sample to the request actually running, so A is charged 2 ms and B 50 ms.
Lesson 21: Keeping the client fast while adding features#
Assumptions. Many Discord users talk while playing a graphically heavy game, so the app competes with the game for CPU, memory and GPU. "Bloat", where each feature makes the app slower to load and heavier to run, hurts them directly. Video chat, screen sharing and the in-game overlay all had to arrive without that cost. The desktop app is a web app at heart (JavaScript, stylesheets, fonts), so the techniques are those of large web front ends.
The architecture: code splitting. Every piece of code must be downloaded or read from disk, parsed and kept in memory. Splitting code so that only what the current screen needs loads first makes start-up faster and memory smaller. The rest loads on demand. If chunks are small and well chosen, users rarely notice the loading.
- A small core. At start-up, the core JavaScript, fonts, images and stylesheets came to about 700 KB, about the size of a minimal search engine home page. Everything else loads later. New users following an invite link do not download the whole app.
- Route-level chunks. Each view is a route. Its components are wrapped in a function that runs when the user arrives, and webpack, the bundler, turns each route into its own chunk and handles most of the loading.
- Retry on failure. A chunk download can fail, leaving a missing component and an error. Discord wrote makeLazy, a loader that retries at growing intervals until the chunk arrives.
- Styles and animations too. Stylesheets for each route are split the same way, and even animations are lazy-loaded, so art and polish do not slow start-up.
- Only one language. Discord had 27 translations of about 30 KB each. Loading only the user's locale saves close to 1 MB; switching language briefly loads the new chunk. New languages cost nothing for everyone else.
// Original illustration of a lazy route loader with exponential backoff.
function makeLazyLoader<T>(load: () => Promise<T>, maxDelayMs = 30000) {
let cached: Promise<T> | null = null;
return function get(): Promise<T> {
if (cached) return cached;
const attempt = (delayMs: number): Promise<T> =>
load().catch(() =>
new Promise<T>((resolve) =>
setTimeout(() => resolve(attempt(Math.min(delayMs * 2, maxDelayMs))), delayMs)
)
);
cached = attempt(500);
return cached;
};
}
// Usage: each route's chunk is fetched only when the user opens that route.
const loadSettings = makeLazyLoader(() => import("./routes/settings"));Overlooked constraints.
- The first click on a new route pays the cost. Lazy loading moves latency from start-up to first use. Chunks must be small, and important routes can be prefetched when the app is idle.
- Chunk names change with every deploy. A long-running desktop client may ask for a chunk from an older build that the server no longer has. Keeping old chunks available, and retrying with backoff, protects users who keep the app open for days.
- Bundle budgets need enforcement. Without a size check in CI, the core bundle grows one import at a time.
What Discord sacrificed. Instant availability of every feature: some views show a short load on first open, and switching language takes a moment. The build becomes more complex, with chunk boundaries to plan and a custom loader to maintain.
Deep Dive: what 700 KB buys at start-upShow
Parse and compile cost (handbook's illustration). On a mid-range laptop, JavaScript parse and compile runs on the order of 1 MB per 100 to 200 ms, more on slower machines and while a game holds the CPU. Shipping a 5 MB bundle instead of 700 KB could add half a second to a second of start-up before any network cost, and keep several extra MB of code and its data structures in memory for the whole session.
Network cost for invites. On a 10 Mbps mobile link, 700 KB takes about 0.56 seconds. A 5 MB bundle takes 4 seconds. For a new user tapping an invite, that difference can decide whether they stay.
Locale savings. 26 unused locales × 30 KB = 780 KB, close to the "nearly 1 MB" in the post, and more than the whole core bundle. Without splitting, every new language would make the app slower for everyone.
Backoff schedule. Starting at 500 ms and doubling to a 30 second cap, retries happen at 0.5, 1, 2, 4, 8, 16 and then every 30 seconds. A brief network glitch recovers in about a second, while a long outage does not hammer the CDN with retries. If 1 million clients lose a chunk at once, jitter (a random part of each delay) should be added so retries do not arrive in lockstep.
Lesson 22: Moving engineering to cloud development environments#
Assumptions. Discord develops in a polyglot monorepo where Python, TypeScript, Rust, Elixir and C/C++ are the most active languages, and ships to Android, iOS, macOS, Windows and Linux. Engineering more than tripled in a few years and works mostly remotely, with offices in San Francisco and the Netherlands. The Internal Developer Experience team owns roughly the first third of the software lifecycle: IDEs, dev environments, build and test tools, CI and change management. This lesson covers how all backend and infrastructure development moved to Linux cloud development environments (CDEs) built on Coder.
The pain before. Most engineers used MacBooks.
- Package drift. Laptops were provisioned with Homebrew, and one brew upgrade could stop an engineer cold. Pinning every package and transitive dependency fixed that but made it hard to install anything else. System dependencies later moved to Nix, which gives reproducible packages, leaving Homebrew for personal tools.
- Service orchestration. Makefiles and procfiles were outgrown. Docker and docker-compose were tried, but Docker for Mac was slow and rebuilds added friction, so the team moved to a supervisor-based system with tools to define and run services.
- Two environments. Without containers, there were two non-reproducible setups, Mac and Ubuntu, and the tooling teams spent much time debugging one-off breakage. One Linux environment was the goal.
Why CDEs. VMs in the cloud are reproducible and configurable, can be rebuilt from an image, are more secure, come with cloud IAM, and can be managed with standard automation. The deciding requirement was a good editor loop, and VS Code's remote development extension was stable, while most Discord engineers already used VS Code. A fully immutable machine would be ideal but impractical, so /home is preserved across restarts for repos, dotfiles and personal tools, while the base template and image can be updated without a full rebuild.
Honest drawbacks. Nothing beats localhost. Working over SSH adds latency, and unstable networks caused lag and dropped connections. Sending large HTML and JavaScript bundles over the network slowed front-end save-and-rebuild loops, so many engineers kept front-end work local and backend work remote, which forces a "split-brain" repo or code syncing when a change touches both API and UI.
Coder V1 to V2. Discord started with Coder in late 2020, when Coder's product was Kubernetes-native, a good fit for a heavy Kubernetes user and cheaper than building its own. But running a whole dev machine inside a container was hard:
- Privileged containers were not allowed, so changing kernel parameters, which Scylla needs, required a privileged daemon on each node to tune the host.
- Layers of virtualization in a Sysbox environment were hard to debug, and there were noisy neighbours, lag spikes and high latency.
In 2023 Discord moved to Coder V2, which provisions VMs and rebuilt its networking on Tailscale and WireGuard (a modern, fast VPN protocol). Full access to the host simplified the setup, engineers reported that development felt faster and smoother, and tickets about latency and dropped connections stopped.
The migration plan.
- Solidify the default experience so it "just works": dev image, system dependencies, users, permissions, preinstalled software, plus automation for fast feedback loops.
- Broaden adoption: interviews, dogfooding, small tests, representative feedback, then open beta. Champions from many departments tested varied daily workflows. The team benchmarked build tools, load-tested the network and checked common loops.
- Hard cutoff: docs, training, support channels, and backend development on MacBooks deprecated.
The goal was an experience good enough that people moved voluntarily, with nudges when a laptop broke. Apple's M1 forced the timeline: new laptops were ARM-only, parts of the backend stack failed even under Rosetta emulation, so step 3 was brought forward.
Lessons the team named. Developers care about responsiveness above all: if they can type faster than the screen updates, the flow breaks. Onboarding for people less comfortable with a terminal needed docs, videos and good default dotfiles, and this "last mile" still felt short. The biggest regret was not building network diagnosis tooling before the cutover. Coder's early "satellite" feature put clusters in several regions, but some remote engineers still suffered, and the tools to diagnose their networks came only afterwards. Communication and documentation for a change that rewrites everyone's workflow can hardly be overdone. Despite two migrations (Mac to V1 to V2), the team said it would make the investment again, and starting before the pandemic was lucky timing.
Overlooked constraints.
- The developer's network is now part of the dev loop. Every keystroke round trip crosses the internet, so regional placement and diagnosis tools must exist before the cutover.
- Hardware shifts can force the schedule. M1 turned a voluntary migration into a deadline.
- Containers are not machines. Workloads that need kernel tuning, like ScyllaDB, push dev environments toward VMs.
What Discord sacrificed. Localhost speed and offline work. Front-end engineers kept a split workflow. Discord pays cloud costs for every engineer's VM, and it did the migration twice.
Deep Dive: the latency budget of remote developmentShow
Keystroke echo (handbook's illustration). People notice delays in typing above roughly 50 to 100 ms. A VS Code remote session edits files locally in the editor, so keystrokes echo instantly, but terminal input, language server results and file saves all cross the network. From San Francisco to a VM in a nearby region the round trip may be 10 to 20 ms, which is fine. From Europe to a US region it is 80 to 150 ms, enough to make a remote terminal feel sluggish. That is why regional clusters matter.
Rebuild loop. A backend change that triggers a 2 second incremental build on a 32-core VM might take 10 seconds on a laptop running a heavy stack, so remote can be faster overall. A front-end change that produces a 20 MB development bundle must travel to the browser. At 50 Mbps that adds 3.2 seconds per reload, which explains why front-end work stayed local.
Cost per engineer. A 16-vCPU, 64 GB VM at roughly 0.6 to 0.8 dollars per hour (handbook's illustration), running 10 hours a day, 21 days a month, costs about 130 to 170 dollars a month. If it saves even one hour of debugging a broken laptop environment per month for an engineer whose time costs well over 100 dollars an hour, it roughly pays for itself, before counting faster onboarding and fewer one-off support tickets.
Why WireGuard helped. WireGuard runs over UDP with small, fixed handshakes and roams cleanly when a laptop changes networks, whereas long-lived SSH over TCP stalls when packets are lost and must reconnect after a network change. On flaky home Wi-Fi, that difference shows up as fewer dropped sessions.
Family 7: Synthesis
Lesson 23: Recurring patterns across twenty-two posts#
Read side by side, the Discord posts repeat a small number of moves. Each one is a reusable design decision with a known cost.
| Pattern | Where it appears | What it buys | What it costs |
|---|---|---|---|
| Partition by the natural unit, then bound it | Lesson 1 buckets, Lesson 7 cells, Lesson 13 relays | Even writes, bounded partitions, failure isolation | Queries that span units become multi-step |
| One owner process or instance per hot entity | Lesson 2 data services, Lesson 8 guild processes, Lesson 14 one SFU per call | A single place where duplicate work can meet | That owner becomes the ceiling; placement matters |
| Merge duplicate work before it reaches storage | Lesson 2 request coalescing, Lesson 17 Nginx coalescing | Hot-partition reads collapse to one | Only overlapping requests merge; no help for repeats later |
| Rewrite the hot path in a language without GC pauses | Lessons 2, 9, 10, 15 Rust; Lesson 17 C via Cgo | Predictable tail latency | Two languages to staff, FFI bugs |
| Do less work, not faster work | Lesson 11 passive sessions, Lesson 13 passive users, Lesson 19 skip unsampled parsing | Large step changes in capacity | Behaviour differences between active and passive users |
| Treat the lowest layer as part of your system | Lesson 5 super-disks, Lesson 15 NIC queues and softirq | Problems solved where they really live | Deep expertise or a partner's kernel team |
| Migrate with double writes, comparison and rollback | Lessons 3, 7, 15 Valkey, 22 | Zero-downtime cutovers | Weeks of running two systems |
| Push non-urgent work to a buffered pipeline | Lesson 6 lazy indexing, Lesson 12 GenStage | Bursts absorbed without dropping work | Delay, and a queue to monitor |
| Instrument by business unit, not by machine | Lesson 19 traces through guilds, Lesson 20 cost per feature | Answers in product terms | Metadata on every route, message and task |
| Build platforms only after several teams need them | Lesson 4 control plane, Lesson 18 Ray platform, Lesson 22 CDEs | Consistency and less support load | A platform team to fund |
The deeper theme: the unit of fan-out. Discord's product puts large numbers of people into one shared space, a channel, a guild or a call. Almost every scaling problem in these posts comes from one popular unit concentrating load on one partition, one process or one server: hot Cassandra partitions, Midjourney's guild, a mixed-region call pinned to Reykjavik, a million session spans from one sampled message. The fixes all keep the unit's single ordering point, because chat needs order and calls need one host, and then remove as much work from that point as possible.
What the company sacrificed overall. Discord repeatedly chose a single owner per unit, which gives simple ordering and consistency, over multi-owner designs that would spread load but complicate ordering. The cost shows up as constant work to shrink per-event cost inside those owners. It also chose to own deep layers, from a custom media engine to a Rust SFU, Lilliput and Transport, which gives control at the price of long-term maintenance with a small team.
Deep Dive: the break-even point for coalescing, relays and rewritesShow
Coalescing break-even (handbook's illustration). Coalescing helps only when requests overlap in time. If a hot key gets λ requests per second and a database read takes t seconds, the expected number of requests arriving during one in-flight read is λ × t. At λ = 5,000 per second and t = 5 ms, about 25 requests share each read, a 25 times cut. At λ = 10 per second, only 0.05 overlap, and coalescing does almost nothing. That is why coalescing is precisely a hot-key tool.
Relays break-even. If the guild's cost per event is a + b × n, where a is fixed work and b is per-session work, moving the per-session part to k relays leaves the guild with a + c × k, where c is the cost of one send to a relay. Relays pay off once b × n is more than c × k. With b = 1 µs, n = 100,000 and c = 50 µs with k = 7 relays, that is 100 ms versus 0.35 ms, a clear win. With n = 1,000, it is 1 ms versus 0.35 ms, still a win but small, so small guilds do not need relays.
Rewrite break-even. A rewrite in a faster language pays if the saved hardware plus avoided incidents exceed engineering cost. Lesson 17's 60% fewer instances on a 12-machine fleet saves about 7 machines; at a few hundred dollars per machine per month that is a few thousand dollars per month, modest. The real gains in Lessons 2 and 10 were tail latency, where GC pauses hurt users, not average hardware cost. Rewrites justified by p99 are more convincing than those justified by averages.
Cross-cutting: hot keys, sorted search and live data, seen through Discord#
Three classic interview problems connect directly to Discord's posts.
1. Millions of concurrent reads for the same cached data. A hot key is a single key that receives a large share of all traffic, such as one celebrity's profile, one viral post or the latest messages in a huge channel. Caching alone does not solve it, because a cache cluster still stores each key on one node, and that node's network card and CPU set the limit. A single Redis node might serve on the order of 100,000 to a few hundred thousand simple reads per second, so a key read 2 million times per second needs more than one copy. The standard toolbox, in the order you would reach for it:
- Request coalescing at the layer in front of storage, so overlapping misses share one read. This is Discord's Lesson 2: routing by channel_id with consistent hashing puts all reads for a channel on one data-service instance, where they merge. It never serves stale data, but helps only requests that overlap in time.
- A small in-process cache in each application server for the very hottest keys, with a short TTL such as 1 to 5 seconds. Each of 500 servers then asks the cache once per TTL instead of on every request: 500 reads per second at most, regardless of user traffic. The cost is up to one TTL of staleness.
- Hot-key replication in the distributed cache. Store copies under suffixed keys such as post:123#1 to post:123#8 on different nodes and have readers pick a suffix at random. Read capacity grows with the number of copies; writes must update or invalidate every copy. Detect hot keys by sampling access counts, so only truly hot keys are copied.
- CDN and edge caching for content that is the same for everyone and can be a few seconds old: images (Lesson 17's Media Proxy output), public pages, static search results. Edge nodes absorb the burst before it reaches your data centre.
- Change the access pattern when none of that is enough. Discord's passive sessions (Lessons 11 and 13) are this move: most users never request the data until they look.
See Distributed caching, CDN and the Scaling reads pattern for the full treatment.
2. Search results sorted by recency or popularity. In a post-search design, a naive approach fetches every post ID matching a keyword, looks up each one's timestamp or like count, and sorts in memory. For a common word with tens of millions of matches, that means hundreds of MB of IDs, tens of millions of lookups and a huge sort per query. The better design keeps two indexes per keyword: one ordered by creation time, which can be an append-only list where queries read only the newest end, and one ordered by like count, such as a Redis sorted set where each post's score is its likes. New posts go into both for each keyword they contain. Queries then read only the top N entries. The costs are double index storage and write amplification on likes: each like must update the post's score under every keyword it contains, which is why like events are usually batched or handled in a two-stage design (a precise counter updated often, the search index updated in bulk less often). In a chat search such as Discord's (Lessons 6 and 7), recency ordering can come almost for free when message IDs are time-ordered Snowflake IDs, since sorting by ID is sorting by time, and Discord's Redis sorted sets appear in the shard allocator of Lesson 6. The same "precompute the order you will query" rule applies. See Elasticsearch and Redis.
3. Showing live activity data during a run or ride. A fitness-tracking app must show route, distance and elapsed time while the user moves. The key insight is that the device already has the data. GPS points arrive on the phone every second or so; distance can be computed locally by summing distances between successive points (the haversine formula on latitude and longitude), and time comes from the local clock. Sending each point to a server and waiting for it to return the total would add round-trip latency and fail without signal. So the client computes and displays live stats itself, buffers points locally, and uploads them in batches or at the end of the activity, while the server stores the result and handles sharing. Discord applies the same principle in Lesson 21: keep work on the client when the client has what it needs, and send the network only what must be shared. It also mirrors Lesson 14's design, where clients start and restart every call, so the server never has to track client state it cannot see.
Deep Dive: sizing a hot key and a live trackerShow
Hot key capacity (handbook's illustration). An announcement in a 1 million member guild is opened by 30% of members within 10 seconds: 30,000 reads per second for one message. Without protection, all hit one database partition with 3 replicas, 10,000 reads per second per replica, enough to push p99 into hundreds of ms. With coalescing and a 5 ms read, about 150 requests share each query, so only about 200 database reads per second reach the partition, a 150 times cut. If those reads also pass through an in-process cache with a 2 second TTL on 200 API servers, the database sees at most 100 reads per second, and users see a message at most 2 seconds stale.
Hot-key replicas. Suppose a key gets 2 million reads per second and one cache node handles 200,000 per second at a safe load. You need at least 10 copies; with headroom, 16. Each write now updates 16 keys. If that key changes once per second, that is 16 writes per second, trivial against 2 million reads.
Live tracker bandwidth. A run of 1 hour with one GPS point per second is 3,600 points. At about 24 bytes per point (latitude, longitude, timestamp, altitude), that is about 86 KB. Uploading it in one batch at the end, or every 30 seconds in 720-byte chunks, is far cheaper than 3,600 round trips. For 10 million concurrent activities, per-second uploads would be 10 million requests per second; 30-second batches cut that to about 333,000 per second.
When to Use It#
Study the Discord posts when:
- You are designing chat, social or community products where many users share one space. Lessons 1 to 3, 8, 11 and 13 show how storage and fan-out work when one channel or guild can be enormous.
- You face hot partitions or hot keys. Lesson 2's routing plus coalescing is a precise, reusable answer that interviewers recognize.
- You run persistent connections at scale such as WebSockets. Lessons 8 to 13 cover process models, compression, passive sessions and burst handling.
- You build real-time voice or video. Lessons 14 to 16 cover SFUs, custom signaling, edge placement and end-to-end encryption for groups.
- You are thinking about a language rewrite for tail latency. Lessons 2, 9, 10 and 15 show when Rust paid off and what it exposed.
- You need cost or performance visibility in a large shared code base. Lessons 19 and 20 show tracing and cost attribution that work with fan-out and green threads.
When NOT to Use It#
- Do not copy the scale. Discord stores trillions of messages and serves millions of concurrent users. A community app with 50,000 users can store messages in PostgreSQL with an index on channel and message ID and serve them from one region.
- Do not copy the Elixir and Rust mix without the team. Discord's choices fit engineers who know the BEAM deeply. The patterns (one process per entity, relays, coalescing) can be built in Go, Java or Node.
- Do not use it for strong cross-entity consistency. Discord orders events within a channel or guild, not across them. Payments, ledgers and inventory need the patterns on the Stripe page and the distributed transactions page.
- Do not treat end-to-end encryption as free. Lesson 16 shows years of work across every platform. If your product needs server-side processing of content, E2EE removes it.
- Do not take posts as current state. Several systems changed after their posts, such as etcd replaced by Valkey for voice discovery in Lesson 15. Treat numbers as a point in time.
How to Implement It#
Apply the lessons in this order for a chat or community product.
- Partition messages by channel and time bucket (Lesson 1). Choose a bucket size that keeps a busy channel's partition under about 100 MB.
- Use time-ordered IDs such as Snowflake IDs so sorting by ID sorts by time, which makes pagination and search ordering cheap.
- Put a thin data service in front of the database (Lesson 2), route by channel with consistent hashing, and coalesce identical in-flight reads.
- Model each shared space as one owner process or actor (Lesson 8), and fan out through relays once spaces grow large (Lesson 13).
- Send active users full updates and everyone else summaries (Lessons 11 and 13). Compress the WebSocket stream with a streaming compressor such as zstd.
- Absorb bursts in a buffered pipeline with back-pressure (Lesson 12) for push notifications and indexing.
- Index search lazily and in bulk (Lessons 6 and 7), and isolate the largest tenants in their own indexes or cells.
- Trace by entity, sample by fan-out size (Lesson 19), and attribute cost by feature (Lesson 20) before costs surprise you.
- For voice, run an SFU with client-driven reconnect (Lesson 14), place calls near the median participant, and check network paths before moving regions (Lesson 15).
- Migrate with double writes, comparison and gradual ramps (Lessons 3 and 15), never in one step.
A routing and coalescing configuration in the style of Lesson 2:
data_service:
routing:
key: channel_id # all reads for a channel meet on one instance
strategy: consistent_hash
virtual_nodes: 256
coalescing:
enabled: true
key: [channel_id, query_shape, cursor]
max_waiters_per_key: 10000 # bound memory under extreme bursts
timeout_ms: 200 # waiters fail fast if the leader stalls
database:
consistency: LOCAL_QUORUM
timeout_ms: 100
hot_channel_guard:
detect_rps_above: 2000
action: in_process_cache
ttl_ms: 1000Technology choices.
| Need | Discord choice | Alternatives | When each fits |
|---|---|---|---|
| Message storage | Cassandra, then ScyllaDB | DynamoDB, Bigtable, PostgreSQL with partitioning | DynamoDB to avoid operations; PostgreSQL below billions of rows |
| Hot-path services | Rust | Go, C++, Java with low-pause GC such as ZGC | Rust or C++ for strict p99; Go when GC pauses are acceptable |
| Real-time fan-out | Elixir on the BEAM | Akka on the JVM, Go with goroutines, Orleans | BEAM for many isolated stateful processes; Orleans for .NET teams |
| Search | Elasticsearch on ECK | OpenSearch, Vespa, Typesense | OpenSearch for a managed AWS option; Vespa for ranking-heavy search |
| Service discovery | etcd, then Valkey with TTLs | Consul, ZooKeeper, Kubernetes endpoints | etcd or Consul for strong consistency; TTL store for huge, churny fleets |
| Voice and video | Custom C++ SFU, then Rust SFU | mediasoup, Janus, LiveKit, Jitsi | LiveKit or mediasoup unless you need custom protocols |
| Group E2EE | DAVE on MLS | Signal Sender Keys, other MLS libraries | MLS for large, changing groups |
| ML platform | Ray with KubeRay and Dagster | Kubeflow, SageMaker, Anyscale | Managed services for small teams |
| Profiling and cost | Pyroscope with labels | Grafana Pyroscope, Parca, Datadog profiler | Any continuous profiler that supports labels |
| Dev environments | Coder V2 VMs | GitHub Codespaces, Gitpod, Dev Containers | Codespaces for GitHub-centric teams; self-hosted for custom kernels |
Trade-offs#
| Choice Discord made | What it bought | What it cost |
|---|---|---|
| One owner per channel, guild or call | Simple ordering and consistency | Hot owners set the ceiling; constant work to shrink per-event cost |
| Eventual consistency in Cassandra and ScyllaDB | Cheap writes, multi-replica availability | Tombstones, read repair and rare anomalies |
| Coalescing instead of caching messages | Never serves stale messages | Helps only overlapping reads |
| Rust for hot paths | Predictable tail latency, no GC pauses | Two or three languages; FFI and NIF risks |
| Passive sessions | Large cuts in bandwidth and CPU | Delayed state for users not looking |
| Custom voice protocol and SFU | Fast joins, hidden IPs, server features | Owning a WebRTC fork forever |
| Moving voice to a 300-city edge | Lower latency in many regions | Less control over hosts, joint debugging with a partner |
| E2EE for all calls | Media unreadable by Discord | No server-side media features; complex clients on every platform |
| Head sampling with fan-out rates | Affordable tracing at huge fan-out | Partial traces and thin samples for big fan-outs |
| Cloud dev VMs | One reproducible Linux environment | Network-dependent dev loop, cloud cost per engineer |
Common Pitfalls#
- Unbounded partitions. Partitioning only by channel ID lets a busy channel grow forever. Always add a time bucket or another bound.
- Treating deletes as free. In LSM stores, deletes write tombstones that slow reads until compaction. Lesson 1's empty-channel scans came from this.
- Fixing hot partitions with a faster database only. A faster engine makes each read cheaper but does not stop thousands of readers arriving. Reduce the reads too.
- Fanning out to everyone equally. Sending full updates to users who are not looking wastes most of the bandwidth. Separate active from passive.
- Placing a shared session at the creator's nearest server. Group calls and rooms should be placed for all participants, not the first one.
- Moving traffic without checking the path. A PoP with spare capacity is useless if the ISP's transit link into it is full at peak.
- Tracing every fan-out branch. One sampled message to a million recipients can produce a million spans. Sample by fan-out size.
- Charging cost by request count or latency. Both misattribute cost, especially with green threads. Use CPU-time sampling.
Real-World Examples#
- Slack moved to sharded MySQL with Vitess and runs real-time messaging through its own gateway servers. It faces the same hot-channel problem in very large shared channels.
- WhatsApp famously ran on Erlang on the BEAM, the same runtime as Discord's Elixir gateway, with a very small engineering team.
- Apple Messages, Google Messages and WhatsApp use end-to-end encryption for chat; Google has adopted MLS for RCS group messaging, the same group key protocol as DAVE.
- Zoom, Google Meet and Microsoft Teams use SFU-style media servers for group calls, the architecture of Lesson 14.
- Netflix and Cloudflare appear in this handbook's other blog pages; Cloudflare is also the edge partner in Lesson 15. See Netflix engineering and Cloudflare engineering.
In the Interview#
Deep Dive: designing a small Discord-like community appShow
Requirements (handbook's illustration). 2 million registered users, 200,000 concurrent, 20,000 communities, the largest with 100,000 members and 10,000 online. 50 million messages a day, about 580 per second on average and 3,000 per second at peak. Messages average 200 bytes plus 300 bytes of metadata and indexes.
Storage. 50 million × 500 bytes = 25 GB per day, about 9 TB per year before replication, 27 TB with 3 replicas. That is beyond a comfortable single PostgreSQL server within a year or two, so plan a wide-column store such as ScyllaDB or DynamoDB, partitioned by channel and 10-day bucket. A typical channel's bucket stays well under 100 MB.
Fan-out. At 3,000 messages per second and an average of 50 online recipients per channel, that is 150,000 deliveries per second. The 10,000-online community at 20 messages per second alone is 200,000 deliveries per second. Using passive sessions where 90% of online members are not looking at that channel cuts it to about 20,000 full deliveries plus cheap unread markers.
Gateways. 200,000 WebSockets at about 50,000 per gateway node gives 4 nodes; run 8 for failover and deploys. At an average of 2 KB per second per connection after compression, that is 400 MB per second of egress, about 3.2 Gbps in total.
Hot reads. An announcement in the largest community is opened by 5,000 people in 10 seconds, 500 reads per second for one channel. Coalescing at a 5 ms read cuts this to about 200 reads per second at the partition, and a 1 second in-process cache cuts it to a few. No special database is needed.
Search. Index messages asynchronously through a queue in bulk batches. 50 million messages a day at about 1 KB indexed is 50 GB a day; split indexes by time and put the largest communities in their own indexes.
What to say about trade-offs. This design gives bounded partitions, cheap writes and fast recent reads, at the cost of eventual consistency between replicas, delayed search results by a few seconds, and a single owner per community that limits the largest community's message rate.
Key Takeaways#
- Partition by the product's natural unit and bound it. Channel plus time bucket kept Discord's message partitions manageable from billions to trillions.
- A faster database and fewer database reads solve different problems. ScyllaDB made reads cheaper; routing plus request coalescing made them fewer. Discord needed both.
- Change the shape of work before optimizing code. Passive sessions, relays and lazy indexing gave larger gains than rewrites, because fan-out cost grows with the square of a space's size.
- Rewrite hot paths for tail latency, not averages. Rust removed GC pauses in Read States, data services and the SFU, but brought FFI risks and a second language.
- For real-time media, the network and the kernel are part of your system. Call placement, ISP peering, NIC queues and softirq placement all decided call quality.
- End-to-end encryption for groups is a coordination problem. MLS epochs, version transitions and every client platform mattered more than the cipher.
- Observe in product terms. Trace by guild and sample by fan-out size; attribute cost by feature with CPU-time sampling.
- Migrate gradually with double writes, comparison and rollback, and pace rollouts by the real constraint, whether that is capacity, peering or developer trust.