Case Study: Discord
"While Discord is rich with features, most of it boils down to pub/sub." — Stanislav Vishnevskiy, How Discord Scaled Elixir to 5,000,000 Concurrent Users, Discord engineering blog, 6 July 2017
Summary: Discord is a chat, voice and community product whose backend, as its own engineers describe it, is a pub/sub fan-out engine (Elixir on the BEAM) in front of a Python API, Rust data services, ScyllaDB, Elasticsearch and a fleet of voice SFUs; this chapter walks the system with the 4-step method and keeps every claim tied to a dated Discord post. Focus: The WebSocket gateway, sessions and guild processes (GenServer, Manifold, FastGlobal, relays, passive sessions), message storage from MongoDB to Cassandra to ScyllaDB, hot partitions and request coalescing, read states and the Go-to-Rust rewrite, voice with WebRTC and an SFU, message search on Elasticsearch, presence and typing, push notifications with backpressure, the API on Kubernetes, the data platform, and what three published incidents teach. Learning goal: Given a "design Discord" prompt, scope it, estimate it with real published numbers, draw the high-level design, defend each subsystem decision with the evidence Discord published, say which parts are inference, and map each part onto the generic pattern you would reuse in your own system.
This is a case study in the System Design path. It does not re-teach mechanisms that other chapters own; it links them. WebSockets, heartbeats and presence in general live in Real-Time Communication; Cassandra and ScyllaDB internals (CQL, compaction, tombstones, shard-per-core) in Cassandra & ScyllaDB in Depth; caching and stampedes in Caching; Snowflake-style IDs in ID Generation at Scale; hot keys and routing in Sharding at System Level; the method itself in The 4-Step Approach.
How to read the evidence. Every architecture statement on this page comes from a Discord engineering post, Discord's developer documentation or a Discord GitHub README that was fetched and read; the post and its date are named next to the claim and listed in References. Anything that is a generalisation, an estimate or a guess about how something probably works is marked inference. The Go and Laravel code are small re-implementations written for this page; they are not Discord's code.
Page map
| If you are looking for | Go to |
|---|---|
| The whole system in three tables | Everything in one minute |
| Why Discord is worth studying, and the main trade-off | Why it exists |
| What changed over time, post by post | Where it comes from |
| Step 1 and 2: requirements and numbers | Scope, Estimate |
| Step 3: the high-level picture | High-level design |
| Gateway, sessions, guilds, Manifold, FastGlobal | Real-time gateway |
| Million-member servers, relays, passive sessions | Large guilds |
| MongoDB to Cassandra to ScyllaDB | Message storage |
| Hot partitions and request coalescing | Data services |
| Read states, GC latency, Go to Rust | Read states |
| WebRTC, SFU, voice servers, the edge | Voice and video |
| Elasticsearch, lazy indexing, cells | Search |
| Presence and typing indicators | Presence and typing |
| Push notifications and GenStage | Push |
| Python API, Rust, Kubernetes | API and infrastructure |
| Dagster, dbt, BigQuery | Data platform |
| Outages and what they taught | Reliability and incidents |
| Gateway opcodes, close codes, rate limits, knobs | Mechanics |
| Code | Go, Laravel |
| Classic failures and their fixes | Solving the classic problems |
| Which generic chapter each subsystem maps to | What you can copy |
| Decision table | Choosing |
| Monolith to distributed system | In architecture |
| Run the models yourself | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Subsystems and what Discord says it built.
| Subsystem | What Discord built | First public source | Generic pattern |
|---|---|---|---|
| Real-time gateway | Elixir WebSocket gateway; one GenServer per session and one per guild | 2017 Elixir post | Pub/sub fan-out over persistent connections |
| Large guilds | Relays (up to 15,000 sessions each), passive sessions, Rust NIF sorted set | 2019, 2023 posts | Split fan-out, do less work |
| Message storage | MongoDB, then Cassandra, then ScyllaDB; key ((channel_id, bucket), message_id) | 2017, 2023 posts | Partition by access pattern, bound partition size |
| Hot partitions | Rust data services with request coalescing and consistent-hash routing | 2023 post | Single-flight plus affinity routing |
| Read states | LRU cache in front of Cassandra; rewritten from Go to Rust | 2020 post | Write-behind cache; pick a runtime for the tail |
| Voice and video | WebRTC clients, in-house C++ SFU, voice servers per region, later edge PoPs | 2018, 2026 posts | Selective forwarding unit, client-initiated failover |
| Search | Elasticsearch, application-level sharding, lazy indexing; later cells on Kubernetes | 2017, 2025 posts | Index lazily, batch by destination, cells |
| Push | GenStage producer/consumer with demand of 100 and a shedding buffer | 2016 post | Backpressure plus load shedding |
| API | Python codebase, over 1,700 endpoints, several hundred Kubernetes deployments | 2026 post | Modular monolith deployed many ways |
| Data platform | Derived, replaced by Dagster + dbt on BigQuery | 2024 post | Declarative orchestration |
Numbers Discord published (with the year they were true).
| Number | Value | Year | Source post |
|---|---|---|---|
| Concurrent users | Nearly 5 million | 2017 | Scaled Elixir to 5,000,000 |
| Concurrent users | 11 million (title) | 2019 | Rust to scale Elixir |
| Messages per day | Well past 120 million | 2017 | Stores billions |
| Concurrent voice users | More than 2.6 million, 220 Gbps, 120 Mpps egress | 2018 | Voice with WebRTC |
| Cassandra nodes for messages | 12 (2017), 177 (early 2022) | 2017, 2023 | Stores billions / trillions |
| ScyllaDB nodes after migration | 72, 9 TB disk each | 2022 | Stores trillions |
| Historical-fetch p99 | 40-125 ms on Cassandra, 15 ms on ScyllaDB | 2022 | Stores trillions |
| Largest guild | Midjourney: over 10 million members, over 1 million online | 2023 | Maxjourney |
| Search | 26 billion documents (2017); trillions of messages, 40 clusters (2025) | 2017, 2025 | Indexes billions / trillions |
| SFU instances | More than 25,000 | 2026 | 3/25/26 voice outage |
The decisions in one line each.
| Decision | One-line reason Discord gave |
|---|---|
| Elixir/Erlang for real time | "The Erlang VM was the perfect candidate for the highly concurrent, real-time system" (2017) |
| Store every message forever | Users come back on any device and expect history (2017) |
| Cassandra over MongoDB | Linear scalability, automatic failover, predictable performance, open source (2017) |
| ScyllaDB over Cassandra | No garbage collector, shard-per-core isolation, faster repairs (2023) |
| A data-service layer | Control concurrency to hot partitions; coalesce identical reads (2023) |
| Rust for Read States | Go's GC caused latency spikes every ~2 minutes (2020) |
| Own SFU, no ICE, client-server voice | Large calls, IP privacy, DDoS protection, moderation (2018) |
| Lazy search indexing | Not everyone searches; index only on first search (2017) |
| Drop some push notifications | Better than the pipeline never recovering (2016) |
Why it exists
Discord is useful to study because its engineers wrote down, over ten years, the same system at very different sizes: four backend engineers and a 12-node Cassandra cluster in 2017, a million-plus users online in one server in 2023, more than 25,000 SFU instances in 2026. Few companies publish the before as honestly as the after. Each post names the bottleneck, the numbers and the fix, which is exactly the material a design interview or a real design review needs.
The core trade-off running through every Discord post is fan-out cost versus freshness: a chat product must show everything to everyone in real time, and the work to do that grows with the number of people online.
| Push everything to everyone now | Push less, or later |
|---|---|
| Every session gets every event it may see | Passive sessions get periodic deltas only |
| Simple client, simple mental model | Client must catch up when the user opens the guild |
| Work grows with online members squared per guild | Work grows with active members |
| Typing, presence, read markers all real time | Typing and read markers can be switched off under load |
| Search sees messages within a second | Search indexes in bulk, lazily, minutes later |
Everyday picture. Think of a guild as a stadium with one announcer (the guild process). Every time anything happens, the announcer must tell every seat. With 30 friends this is a conversation; with a million people it is impossible for one voice, so Discord hired section announcers (relays), stopped shouting at seats whose occupants are asleep (passive sessions), and gave the announcer a megaphone that speaks to each stand once instead of to each seat (Manifold). The rest of this page reuses the stadium.
Three common misunderstandings, up front
- "Discord is a microservices company that rewrote everything in Rust." The 2026 cost-attribution post describes "a unified Python codebase containing over 1700 API endpoints"; Rust appears in specific hot paths (Read States, data services, the authentication service, Elixir NIFs). Elixir still runs the real-time core.
- "Moving to ScyllaDB fixed hot partitions." The 2023 post says the opposite: "Hot partitions can still be a thing in ScyllaDB", which is why the data-service layer with coalescing came first.
- "Voice is peer-to-peer WebRTC." Discord's 2018 post says every call goes through its servers because peer-to-peer "becomes prohibitively expensive as the number of participants increases", and so that users' IP addresses are never exposed.
Where it comes from
The timeline below is the "what changed over time" view, built only from dated Discord posts. Read it top to bottom: almost every row is a fix for a bottleneck the previous row created.
| Date | Post | What changed |
|---|---|---|
| Early 2015 | Stores billions (2017) | Original Discord built "in just under two months"; everything in one MongoDB replica set |
| Nov 2015 | Stores billions | 100 million stored messages; data and index no longer fit in RAM |
| ~2016 | Stores billions | Messages move to Cassandra after a dark launch with double reads/writes; MongoDB phased out "within a week" |
| Summer 2016 | Push with GenStage (Dec 2016) | Push notifications choke on bursts; rebuilt with GenStage and Firebase XMPP |
| Jan 2017 | Stores billions | 12-node Cassandra cluster, RF 3, over 120 million messages a day |
| Jan 2017 | Indexes billions (Mar 2017) | Search launches on Elasticsearch with lazy indexing |
| Jul 2017 | Scaled Elixir | Nearly 5 million concurrent users; Manifold, FastGlobal and Semaphore released |
| Late 2017 | Reduced websocket traffic (2024) | Gateway connections compressed with zlib |
| Sep 2018 | Voice with WebRTC | 850+ voice servers, 13 regions, 2.6 million concurrent voice users |
| May 2019 | Rust to scale Elixir | Member list sorted set rewritten as a Rust NIF; Read States port to Rust completed |
| Feb 2020 | Go to Rust | Read States in Rust removes GC spikes; cache raised to 8 million Read States |
| By 2020 | Stores trillions (2023) | Every database except cassandra-messages migrated to ScyllaDB |
| Aug 2022 | Network disks | "Super-disk": Local SSD mirrored with Persistent Disk via RAID |
| May 2022 | Stores trillions | Messages switch to ScyllaDB; 177 Cassandra nodes become 72 ScyllaDB nodes |
| Oct 2023 | Maxjourney | Relays, passive sessions, worker processes with ETS for a 1M-online guild |
| Nov 2023 | Authentication outage | 50-minute outage during a zonal ScyllaDB OS upgrade |
| Apr 2024 | Reduced websocket traffic | zstd streaming rolled out; passive sessions v2 in late May; ~40% less gateway bandwidth |
| Jul 2024 | Data orchestration | In-house Derived replaced by Dagster + dbt |
| Apr 2025 | Indexes trillions | Search moved to Elasticsearch cells on Kubernetes, Pub/Sub queue |
| Feb 2025 onward | Voice to the edge (2026) | Voice and video moved onto Cloudflare PoPs; over 80% of traffic there by 2026 |
| Mar 2026 | Voice outage (Apr 2026) | Session pods scaled down without handoff; voice syncers overwhelmed |
| Jun 2026 | Cost attribution | Python API: 1,700+ endpoints, ~700 background tasks, several hundred Kubernetes deployments |
The concept catalogue
The catalogue follows the 4-step method from The 4-Step Approach: scope, estimate, high-level design, then one decision block per subsystem. Each block has the usual order: plain words, the usual wrong belief, a definition, a sequence, real scenarios, what Discord did (with sources), and how to apply it.
Step 1: Scope the problem Must-know
In plain words: before drawing boxes, write down what the product must do and how good it must be, in the words Discord used.
Common misunderstanding: "Scope is the feature list." The features are the easy half; the non-functional requirements (history forever, real-time fan-out, voice quality, cost of search) are what shaped every Discord decision.
Definition: the functional and non-functional requirements Discord stated in its posts.
| Requirement | Discord's words or fact | Source |
|---|---|---|
| Keep all history | "store all chat history forever" | Stores billions, 2017 |
| Read/write mix | Reads "extremely random", read/write ratio "about 50/50" | Stores billions, 2017 |
| Latency target | Alert when API p95 goes above 80 ms | Stores billions, 2017 |
| No message cache | Did not want to cache messages in Redis or Memcached | Stores billions, 2017 |
| Real-time ordering | Clients "depend on linearizability of events" | Scaled Elixir, 2017 |
| Multiparty voice | Every call multiparty; 1,000 people taking turns seen | Voice, 2018 |
| Search is an accessory | Search "shouldn't cost more than the actual storage of messages" | Indexes billions, 2017 |
| Self-healing | Small team, no dedicated devops | Stores billions, Indexes billions |
Interview step Discord answer
1 Who are the users? gamers, then any community; 3 people to 10M members per guild
2 Core actions? send/read messages, presence, typing, voice/video, search, push
3 Hard constraints? history forever, real-time order per channel, p95 alerts at 80 ms
4 What may degrade? typing, read markers, some push notifications, search freshness
5 Out of scope here payments (Nitro), moderation ML, client renderingReal scenario: an interviewer asks "design Discord"; you answer with these eight rows and ask which to drop. A product manager asks for full-text search; you note Discord's cost rule and propose lazy indexing.
Fix / how to use it: copy the table shape (requirement, number, source) for any system you design; the "what may degrade" row is the one people forget and Discord used during every incident.
Step 2: Estimate with published numbers Must-know
In plain words: turn the requirements into rates, sizes and connection counts, using Discord's own numbers where they exist and labelled guesses where they do not.
Common misunderstanding: "Concurrent users tells me the message rate." It does not; Discord's 2017 storage post shows guild types with wildly different rates (voice-heavy servers barely write; large public servers write thousands a day). The method lives in Capacity Estimation.
Definition: back-of-the-envelope figures for traffic, storage, connections and fan-out.
| Quantity | Value | Status |
|---|---|---|
| Messages per day (2017) | 120 million | Published |
| Average write rate | 120,000,000 / 86,400 ≈ 1,400 per second | Inference (arithmetic) |
| Peak write rate | ≈ 4,200 per second at an assumed 3x peak factor | Inference (assumed factor) |
| Bytes per stored message | ~1 KB with metadata | Inference (assumption, not published) |
| Daily new storage (2017) | ~120 GB before replication, ~360 GB at RF 3 | Inference |
| Sessions per Erlang VM | Up to 500,000 live sessions | Published (2017) |
| Guilds per average user | 5 | Published (2017) |
| Fan-out, one message, 1M online guild | 1,000,000 deliveries; ~100,000 if 90% are passive | Inference from published ratio |
| Relays for 1M active sessions | 1,000,000 / 15,000 ≈ 67 | Inference from published limit |
| Migration speed | Up to 3.2 million messages per second | Published (2023) |
Fan-out arithmetic (Maxjourney post, "I love jello")
1 1,000 online, each sends once -> 1,000 x 1,000 = 1 million deliveries
2 10,000 online -> 10,000 x 10,000 = 100 million
3 100,000 online -> 100,000 x 100,000 = 10 billion
4 passive sessions (~90% in large guilds) cut each row by about 10x (inference: assumes uniform activity)Real scenario: sizing a gateway fleet (sessions per VM), sizing a messages cluster (daily growth times replication), deciding whether one process per guild can cope (deliveries per second per guild).
Fix / how to use it: keep published and inferred numbers in separate columns; when a figure is inferred, write the assumption next to it, as above.
Step 3: High-level design Must-know
In plain words: clients hold one WebSocket to the gateway; everything that happens is published to a guild process that fans it out; writes go through an HTTP API to databases behind data services; voice runs on separate media servers.
Common misunderstanding: "The WebSocket gateway is the backend." The 2018 voice post separates Discord Gateway, Discord Guilds and Discord Voice, and the 2023 storage post separates the "API monolith" from the data services and ScyllaDB.
Definition: the boxes and arrows below, each one named in a Discord post.
Sending a message (assembled from the 2017, 2023 and 2026 posts; ordering of steps 3-4 is inference)
1 client -> API (HTTPS POST /channels/{id}/messages) Python API, Kubernetes
2 API -> data service (gRPC, routed by channel_id) Rust
3 data service -> ScyllaDB INSERT ((channel_id, bucket), message_id)
4 API -> guild process: publish MESSAGE_CREATE Elixir
5 guild -> relays -> session processes (permission checks) Manifold groups by node
6 session -> gateway -> client WebSocket (zstd-compressed) op 0 dispatch
7 offline recipients -> push collector -> pushers -> Firebase
8 message -> Pub/Sub -> index router -> Elasticsearch searchable laterReal scenario: the "Awaiting Endpoint" status in a voice call (guilds looking for a voice server); a message that appears instantly but is not searchable for a while; a mobile notification for a user who is offline.
Fix / how to use it: in an interview, draw this picture first, then spend the time on the two hardest arrows: guild fan-out and the message read path.
Real-time gateway: sessions, guilds, Manifold, FastGlobal Must-know
In plain words: each connected device gets a small Elixir process (a session); each server gets one process (a guild); the guild tells all its sessions about everything, in order.
Common misunderstanding: "Sending a message between Erlang processes is free." The Manifold README measured "about 70 µs/op" for send/2, multiplied by tens of thousands of connected sessions per event.
Definition: "Users connect to a WebSocket and spin up a session process (a GenServer), which then communicates with remote Erlang nodes that contain guild ... processes (also GenServers)" (2017). Discord places processes on nodes with consistent hashing (2017: "Discord is a distributed system achieved through consistent hashing"; 2026: a hash ring powered by etcd).
Event flow inside the BEAM cluster (2017 post + Manifold README)
1 user A types a message; API publishes to guild G's process (one GenServer, one mailbox)
2 G looks up its 30,000 session PIDs spread over 10 session nodes
3 naive: 30,000 send/2 calls x ~70 us = ~2.1 s of sender time per event (inference: arithmetic)
4 Manifold: group PIDs by node -> 10 sends to Manifold.Partitioner on each node
5 each partitioner hashes PIDs with :erlang.phash2, hands groups to per-core workers
6 workers send to local sessions; order per sender is preserved (send/2 linearizability)Real scenario: /r/Overwatch with up to 30,000 concurrent users in 2017; session nodes restarting and every session looking up 5 guild nodes on the ring at ~12 µs per call (30 seconds per crashed node, per the post); a burst of reconnects stampeding ten guild-registry processes.
What Discord did:
| Problem (2017 post) | Fix | Measured effect |
|---|---|---|
| Fan-out send cost | Manifold: one send per remote node | Packets/sec dropped by half (README) |
| Ring lookup hot path | ETS (7 µs) then FastGlobal constant pool (0.3 µs) | 17.5 s to 750 ms per node restart |
| Registry stampede | Semaphore on :ets.update_counter/4 | Sessions "did not even budge" in a later presence crash |
| Large messages to many nodes | Manifold pack_mode: :binary encodes once (README) | Fewer ETF encodings |
| Sender busy | Manifold send_mode: :offload to sender pool (README; Maxjourney) | Needed min_bin_vheap_size tuning |
Fix / how to use it: the transferable ideas are batching per destination node and making the hot read path copy-free. See the Go model in Go (fanout), and Real-Time Communication for WebSocket scaling in general.
Large guilds: relays, passive sessions, sorted sets in Rust Must-know
In plain words: when one server has a million people online, one process cannot do all the work, so Discord splits it across relays and simply stops sending most updates to people who are not looking.
Common misunderstanding: "Just run several guild processes per server." The Maxjourney post explains why not: some things "need a full view", such as voice-channel membership and member lists, so one guild process stays the routing point.
Definition: a relay sits between the guild and sessions and does fan-out with permission checks for up to 15,000 sessions; a passive session is a user-guild connection that receives only periodic summaries until the user opens that guild (Maxjourney, 2023).
A message in a 1M-online guild (Maxjourney 2023, websocket post 2024)
1 guild process receives MESSAGE_CREATE; does only the work that needs the full view
2 forwards to ~N relays; each relay checks permissions for its <=15,000 sessions
3 ~90% of user-guild connections are passive: they get nothing now
4 periodically, passive sessions get PASSIVE_UPDATE (v2 sends only the delta)
5 user clicks the guild: session upgraded to active, receives the full firehoseReal scenario: Midjourney (over 10 million members, over 1 million online); an @everyone ping that must compute who can see it (moved to worker processes reading members from ETS); handing a guild to another machine during a deploy (multi-GB member state copied by a worker while the guild keeps serving).
What Discord did:
| Technique | Source | Effect reported |
|---|---|---|
| Passive sessions | Maxjourney 2023 | Fan-out work about 90% cheaper in large servers |
| Relays | Maxjourney 2023 | Guilds in the hundreds of thousands of members |
| Members in ETS + worker processes | Maxjourney 2023 | Expensive scans off the guild's hot loop |
| Member list SortedSet as a Rust NIF | Rust to scale Elixir 2019 | Worst case 3.68 µs at 1,000,000 items vs 640 µs pure Elixir at 250,000 |
| PASSIVE_UPDATE_V2 deltas | Websocket post 2024 | From 35% to 5% of gateway bandwidth |
Fix / how to use it: "do less work" beats "do work faster": define which subscribers need real-time updates and send summaries to the rest. The generic form is in Feeds: Fan-Out.
Message storage: MongoDB to Cassandra to ScyllaDB Must-know
In plain words: messages are stored by channel and by 10-day time bucket, newest first, so "load the last 50 messages of this channel" reads one small, contiguous slice.
Common misunderstanding: "Cassandra supports 2 GB partitions, so a channel can be one partition." The 2017 post: "just because it can be done, it doesn't mean it should"; partitions over 100 MB caused GC pressure during compaction and expansion.
Definition: primary key ((channel_id, bucket), message_id) where message_id is a Snowflake and the bucket is a static time window derived from the ID (2017; unchanged in the 2023 post). Writes and reads at quorum consistency (2023).
The "big surprise" (Stores billions, 2017)
1 public server deletes millions of messages via the API, leaving 1
2 each delete is a tombstone; tombstones live 10 days (default) until compaction
3 a user opens the channel; Cassandra scans millions of tombstones to find 1 message
4 JVM generates garbage faster than it can collect: 10-second stop-the-world GCs, node unresponsive
5 fix: tombstone lifetime 10 days -> 2 days (nightly repairs make it safe)
6 fix: remember empty buckets per channel and skip them on later readsReal scenario: a voice-heavy server with a few messages a year (a 50-message read touches many buckets and disk seeks); a busy public server (recent messages hot in cache); concurrent edit and delete producing a row with only the primary key and text (Discord deletes rows whose required author_id is null); writing nulls creating 12 tombstones per message (fix: write only non-null columns).
What Discord did:
| Phase | Cluster | Main pain | Main fix |
|---|---|---|---|
| 2015 MongoDB | One replica set, index (channel_id, created_at) | Index out of RAM at 100M messages | Move to Cassandra |
| 2017 Cassandra | 12 nodes, RF 3, ~1 TB compressed per node | Tombstones, large partitions | 10-day buckets, 2-day tombstones |
| 2022 Cassandra | 177 nodes, ~4 TB per node | Hot partitions, compaction backlog, GC pauses | Data services, then ScyllaDB |
| 2022 ScyllaDB | 72 nodes, 9 TB each | (quiet) | Rust migrator, 9 days instead of 3 months |
Fix / how to use it: the CQL schema and the bucket math are in Solutions and the Go/PHP snowflake code. Engine internals (tombstones, compaction, gossip, hinted handoff) are owned by Cassandra & ScyllaDB in Depth.
Hot partitions and data services with request coalescing Must-know
In plain words: when thousands of people open the same channel at once, Discord makes one database read and hands the result to all of them.
Common misunderstanding: "A cache would do the same." A TTL cache still lets the first wave of misses through at the same moment (a stampede), and Discord's 2017 requirement was not to cache messages in Redis. Coalescing joins requests that are in flight; it needs no TTL and serves no stale data. Inference: the two combine well, see Caching.
Definition: "data services — intermediary services that sit between our API monolith and our database clusters", written in Rust, with "roughly one gRPC endpoint per database query", no business logic, and request coalescing: the first request spawns a worker task, later requests for the same row subscribe to it. Upstream, consistent hash-based routing by a routing key (the channel ID for messages) sends all requests for a channel to the same instance (2023).
@everyone announcement in a large server (2023 post's own example)
1 t=0 announcement posted; 50,000 clients receive MESSAGE_CREATE
2 t=0.2s thousands of clients fetch the channel: GET messages?limit=50
3 router hashes channel_id -> every request goes to data service B
4 first request on B spawns worker task W for partition (channel, bucket)
5 later requests find W in flight and subscribe
6 t=0.2s+ W reads ScyllaDB once; all subscribers get the same rows
7 without routing: requests spread over all instances, each makes its own read (inference)Real scenario: the World Cup final 2022 message spikes shown in the 2023 post; an @everyone ping; a game launch announcement.
What Discord did and what it did not solve:
| Layer | What it does | Limit Discord admits |
|---|---|---|
| Request coalescing | One query per row for concurrent callers | Only helps identical, concurrent requests |
| Consistent-hash routing | Puts identical requests on one instance | Uneven if one channel is extremely hot (inference) |
| ScyllaDB | No GC, shard-per-core isolation | "Hot partitions can still be a thing" |
| Super-disk storage | Local SSD reads, Persistent Disk durability (RAID) | 40-minute RAID sync on startup (auth outage post) |
Fix / how to use it: see coalesce in Go and CoalescedMessageReader in Laravel; the general technique is in Write Buffering, Batching, Coalescing.
Read states and the Go-to-Rust rewrite Important
In plain words: Discord keeps, for every user and every channel, "how far have you read and how many mentions are waiting", and serves it from memory because it is touched on every connect, every message and every read.
Common misunderstanding: "Go was slow." The post says the Go version "was fast most of the time"; the problem was latency spikes every two minutes from the garbage collector scanning a huge cache, which no GOGC setting fixed.
Definition: "There is one Read State per User per Channel", with counters updated atomically; each server holds an LRU cache (millions of users, tens of millions of Read States, hundreds of thousands of updates per second) backed by Cassandra, committing on eviction and 30 seconds after an update (tens of thousands of writes per second) (2020).
Why the spikes (Go to Rust, 2020; Go 1.9.2)
1 cache holds tens of millions of live Read States (pointers everywhere)
2 service allocates little, so GC is not triggered by heap growth
3 Go forces a GC run if none happened for 2 minutes
4 the collector must scan the whole LRU to prove what is still referenced
5 -> latency and CPU spike roughly every 2 minutes
6 Go mitigation: many smaller partitioned LRUs -> smaller spikes, more misses, worse p99
7 Rust: evicted entries freed immediately, no collector; cache raised to 8 million Read StatesReal scenario: the unread badge on every channel; the @mention counter; login, which loads read states for all channels (the READY payload includes read states, per the 2024 websocket post); during the 2023 auth outage Discord switched off "marking messages as read" to shed load.
What Discord did:
| Option | Result in the post |
|---|---|
| Tune GC percent on the fly | No change (not allocating fast enough to trigger more GCs) |
| Smaller, partitioned LRU caches | Smaller spikes, higher p99 from more database loads |
| Rewrite in Rust (nightly async, tokio) | No spikes; better latency, CPU and memory |
| BTreeMap instead of HashMap, fewer copies | Further memory and CPU savings |
| Raise cache to 8 million Read States | Average latency in microseconds |
Inference: modern Go has GOMEMLIMIT (Go 1.19+) and better GC pacing, so the same experiment today might end differently; Discord's post is about Go 1.8 to 1.10. The lesson that survives is about tail latency of a huge long-lived heap, not about one language. The Go model in this page (readstates) mirrors the design, not the runtime. Write-behind as a pattern is in Write Buffering.
Voice and video: WebRTC, SFU, voice servers, the edge Must-know
In plain words: your client sends audio once to a Discord voice server, and that server forwards it to everyone else in the call.
Common misunderstanding: "WebRTC means browser-to-browser." WebRTC is a set of audio, video and networking components; Discord uses it in clients but routes all media through its own SFU, and its native apps skip SDP negotiation, ICE and DTLS/SRTP in favour of a minimal exchange and Salsa20 encryption (2018).
Definition: a selective forwarding unit (SFU) receives each participant's media and forwards selected streams to the others without mixing. Discord's 2018 design: a voice server per guild (all voice channels of a guild on the same server) with a signalling component in Elixir and a "homegrown SFU (written in C++)".
Joining a voice channel (Voice with WebRTC, 2018)
1 client updates its voice state over the gateway WebSocket
2 Discord Guilds picks the least-utilised voice server in the region from etcd -> "Awaiting Endpoint"
3 Guilds pushes all voice states to that voice server; client is told the endpoint
4 client opens a second WebSocket to the voice server (voice WebSocket)
5 client exchanges UDP with the SFU -> "Voice Connected"
6 SFU forwards packets; drops packets of server-muted users; handles RTCP bandwidth feedback
7 server dies or is DDoSed: removed from discovery, Guilds assigns a new one, clients reconnectReal scenario: a 1,000-person stage where people take turns; a DDoS against a voice server (Discord moves the guild to another server); a guild owner changing voice region; a user behind NAT (no ICE needed, periodic pings keep the firewall open).
How it evolved:
| Year | Fact | Source |
|---|---|---|
| 2018 | 850+ voice servers, 13 regions, 30+ data centers, 2.6M concurrent voice users | Voice with WebRTC |
| 2018 | Gateway and Guilds on Google Cloud Platform; voice on physical servers at several providers | Voice with WebRTC |
| 2025-2026 | Voice moved onto Cloudflare PoPs (300+ cities); over 80% of voice/video traffic there | Voice to the edge |
| 2026 | One SFU instance hosts a whole call; host placement matters more than coverage for mixed-region calls | Voice to the edge |
| 2026 | More than 25,000 SFU instances; voice syncers place calls and send RPCs to SFUs | 3/25/26 voice outage |
| 2026 | Discovery for edge hosts in Valkey with a ten-minute TTL; etcd strained at 25,000 hosts | Voice to the edge |
Inference: Discord's posts read here say the SFU was C++ (2018); none of them say it was rewritten in Rust, so do not claim that. Discord does say it uses Rust for Go Live video capture and encoding on the client (2020). UDP versus TCP for media is in TCP & UDP.
Message search: Elasticsearch, lazy indexing, cells Important
In plain words: Discord only builds a search index for a server the first time someone searches it, indexes messages in bulk from a queue, and keeps each server's messages together on one small index.
Common misunderstanding: "Elasticsearch near-real-time refresh is free." The 2017 post found the default 1-second refresh across a thousand indices burned CPU and disk with tiny segments; Discord set refresh to 60 minutes and refreshed a shard on demand when a search hit a "dirty" guild.
Definition: application-level sharding into "Shards" (an Elasticsearch cluster plus index pair), a persistent shard mapping in Cassandra cached in Redis, a load-aware shard allocator on a Redis sorted set, and message fields stored only in the inverted index (results fetched from Cassandra) (2017).
Search read path (Indexes billions, 2017)
1 look up the Shard for guild_id (Redis cache, Cassandra source of truth)
2 check Redis: is (Shard, guild_id) dirty?
3 if dirty: refresh that Elasticsearch index, mark Shard clean
4 run the query (permission-checked in the Search API)
5 fetch message bodies and 2 messages of context from CassandraReal scenario: a server nobody has ever searched (no index until the first search, then an "initial" 7-day phase and a "deep" full-history phase); a "Big Freaking Guild" nearing Lucene's ~2 billion document limit; cross-DM search, which needed messages sharded by user rather than by guild.
How it evolved:
| Problem (2025 post) | Fix (2025 post) |
|---|---|
| Redis indexing queue dropped messages when CPU maxed | Google Cloud Pub/Sub with guaranteed delivery |
| A 50-message bulk spanned many nodes; one node down failed ~40% of batches | Router batches by destination (cluster, index) with a tokio task per destination |
| 200+ node clusters, master nodes OOM | Many smaller clusters grouped in "cells" on Kubernetes (ECK operator) |
| No rolling restarts (log4shell patch needed full downtime) | ECK rolling upgrades; dedicated master, ingest and data nodes per zone |
| Lucene MAX_DOC ~2 billion per index | BFG cell: reindex big guilds to multi-shard indices with dual-writes |
| No cross-DM search | Separate user-dm-messages cell, DMs indexed twice (once per recipient) |
Results reported in 2025: median query latency from 500 ms to under 100 ms, p99 from 1 s to under 500 ms, 40 clusters. Search engines in general: Search Systems and Full-Text Search.
Presence and typing indicators Good to know
In plain words: "online", "idle", "playing X" and "is typing..." are tiny, frequent events that matter only right now; Discord fans them out through the same guild processes and treats them as the first thing to drop under pressure.
Common misunderstanding: "Presence is just a column in the users table." In Discord's 2017 post, "When a user comes online, they connect to a guild, and the guild publishes a presence to all other connected sessions", and presence has its own services that can crash and rebuild "within minutes".
Definition: presence updates (PRESENCE_UPDATE) and typing events (TYPING_START) are gateway dispatches; for bots the documentation limits outbound gateway events to 120 per connection per 60 seconds, and sending an Update Presence is one of those events.
Typing under load (2023 auth outage post)
1 10:52 authentication cluster overloaded; availability ~25%
2 11:05 engineers turn off sending typing events and marking messages as read
3 auth functionality restored to ~50% of users
4 11:43 full recovery after the zone returns; typing back onReal scenario: the "X is typing..." line (a 636-byte TYPING_START compresses to 466 bytes, or 187 bytes with a trained zstd dictionary, per the 2024 post); the presence storm when a large guild comes online; Discord's API marks the typing-indicator feature as tier E, the lowest of the tiers shown in the 2026 post (messaging is tier S).
| Event | Delivery promise (inference from posts) | Dropped under load? |
|---|---|---|
| MESSAGE_CREATE | Every active session that may see it, in order | No |
| PRESENCE_UPDATE | Best effort, rebuilt after crashes | Can lag |
| TYPING_START | Best effort, ephemeral | Yes, switched off in 2023 |
| Read state ack | Eventually persisted | Yes, switched off in 2023 |
Fix / how to use it: classify every real-time event by "what breaks if it is late or missing"; give the cheap-to-lose ones a kill switch. Presence in general: Real-Time Communication.
Push notifications: GenStage backpressure and load shedding Important
In plain words: when a huge server sends an announcement, millions of phones need a notification; Discord limits how many are in flight and throws away the overflow rather than letting the pipeline fall over.
Common misunderstanding: "Every notification must be delivered." The 2016 post says a few were dropped in a burst, and "If a few notifications weren't dropped, the system may never have recovered".
Definition: two GenStage stages: a Push Collector (producer, one per machine, with a buffer_size that sheds when full) and many Pushers (consumers) that demand at most 100 requests at a time because Firebase's XMPP connections allow no more than 100 pending requests (2016). Discord sends pushes "only ... when users are not active on the application".
A burst (Push with GenStage, 2016)
1 17:47:00 nominal
2 17:47:30 burst starts; collector buffer blips, pushers drain it
3 17:48:50 pushers cannot send to Firebase as fast as requests arrive; buffer fills
4 17:50:00 buffer peaks; collector sheds some requests
5 17:52:30 completely back to normal; "no noticeable impact to the system or users"Real scenario: /r/Overwatch at 25,000 concurrent users and Pokémon GO servers in summer 2016; an @everyone in a million-member guild (inference: same mechanism, much bigger).
Fix / how to use it: demand-driven consumers plus a bounded buffer that sheds; see pusher in Go, and the general rules in Backpressure & Flow Control and Load Shedding.
API, Rust adoption and Kubernetes Important
In plain words: the HTTP API is one big Python codebase deployed as many separate Kubernetes deployments; Rust is used where latency or safety matter most.
Common misunderstanding: "One codebase means one deployment." Discord runs "the same codebase in all of our Kubernetes deployments, each of which handles a specific subset of HTTP traffic or background tasks" (2026).
Definition: a unified Python API (1,700+ endpoints, ~700 background tasks, several hundred Kubernetes deployments, phased rollouts), each endpoint tagged with a feature, an owning team and a tier used for SLOs (2026); Rust in Read States (2020), data services (2023), the authentication service (2023), Elixir NIFs and client video (2020).
Where each language sits (from the posts read for this page)
1 Elixir/Erlang gateway, sessions, guilds, relays, presence, voice signalling, voice syncers
2 Python HTTP API monolith and background tasks; earlier, Celery index workers (2017)
3 Rust data services, Read States, auth service, search index router, NIFs, client encode
4 C++ SFU (2018), client media engine on WebRTC native
5 Go the old Read States (2020); an image-resizing service per a post title not read hereReal scenario: cost attribution per feature (sampling which feature a Python worker is busy with); the 2026 Kubernetes migration of stateful Elixir services, which caused the voice outage; stateless services on Kubernetes before stateful ones (2025 search post).
| Platform fact | Source |
|---|---|
| Gateway and Guilds on Google Cloud Platform | Voice, 2018 |
| Stateless services on Kubernetes; stateful moved later | Indexes trillions, 2025 |
| Elixir services migrating to Kubernetes ("the blessed path") | Voice outage, 2026 |
| Validating admission webhook blocks scale-down until pods hand off | Voice outage, 2026 |
| Scylla Control Plane (SCP) automates ScyllaDB operations; 7-person persistence team | Automates ScyllaDB, 2026 |
Fix / how to use it: inference: the pattern is a modular monolith with many deployment shapes plus small, rewritten hot paths, which is the opposite of "split everything". See Containers & Kubernetes and Monolith vs Microservices.
Data platform: from Derived to Dagster and dbt Good to know
In plain words: analytics data is transformed by SQL models (dbt) whose order and freshness are managed by an orchestrator (Dagster), all running on Kubernetes against BigQuery.
Common misunderstanding: "Data orchestration is cron." Discord chose Dagster for "declarative automation", which schedules assets by their dependencies (hourly feeding daily) rather than by fixed times (2024).
Definition: "Transformation 2.0" (T2): over 2,000 dbt tables, over 12,000 dbt tests, about 4,000 materialisations a day, replacing the in-house Derived system used for five years (2024).
Problems Discord hit and fixed (Data orchestration, 2024)
1 dbt incremental models share a temp table -> race when partitions run in parallel -> changed temp storage
2 partition-by-partition backfills slow on BigQuery -> open-source change to cap partitions per backfill
3 code version must be consistent across partitions -> sensors and jobs over Dagster's GraphQL APIReal scenario: a product dashboard that is late ("Why isn't my data asset updating?" now self-serve); data-quality checks that warn or block downstream runs; notifications to table owners through a Discord app called DAN.
Fix / how to use it: OLTP stores (ScyllaDB) and the warehouse (BigQuery) are separate systems with separate tools; see OLTP vs OLAP and Big Data Architectures.
Reliability: what three incidents teach Must-know
In plain words: Discord's outages were not caused by one broken box; each was a normal operation (an upgrade, a scale-down) meeting a hidden weak spot, then made worse by retries or reconnects.
Common misunderstanding: "Three-zone replication with quorum means a zone can always go down safely." In November 2023 one zone was down on purpose and one degraded disk in another zone was enough to break the authentication cluster.
Definition: the published incidents: the 2017 registry stampede (Scaled Elixir), the 6 November 2023 authentication outage (about 50 minutes) and the 25 March 2026 voice outage (12:13 to 15:30 PDT).
3/25/26 voice outage, condensed (Discord's own post)
1 12:13 Kubernetes change halves session pods; grace period ends before handoff -> 17% of sessions stopped
2 process monitors fire {:DOWN, ...}; gateways tell clients to reconnect
3 start-session rate limit not re-tuned for pod count -> gateway memory exhaustion in us-east1-b
4 mass call teardown and re-creation -> burst of HTTPS connections from voice syncers to SFUs
5 connection pool supervisor (one GenServer) mailbox grows; etcd registration also blocked
6 syncers drop out of the etcd hash ring (60 s TTL); calls stuck in "Awaiting Endpoint"
7 13:43 lower syncer spawn rate limits; 14:15 capacity doubled; 14:26 healthyWhat each incident changed:
| Incident | Trigger | Amplifier | Changes Discord made |
|---|---|---|---|
| 2017 guild registry | Burst of reconnecting sessions | Timeouts left requests queued; retries piled up | Semaphore to fail fast |
| 2023 authentication | Zonal OS upgrade + degraded NVMe disk | Retry storm from the API; cold row caches | Doubled cluster, disk-degradation detection, Scylla control plane |
| 2026 voice | Pods scaled down without handoff | Reconnect thundering herd; single supervisor bottleneck | Admission webhook, PartitionSupervisor, tuned rate limits, more monitoring |
Fix / how to use it: Discord frames capacity problems as "an economics problem: your solutions either increase supply ... or reduce demand" (2026). The generic chapters: Cascading Failures, Timeouts, Retries & Jitter, Circuit Breaker, Rate Limiting.
Mechanics
These are the exact knobs and codes Discord publishes or names. Gateway and REST details come from Discord's developer documentation (the public bot API); inference: the first-party clients use the same gateway concepts, as the 2024 websocket post's references to op 0 dispatches, READY and TYPING_START suggest, but the internal limits for users are not published.
Gateway protocol
| Step or knob | Value | Note |
|---|---|---|
| Hello (op 10) | heartbeat_interval, example 45000 ms | First message after connecting |
| First heartbeat | After heartbeat_interval * jitter, jitter in 0..1 | Spreads reconnecting clients |
| Heartbeat (op 1) / ACK (op 11) | No ACK between heartbeats = zombied connection | Reconnect with a close code other than 1000/1001 |
| Identify (op 2) | 1,000 per 24 hours per bot | Resume does not count |
| Resume (op 6) | session_id, last sequence, resume_gateway_url | Missed events replayed, then Resumed |
| Invalid Session (op 9) | d: true means resumable | Otherwise identify again |
| Outbound rate limit | 120 events per connection per 60 s | Exceeding disconnects |
| Transport compression | zlib-stream or zstd-stream | Discord's own clients moved to zstd in 2024 |
| Sharding | shard_id = (guild_id >> 22) % num_shards | Guild-based routing for bots |
| Identify concurrency | max_concurrency from session start limit | Exceeding gets op 9 |
Gateway close codes
| Code | Name | Reconnect? |
|---|---|---|
| 4000 | Unknown error | Yes |
| 4004 | Authentication failed | No |
| 4007 | Invalid seq | Yes, new session |
| 4008 | Rate limited | Yes, slower |
| 4009 | Session timed out | Yes, new session |
| 4011 | Sharding required | No, shard first |
| 4014 | Disallowed intent(s) | No |
REST rate limits
| Limit | Value | Signal |
|---|---|---|
| Global (bots) | 50 requests per second | HTTP 429, X-RateLimit-Global |
| Per route | Varies, grouped by X-RateLimit-Bucket | Retry-After / retry_after |
| Invalid requests | 10,000 per 10 minutes per IP (401, 403, 429) | Temporary Cloudflare ban |
Identifiers and storage knobs
| Knob | Value | Source |
|---|---|---|
| Snowflake timestamp | Bits 63-22, ms since 1420070400000 (first second of 2015) | Developer docs |
| Worker / process / increment | 5 / 5 / 12 bits | Developer docs |
| Message bucket | About 10 days, keeps partitions under 100 MB | Stores billions |
| Replication / consistency | RF 3 across three zones; quorum reads and writes | Stores billions; auth outage |
| Tombstone lifetime | Lowered from 10 days (default) to 2 days | Stores billions |
| ScyllaDB disk | RAID mirror of Local SSD + Persistent Disk; ~40 min sync at boot | Network disks; auth outage |
| Elasticsearch index | 1 primary shard, 1 replica, refresh every 60 min (2017) | Indexes billions |
| Elasticsearch index size target | 200M messages and 50 GB per index (2025) | Indexes trillions |
| zstd gateway settings | Level 6, chainlog 16, hashlog 16, windowlog 18 | Reduced websocket traffic |
| BEAM GC tuning | min_bin_vheap_size raised to a few MB for guilds | Maxjourney |
| Firebase XMPP | Max 100 pending requests per connection | Push with GenStage |
| Relay size | Up to 15,000 sessions per relay | Maxjourney |
Go
The Go module (academy/case-study-discord, standard library only) models five mechanisms from the posts. None of it is Discord's code; Discord's real implementations are in Elixir and Rust.
Before
A read-state service that does a database round trip for every mention, every ack and every read. It is correct; it is the wrong shape for a path that is "accessed every time you connect to Discord, every time a message is sent and every time a message is read".
// Package before is the naive first version of a read-state service:
// correct, simple, and the wrong shape for a hot path. Every mention and
// every ack is a synchronous read-modify-write against the database, so a
// busy channel turns one user's unread badge into thousands of writes per
// minute, and every Get is a database round trip.
package before
import "sync"
// Key identifies one Read State.
type Key struct{ UserID, ChannelID int64 }
// State is the persisted row.
type State struct {
LastReadMessageID int64
MentionCount int
}
// DB counts round trips so the cost is visible.
type DB struct {
mu sync.Mutex
rows map[Key]State
RoundTrips int
}
// NewDB returns an empty in-memory stand-in for the database.
func NewDB() *DB { return &DB{rows: map[Key]State{}} }
// Mention is a read-modify-write per event (and a lost-update risk
// if two API workers do it at once without a transaction).
func (d *DB) Mention(k Key) {
d.mu.Lock()
defer d.mu.Unlock()
d.RoundTrips += 2 // SELECT then UPDATE
s := d.rows[k]
s.MentionCount++
d.rows[k] = s
}
// Ack writes immediately.
func (d *DB) Ack(k Key, messageID int64) {
d.mu.Lock()
defer d.mu.Unlock()
d.RoundTrips++
d.rows[k] = State{LastReadMessageID: messageID}
}
// Get always goes to the database.
func (d *DB) Get(k Key) State {
d.mu.Lock()
defer d.mu.Unlock()
d.RoundTrips++
return d.rows[k]
}After
Read states as a partitioned LRU with write-behind. Mentions and acks touch memory; a dirty entry is committed once, 30 seconds after its first change, or when it is evicted. The test shows 500 mentions becoming one database write.
// Package readstates models the Read States design that Discord describes in
// "Why Discord is switching from Go to Rust" (2020): one Read State per user
// per channel, held in partitioned LRU caches for fast counter updates,
// persisted by committing on eviction and by a commit scheduled 30 seconds
// after an update. It is a teaching model, not Discord's code.
//
// Note: this is Go. The post's point was that, with a huge long-lived heap,
// Go's garbage collector (forced at least every 2 minutes) scanned the whole
// cache and caused latency spikes; partitioning the cache was the Go-side
// mitigation, and rewriting in Rust removed the collector entirely.
package readstates
import (
"container/list"
"hash/fnv"
"sync"
"time"
)
// Key identifies one Read State.
type Key struct{ UserID, ChannelID int64 }
// State is what the client needs to draw unread badges.
type State struct {
LastReadMessageID int64
MentionCount int
dirtySince time.Time
}
// Store is the database (Cassandra, later ScyllaDB, in Discord's post).
type Store interface {
Load(k Key) (State, error)
Commit(k Key, s State) error
}
// CommitDelay is the deferred write: 30 seconds after an update.
const CommitDelay = 30 * time.Second
type entry struct {
key Key
state State
}
type shard struct {
mu sync.Mutex
cap int
ll *list.List
items map[Key]*list.Element
}
// Service is a set of independent LRU partitions.
type Service struct {
shards []*shard
store Store
now func() time.Time
}
// New builds partitions shards, each holding at most perShard Read States.
func New(store Store, shards, perShard int, now func() time.Time) *Service {
s := &Service{store: store, now: now}
for i := 0; i < shards; i++ {
s.shards = append(s.shards, &shard{cap: perShard, ll: list.New(), items: map[Key]*list.Element{}})
}
return s
}
func (s *Service) shardFor(k Key) *shard {
h := fnv.New64a()
var b [16]byte
for i := 0; i < 8; i++ {
b[i] = byte(k.UserID >> (8 * i))
b[8+i] = byte(k.ChannelID >> (8 * i))
}
_, _ = h.Write(b[:])
return s.shards[h.Sum64()%uint64(len(s.shards))]
}
// get returns the cached element, loading from the store on a miss and
// evicting (with a commit) when the partition is full. Caller holds sh.mu.
func (s *Service) get(sh *shard, k Key) (*list.Element, error) {
if el, ok := sh.items[k]; ok {
sh.ll.MoveToFront(el)
return el, nil
}
st, err := s.store.Load(k)
if err != nil {
return nil, err
}
el := sh.ll.PushFront(&entry{key: k, state: st})
sh.items[k] = el
if sh.ll.Len() > sh.cap {
old := sh.ll.Back()
e := old.Value.(*entry)
if !e.state.dirtySince.IsZero() {
if err := s.store.Commit(e.key, e.state); err != nil {
return nil, err
}
}
sh.ll.Remove(old)
delete(sh.items, e.key)
}
return el, nil
}
// Mention increments the mention counter (someone @mentioned the user).
func (s *Service) Mention(k Key) error {
sh := s.shardFor(k)
sh.mu.Lock()
defer sh.mu.Unlock()
el, err := s.get(sh, k)
if err != nil {
return err
}
e := el.Value.(*entry)
e.state.MentionCount++
s.markDirty(e)
return nil
}
// Ack marks the channel read up to messageID and resets the counter to 0.
func (s *Service) Ack(k Key, messageID int64) error {
sh := s.shardFor(k)
sh.mu.Lock()
defer sh.mu.Unlock()
el, err := s.get(sh, k)
if err != nil {
return err
}
e := el.Value.(*entry)
if messageID > e.state.LastReadMessageID {
e.state.LastReadMessageID = messageID
}
e.state.MentionCount = 0
s.markDirty(e)
return nil
}
func (s *Service) markDirty(e *entry) {
if e.state.dirtySince.IsZero() {
e.state.dirtySince = s.now()
}
}
// Get returns the current state (cache first).
func (s *Service) Get(k Key) (State, error) {
sh := s.shardFor(k)
sh.mu.Lock()
defer sh.mu.Unlock()
el, err := s.get(sh, k)
if err != nil {
return State{}, err
}
return el.Value.(*entry).state, nil
}
// FlushDue commits every entry that has been dirty for CommitDelay or more.
// A ticker calls it in production; tests call it with a fake clock.
// Many updates inside the window cost one database write.
func (s *Service) FlushDue() (int, error) {
n := 0
now := s.now()
for _, sh := range s.shards {
sh.mu.Lock()
for el := sh.ll.Front(); el != nil; el = el.Next() {
e := el.Value.(*entry)
if !e.state.dirtySince.IsZero() && now.Sub(e.state.dirtySince) >= CommitDelay {
st := e.state
st.dirtySince = time.Time{}
if err := s.store.Commit(e.key, st); err != nil {
sh.mu.Unlock()
return n, err
}
e.state.dirtySince = time.Time{}
n++
}
}
sh.mu.Unlock()
}
return n, nil
}package readstates
import (
"sync"
"testing"
"time"
)
type memStore struct {
mu sync.Mutex
data map[Key]State
loads int
commits int
}
func newMem() *memStore { return &memStore{data: map[Key]State{}} }
func (m *memStore) Load(k Key) (State, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.loads++
return m.data[k], nil
}
func (m *memStore) Commit(k Key, s State) error {
m.mu.Lock()
defer m.mu.Unlock()
m.commits++
m.data[k] = s
return nil
}
func TestManyUpdatesOneCommit(t *testing.T) {
now := time.Unix(0, 0)
db := newMem()
svc := New(db, 4, 100, func() time.Time { return now })
k := Key{UserID: 1, ChannelID: 42}
for i := 0; i < 500; i++ { // a busy channel with @mentions
if err := svc.Mention(k); err != nil {
t.Fatal(err)
}
}
if n, _ := svc.FlushDue(); n != 0 || db.commits != 0 {
t.Fatal("nothing may be committed before 30 s")
}
now = now.Add(CommitDelay)
if n, _ := svc.FlushDue(); n != 1 {
t.Fatalf("flushed %d, want 1", n)
}
if db.data[k].MentionCount != 500 || db.commits != 1 {
t.Fatalf("db=%+v commits=%d", db.data[k], db.commits)
}
}
func TestAckResetsAndIsMonotonic(t *testing.T) {
now := time.Unix(0, 0)
svc := New(newMem(), 1, 10, func() time.Time { return now })
k := Key{1, 2}
_ = svc.Mention(k)
_ = svc.Ack(k, 900)
_ = svc.Ack(k, 800) // a late, older ack from another device
st, _ := svc.Get(k)
if st.MentionCount != 0 || st.LastReadMessageID != 900 {
t.Fatalf("state = %+v", st)
}
}
func TestEvictionCommitsDirtyEntry(t *testing.T) {
now := time.Unix(0, 0)
db := newMem()
svc := New(db, 1, 2, func() time.Time { return now })
_ = svc.Mention(Key{1, 1})
_, _ = svc.Get(Key{1, 2})
_, _ = svc.Get(Key{1, 3}) // evicts {1,1}
if db.commits != 1 || db.data[Key{1, 1}].MentionCount != 1 {
t.Fatalf("evicted dirty entry not committed: commits=%d", db.commits)
}
}Request coalescing plus consistent-hash routing. A thousand concurrent readers of channel 42 cause one query; the first caller giving up does not cancel the shared query.
// Package coalesce re-implements, in Go, the two ideas Discord describes for
// its Rust data services ("How Discord Stores Trillions of Messages", 2023):
// request coalescing (one database query per hot row, many subscribers) and
// consistent-hash routing by channel ID so that coalescing can happen at all.
// It is a teaching re-implementation, not Discord's code.
package coalesce
import (
"context"
"hash/fnv"
"sort"
"strconv"
"sync"
)
// Fetch loads one key from the database.
type Fetch[V any] func(ctx context.Context, key string) (V, error)
type call[V any] struct {
done chan struct{}
val V
err error
subs int
}
// Group coalesces concurrent requests for the same key into one Fetch.
type Group[V any] struct {
mu sync.Mutex
inflight map[string]*call[V]
fetch Fetch[V]
}
// NewGroup returns a coalescing group around fetch.
func NewGroup[V any](fetch Fetch[V]) *Group[V] {
return &Group[V]{inflight: map[string]*call[V]{}, fetch: fetch}
}
// Get returns the value for key. The first caller starts a worker that runs
// the query; callers that arrive while it runs subscribe to its result.
// shared reports whether this caller rode on someone else's query.
func (g *Group[V]) Get(ctx context.Context, key string) (v V, shared bool, err error) {
g.mu.Lock()
if c, ok := g.inflight[key]; ok {
c.subs++
g.mu.Unlock()
select {
case <-c.done:
return c.val, true, c.err
case <-ctx.Done():
return v, true, ctx.Err()
}
}
c := &call[V]{done: make(chan struct{}), subs: 1}
g.inflight[key] = c
g.mu.Unlock()
// The worker uses a context detached from this caller: if the first
// caller gives up, the subscribers still get their answer.
go func() {
c.val, c.err = g.fetch(context.WithoutCancel(ctx), key)
g.mu.Lock()
delete(g.inflight, key)
g.mu.Unlock()
close(c.done)
}()
select {
case <-c.done:
return c.val, false, c.err
case <-ctx.Done():
return v, false, ctx.Err()
}
}
// Ring routes a routing key (for messages: the channel ID) to one instance,
// so that every request for the same channel lands where it can be coalesced.
type Ring struct {
points []uint32
owner map[uint32]string
}
// NewRing places each instance on the ring vnodes times.
func NewRing(instances []string, vnodes int) *Ring {
r := &Ring{owner: map[uint32]string{}}
for _, in := range instances {
for i := 0; i < vnodes; i++ {
p := hash(in + "#" + strconv.Itoa(i))
r.points = append(r.points, p)
r.owner[p] = in
}
}
sort.Slice(r.points, func(i, j int) bool { return r.points[i] < r.points[j] })
return r
}
// Lookup returns the instance that owns key.
func (r *Ring) Lookup(key string) string {
h := hash(key)
i := sort.Search(len(r.points), func(i int) bool { return r.points[i] >= h })
if i == len(r.points) {
i = 0
}
return r.owner[r.points[i]]
}
func hash(s string) uint32 {
f := fnv.New32a()
_, _ = f.Write([]byte(s))
return f.Sum32()
}package coalesce
import (
"context"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestHotRowQueriedOnce(t *testing.T) {
var queries atomic.Int64
release := make(chan struct{})
g := NewGroup(func(ctx context.Context, key string) (string, error) {
queries.Add(1)
<-release // simulate a slow read on a hot partition
return "message 42 in " + key, nil
})
const readers = 1000 // an @everyone announcement: everyone opens the channel
var wg sync.WaitGroup
var shared atomic.Int64
for i := 0; i < readers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
v, s, err := g.Get(context.Background(), "channel:42")
if err != nil || v != "message 42 in channel:42" {
t.Errorf("got %q, %v", v, err)
}
if s {
shared.Add(1)
}
}()
}
time.Sleep(50 * time.Millisecond) // let readers subscribe
close(release)
wg.Wait()
if q := queries.Load(); q != 1 {
t.Fatalf("database queried %d times, want 1", q)
}
if shared.Load() != readers-1 {
t.Fatalf("shared = %d, want %d", shared.Load(), readers-1)
}
}
func TestFirstCallerCancelDoesNotHurtSubscribers(t *testing.T) {
release := make(chan struct{})
g := NewGroup(func(ctx context.Context, key string) (int, error) {
<-release
return 7, ctx.Err()
})
ctx, cancel := context.WithCancel(context.Background())
go func() { _, _, _ = g.Get(ctx, "k") }()
time.Sleep(10 * time.Millisecond)
res := make(chan int, 1)
go func() {
v, _, err := g.Get(context.Background(), "k")
if err != nil {
t.Errorf("subscriber err: %v", err)
}
res <- v
}()
time.Sleep(10 * time.Millisecond)
cancel()
close(release)
if v := <-res; v != 7 {
t.Fatalf("subscriber got %d, want 7", v)
}
}
func TestRingIsStableAndSpreads(t *testing.T) {
r := NewRing([]string{"ds-a", "ds-b", "ds-c"}, 64)
if r.Lookup("channel:42") != r.Lookup("channel:42") {
t.Fatal("same key must route to same instance")
}
seen := map[string]int{}
for i := 0; i < 3000; i++ {
seen[r.Lookup("channel:"+strconv.Itoa(i))]++
}
if len(seen) != 3 {
t.Fatalf("keys reached %d instances, want 3", len(seen))
}
for in, n := range seen {
if n < 500 {
t.Fatalf("%s got only %d of 3000 keys", in, n)
}
}
}Snowflake IDs and 10-day buckets. Decodes with the documented formulas and lists the buckets to scan, newest first.
// Package snowflake re-implements the ID layout that Discord documents
// publicly (developer docs, "Snowflakes") and the 10-day message bucket
// described in "How Discord Stores Billions of Messages" (2017).
// It is a teaching re-implementation, not Discord's code.
package snowflake
import (
"errors"
"sync"
"time"
)
// Epoch is the Discord epoch: the first second of 2015, in Unix milliseconds.
const Epoch int64 = 1420070400000
// BucketSize is the time window per Cassandra/ScyllaDB partition (10 days).
const BucketSize = int64(10 * 24 * time.Hour / time.Millisecond)
const (
workerBits = 5
processBits = 5
incrementBits = 12
maxIncrement = 1<<incrementBits - 1
)
// ErrClockBackwards is returned when the wall clock moves behind the last ID.
var ErrClockBackwards = errors.New("snowflake: clock moved backwards")
// Generator produces unique, time-ordered IDs for one worker/process pair.
type Generator struct {
mu sync.Mutex
worker int64
process int64
lastMs int64
increment int64
now func() time.Time
}
// New returns a generator; worker and process are masked to 5 bits each.
func New(worker, process int64, now func() time.Time) *Generator {
if now == nil {
now = time.Now
}
return &Generator{worker: worker & 0x1F, process: process & 0x1F, now: now}
}
// Next returns the next ID. Within one millisecond up to 4096 IDs are issued;
// after that it waits for the next millisecond.
func (g *Generator) Next() (int64, error) {
g.mu.Lock()
defer g.mu.Unlock()
ms := g.now().UnixMilli() - Epoch
if ms < g.lastMs {
return 0, ErrClockBackwards
}
if ms == g.lastMs {
g.increment++
if g.increment > maxIncrement {
for ms <= g.lastMs {
time.Sleep(50 * time.Microsecond)
ms = g.now().UnixMilli() - Epoch
}
g.increment = 0
}
} else {
g.increment = 0
}
g.lastMs = ms
return ms<<(workerBits+processBits+incrementBits) |
g.worker<<(processBits+incrementBits) |
g.process<<incrementBits |
g.increment, nil
}
// Timestamp extracts Unix milliseconds: (id >> 22) + Epoch.
func Timestamp(id int64) int64 { return (id >> 22) + Epoch }
// FromTime builds the smallest ID for a moment, useful for before/after paging.
func FromTime(t time.Time) int64 { return (t.UnixMilli() - Epoch) << 22 }
// Bucket returns the 10-day partition bucket an ID belongs to.
func Bucket(id int64) int64 { return (id >> 22) / BucketSize }
// BucketsNewestFirst lists the buckets to scan for a channel, from the bucket
// of "now" back to the bucket of the channel's own ID (a channel is older
// than any message in it).
func BucketsNewestFirst(channelID int64, now time.Time) []int64 {
first := Bucket(channelID)
last := Bucket(FromTime(now))
out := make([]int64, 0, last-first+1)
for b := last; b >= first; b-- {
out = append(out, b)
}
return out
}package snowflake
import (
"testing"
"time"
)
func TestLayoutMatchesDocs(t *testing.T) {
// A sample ID, decoded with the documented formulas: 175928847299117063
// decodes to 2016-04-30 11:18:25.796 UTC.
const id int64 = 175928847299117063
got := time.UnixMilli(Timestamp(id)).UTC()
want := time.Date(2016, 4, 30, 11, 18, 25, 796_000_000, time.UTC)
if !got.Equal(want) {
t.Fatalf("timestamp = %v, want %v", got, want)
}
if w := (id & 0x3E0000) >> 17; w != 1 {
t.Fatalf("worker = %d, want 1", w)
}
if p := (id & 0x1F000) >> 12; p != 0 {
t.Fatalf("process = %d, want 0", p)
}
if inc := id & 0xFFF; inc != 7 {
t.Fatalf("increment = %d, want 7", inc)
}
}
func TestMonotonicWithinOneMillisecond(t *testing.T) {
fixed := time.UnixMilli(Epoch + 1000)
g := New(1, 2, func() time.Time { return fixed })
prev := int64(-1)
for i := 0; i < 4096; i++ {
id, err := g.Next()
if err != nil {
t.Fatal(err)
}
if id <= prev {
t.Fatalf("id %d not greater than %d", id, prev)
}
prev = id
}
}
func TestClockBackwards(t *testing.T) {
now := time.UnixMilli(Epoch + 5000)
g := New(0, 0, func() time.Time { return now })
if _, err := g.Next(); err != nil {
t.Fatal(err)
}
now = now.Add(-time.Millisecond)
if _, err := g.Next(); err != ErrClockBackwards {
t.Fatalf("err = %v, want ErrClockBackwards", err)
}
}
func TestBuckets(t *testing.T) {
start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
channel := FromTime(start)
now := start.Add(25 * 24 * time.Hour)
b := BucketsNewestFirst(channel, now)
if len(b) < 3 || len(b) > 4 {
t.Fatalf("got %d buckets for 25 days, want 3 or 4: %v", len(b), b)
}
if b[0] <= b[len(b)-1] {
t.Fatalf("buckets not newest first: %v", b)
}
if Bucket(FromTime(now)) != b[0] {
t.Fatal("first bucket must be the current one")
}
}Guild fan-out with relays, passive sessions and per-node batching. The test checks one send per node, a 90% cut from passive sessions, permission filtering and the quadratic growth numbers from the Maxjourney post.
// Package fanout models, in Go, the guild fan-out ideas Discord describes:
// one owner per guild that serialises every event (a GenServer in Elixir, a
// goroutine with a mailbox here), passive sessions that skip most events
// ("Maxjourney", 2023), relays that split fan-out work, and Manifold-style
// grouping so a sender makes one send per remote node, not one per session
// ("How Discord Scaled Elixir to 5,000,000 Concurrent Users", 2017).
// It is a teaching model, not Discord's code.
package fanout
import (
"sort"
"sync"
)
// Session is one connected client device.
type Session struct {
ID string
Node string // which session node holds it
Passive bool // has not opened this guild recently
CanSee func(channel string) bool
}
// Event is something that happened in the guild.
type Event struct {
Channel string
Kind string // MESSAGE_CREATE, TYPING_START, PRESENCE_UPDATE ...
Body string
}
// Delivery is one batch handed to one node: the Manifold idea.
type Delivery struct {
Node string
Sessions []string
Event Event
}
// Sender is the network: it receives one call per node per event.
type Sender interface {
SendToNode(d Delivery)
}
// Guild owns the member/session state of one community and processes one
// event at a time from its mailbox, which gives every recipient the same order.
type Guild struct {
mailbox chan Event
relays [][]*Session
perRelay int
sender Sender
wg sync.WaitGroup
}
// NewGuild splits sessions into relays of at most perRelay sessions
// (Discord's post reports up to 15,000 sessions per relay).
func NewGuild(sessions []*Session, perRelay int, sender Sender) *Guild {
g := &Guild{mailbox: make(chan Event, 1024), perRelay: perRelay, sender: sender}
for i := 0; i < len(sessions); i += perRelay {
end := min(i+perRelay, len(sessions))
g.relays = append(g.relays, sessions[i:end])
}
g.wg.Add(1)
go g.loop()
return g
}
// Publish enqueues an event; the guild goroutine handles it in order.
func (g *Guild) Publish(e Event) { g.mailbox <- e }
// Close drains the mailbox and stops the guild.
func (g *Guild) Close() { close(g.mailbox); g.wg.Wait() }
func (g *Guild) loop() {
defer g.wg.Done()
for e := range g.mailbox {
// Relays run in parallel; each does permission checks for its slice.
var rw sync.WaitGroup
for _, relay := range g.relays {
rw.Add(1)
go func(r []*Session) {
defer rw.Done()
for _, d := range Plan(r, e) {
g.sender.SendToNode(d)
}
}(relay)
}
rw.Wait()
}
}
// Plan decides who receives e and groups recipients by node.
// Passive sessions only get events marked as summary-worthy (none here);
// the client catches up when the user opens the guild.
func Plan(sessions []*Session, e Event) []Delivery {
byNode := map[string][]string{}
for _, s := range sessions {
if s.Passive {
continue
}
if s.CanSee != nil && !s.CanSee(e.Channel) {
continue
}
byNode[s.Node] = append(byNode[s.Node], s.ID)
}
nodes := make([]string, 0, len(byNode))
for n := range byNode {
nodes = append(nodes, n)
}
sort.Strings(nodes)
out := make([]Delivery, 0, len(nodes))
for _, n := range nodes {
out = append(out, Delivery{Node: n, Sessions: byNode[n], Event: e})
}
return out
}
// NotificationsFor is the post's back-of-envelope: if every online member
// sends one message, deliveries grow with the square of the online count.
func NotificationsFor(online int64) int64 { return online * online }package fanout
import (
"fmt"
"sync"
"testing"
)
type countingSender struct {
mu sync.Mutex
calls int
recipients int
}
func (c *countingSender) SendToNode(d Delivery) {
c.mu.Lock()
c.calls++
c.recipients += len(d.Sessions)
c.mu.Unlock()
}
func sessions(n, nodes int, passiveEvery int) []*Session {
out := make([]*Session, n)
for i := range out {
out[i] = &Session{
ID: fmt.Sprintf("s%d", i),
Node: fmt.Sprintf("node-%d", i%nodes),
Passive: passiveEvery > 0 && i%passiveEvery != 0,
}
}
return out
}
func TestOneSendPerNodeNotPerSession(t *testing.T) {
ss := sessions(30000, 10, 0)
d := Plan(ss, Event{Channel: "general", Kind: "MESSAGE_CREATE"})
if len(d) != 10 {
t.Fatalf("got %d node sends, want 10 (one per node)", len(d))
}
total := 0
for _, x := range d {
total += len(x.Sessions)
}
if total != 30000 {
t.Fatalf("recipients = %d, want 30000", total)
}
}
func TestPassiveSessionsCutWork(t *testing.T) {
// 9 of every 10 sessions passive, the ratio Discord reports for large guilds.
ss := sessions(10000, 4, 10)
d := Plan(ss, Event{Channel: "general"})
got := 0
for _, x := range d {
got += len(x.Sessions)
}
if got != 1000 {
t.Fatalf("active recipients = %d, want 1000", got)
}
}
func TestPermissionsFilter(t *testing.T) {
ss := sessions(100, 2, 0)
for i, s := range ss {
if i%2 == 0 {
s.CanSee = func(ch string) bool { return ch != "mods-only" }
}
}
d := Plan(ss, Event{Channel: "mods-only"})
got := 0
for _, x := range d {
got += len(x.Sessions)
}
if got != 50 {
t.Fatalf("recipients = %d, want 50", got)
}
}
func TestGuildWithRelaysDeliversInOrder(t *testing.T) {
c := &countingSender{}
g := NewGuild(sessions(45000, 5, 0), 15000, c)
for i := 0; i < 3; i++ {
g.Publish(Event{Channel: "general", Kind: "MESSAGE_CREATE", Body: fmt.Sprint(i)})
}
g.Close()
// 3 relays x 5 nodes x 3 events
if c.calls != 45 || c.recipients != 135000 {
t.Fatalf("calls=%d recipients=%d, want 45 and 135000", c.calls, c.recipients)
}
}
func TestQuadraticGrowth(t *testing.T) {
cases := map[int64]int64{1000: 1_000_000, 10000: 100_000_000, 100000: 10_000_000_000}
for online, want := range cases {
if got := NotificationsFor(online); got != want {
t.Fatalf("%d online: %d, want %d", online, got, want)
}
}
}Push pipeline with demand of 100 and a shedding buffer.
// Package pusher models the push pipeline Discord describes in "How Discord
// handles push request bursts of over a million per minute with Elixir's
// GenStage" (2016): a collector that buffers push requests with a fixed
// buffer size and sheds the overflow, and pushers that demand at most 100
// requests at a time because Firebase's XMPP connection allows no more than
// 100 pending requests. It is a teaching model, not Discord's code.
package pusher
import (
"context"
"sync"
"sync/atomic"
)
// MaxPending is the per-connection in-flight limit from the post.
const MaxPending = 100
// Push is one notification for one device.
type Push struct {
UserID int64
Title string
}
// Collector is the producer stage: a bounded buffer that sheds when full.
type Collector struct {
buf chan Push
shed atomic.Int64
}
// NewCollector returns a collector with bufferSize slots.
func NewCollector(bufferSize int) *Collector {
return &Collector{buf: make(chan Push, bufferSize)}
}
// Offer never blocks the caller: during a burst it drops instead of
// letting the whole system fall over.
func (c *Collector) Offer(p Push) bool {
select {
case c.buf <- p:
return true
default:
c.shed.Add(1)
return false
}
}
// Shed reports how many requests were dropped.
func (c *Collector) Shed() int64 { return c.shed.Load() }
// Close ends the stream once producers are done.
func (c *Collector) Close() { close(c.buf) }
// Provider is the push service connection (Firebase in the post).
type Provider interface {
Send(ctx context.Context, p Push) error
}
// RunPusher is the consumer stage. The semaphore is the "demand": it never
// has more than MaxPending requests in flight on its connection.
func RunPusher(ctx context.Context, c *Collector, prov Provider) {
sem := make(chan struct{}, MaxPending)
var wg sync.WaitGroup
for p := range c.buf {
select {
case sem <- struct{}{}:
case <-ctx.Done():
wg.Wait()
return
}
wg.Add(1)
go func(p Push) {
defer wg.Done()
defer func() { <-sem }()
_ = prov.Send(ctx, p) // retries and error handling omitted
}(p)
}
wg.Wait()
}package pusher
import (
"context"
"sync/atomic"
"testing"
"time"
)
type slowProvider struct {
inflight, peak, sent atomic.Int64
}
func (s *slowProvider) Send(ctx context.Context, p Push) error {
n := s.inflight.Add(1)
for {
old := s.peak.Load()
if n <= old || s.peak.CompareAndSwap(old, n) {
break
}
}
time.Sleep(2 * time.Millisecond) // waiting for the provider's ack
s.inflight.Add(-1)
s.sent.Add(1)
return nil
}
func TestNeverMoreThan100Pending(t *testing.T) {
c := NewCollector(5000)
prov := &slowProvider{}
done := make(chan struct{})
go func() { RunPusher(context.Background(), c, prov); close(done) }()
for i := 0; i < 2000; i++ {
c.Offer(Push{UserID: int64(i)})
}
c.Close()
<-done
if prov.peak.Load() > MaxPending {
t.Fatalf("peak in-flight %d > %d", prov.peak.Load(), MaxPending)
}
if prov.sent.Load()+c.Shed() != 2000 {
t.Fatalf("sent %d + shed %d != 2000", prov.sent.Load(), c.Shed())
}
}
func TestBurstIsShedNotQueuedForever(t *testing.T) {
c := NewCollector(10) // nobody consuming: a provider outage
accepted := 0
for i := 0; i < 1000; i++ {
if c.Offer(Push{UserID: int64(i)}) {
accepted++
}
}
if accepted != 10 || c.Shed() != 990 {
t.Fatalf("accepted=%d shed=%d", accepted, c.Shed())
}
}The Go angle
| Go feature | Use here | Note |
|---|---|---|
| Goroutine + channel mailbox | Guild "process" that handles one event at a time | Same ordering property as a GenServer, no supervision tree |
sync.Mutex per shard | Partitioned LRU | Discord's Go mitigation was partitioning, too |
container/list | LRU order | Pointer-heavy: exactly what made Go's GC scan expensive |
context.WithoutCancel (Go 1.21+) | Shared coalesced query survives the first caller | Subscribers keep their own deadlines |
golang.org/x/sync/singleflight | Production-grade coalescing | Prefer it over the hand-written Group |
Buffered channel + select default | Shedding collector | Non-blocking offer |
| Semaphore channel | At most 100 in flight | The "demand" of GenStage |
GOGC, GOMEMLIMIT, debug.SetGCPercent | GC tuning | Discord tried GC percent (2020); GOMEMLIMIT came later (Go 1.19) |
Laravel
Laravel is not what Discord runs; these files show how the same ideas look in a PHP application with Laravel 13 features (cache locks, unique queued jobs, broadcasting, the Redis facade).
Before
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
// Before: every channel open is a fresh database query, and every ack is a
// synchronous write. Ten thousand people opening the same announcement means
// ten thousand identical SELECTs against the same partition.
class ChannelMessagesController
{
public function index(Request $request, int $channelId): JsonResponse
{
$messages = DB::table('messages')
->where('channel_id', $channelId)
->orderByDesc('id')
->limit(50)
->get();
return response()->json($messages);
}
public function ack(Request $request, int $channelId, int $messageId): JsonResponse
{
DB::table('read_states')->updateOrInsert(
['user_id' => $request->user()->id, 'channel_id' => $channelId],
['last_read_message_id' => $messageId, 'mention_count' => 0],
);
return response()->json(['ok' => true]);
}
}After
Coalesced reads with Cache::lock()->block(). Workers that miss wait for the lock, then find the value the first worker stored. Reads scan buckets newest first.
<?php
namespace App\Services;
use App\Support\Snowflake;
use Illuminate\Contracts\Cache\LockTimeoutException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
// After: request coalescing across PHP workers. The first worker to miss
// takes an atomic lock and queries; the others wait on the lock and then
// read what it stored. This is the Laravel-shaped cousin of the Rust data
// service in "How Discord Stores Trillions of Messages", not a copy of it:
// Discord coalesces in memory inside one routed instance, here the cache
// store is the meeting point.
class CoalescedMessageReader
{
public function __construct(private int $ttlSeconds = 2)
{
}
public function latest(int $channelId, int $limit = 50): Collection
{
$key = "channel:{$channelId}:latest:{$limit}";
$cached = Cache::get($key);
if ($cached !== null) {
return collect($cached);
}
try {
return Cache::lock("lock:{$key}", 5)->block(3, function () use ($key, $channelId, $limit) {
// Re-check: a worker that held the lock before us filled it.
return collect(Cache::remember($key, $this->ttlSeconds, fn () => $this->query($channelId, $limit)));
});
} catch (LockTimeoutException) {
// Shed to the database rather than fail the user; alert on this.
return collect($this->query($channelId, $limit));
}
}
/** @return array<int, object> */
private function query(int $channelId, int $limit): array
{
$rows = [];
foreach (Snowflake::bucketsNewestFirst($channelId, now()) as $bucket) {
$page = DB::table('messages')
->where('channel_id', $channelId)
->where('bucket', $bucket)
->orderByDesc('message_id')
->limit($limit - count($rows))
->get()
->all();
$rows = array_merge($rows, $page);
if (count($rows) >= $limit) {
break;
}
}
return $rows;
}
}<?php
namespace App\Support;
use DateTimeInterface;
// Discord's documented snowflake layout and the 10-day message bucket from
// "How Discord Stores Billions of Messages". PHP ints are 64-bit, so the
// shifts are exact. A re-implementation for teaching, not Discord's code.
final class Snowflake
{
public const EPOCH_MS = 1420070400000;
public const BUCKET_MS = 10 * 24 * 60 * 60 * 1000;
public static function timestampMs(int $id): int
{
return ($id >> 22) + self::EPOCH_MS;
}
public static function fromTime(DateTimeInterface $at): int
{
$ms = (int) $at->format('Uv');
return ($ms - self::EPOCH_MS) << 22;
}
public static function bucket(int $id): int
{
return intdiv($id >> 22, self::BUCKET_MS);
}
/**
* Buckets to scan for the newest messages, newest first.
*
* @return list<int>
*/
public static function bucketsNewestFirst(int $channelId, DateTimeInterface $now): array
{
return range(self::bucket(self::fromTime($now)), self::bucket($channelId));
}
}Write-behind read states. The ack updates Redis and dispatches one delayed, unique commit job per user and channel.
<?php
namespace App\Http\Controllers;
use App\Jobs\CommitReadState;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
// After: acks and mentions touch Redis only; the database sees one write
// per (user, channel) per 30-second window.
class ReadStateController
{
public function ack(Request $request, int $channelId, int $messageId): JsonResponse
{
$userId = $request->user()->id;
$key = "read_state:{$userId}:{$channelId}";
// Monotonic: an older ack from a second device must not move it back.
$current = (int) Redis::hget($key, 'last_read_message_id');
if ($messageId > $current) {
Redis::hmset($key, ['last_read_message_id' => $messageId, 'mention_count' => 0]);
}
CommitReadState::dispatch($userId, $channelId)->delay(30);
return response()->json(['ok' => true]);
}
}<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
// Write-behind for read states: the hot counter lives in Redis, and at most
// one commit per (user, channel) is waiting in the queue. Dispatch it with
// ->delay(30) on every update; duplicates are dropped while one is pending,
// and unlocking before processing lets a later update schedule the next one.
#[UniqueFor(60)]
class CommitReadState implements ShouldQueue, ShouldBeUniqueUntilProcessing
{
use Queueable;
public function __construct(public int $userId, public int $channelId)
{
}
public function uniqueId(): string
{
return "{$this->userId}:{$this->channelId}";
}
public function handle(): void
{
$state = Redis::hgetall("read_state:{$this->userId}:{$this->channelId}");
if ($state === []) {
return;
}
DB::table('read_states')->upsert(
[[
'user_id' => $this->userId,
'channel_id' => $this->channelId,
'last_read_message_id' => (int) ($state['last_read_message_id'] ?? 0),
'mention_count' => (int) ($state['mention_count'] ?? 0),
]],
['user_id', 'channel_id'],
['last_read_message_id', 'mention_count'],
);
}
}Typing as an ephemeral broadcast.
<?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
// Typing is ephemeral: broadcast now (no queue), never store it, and accept
// that it may be dropped. With Laravel Reverb the cheaper option is a client
// event (Echo's whisper('typing', ...)), which never reaches the app at all.
class TypingStarted implements ShouldBroadcastNow
{
use Dispatchable;
use InteractsWithSockets;
public function __construct(public int $channelId, public int $userId)
{
}
/** @return array<int, PrivateChannel> */
public function broadcastOn(): array
{
return [new PrivateChannel("channel.{$this->channelId}")];
}
public function broadcastAs(): string
{
return 'TYPING_START';
}
}The Laravel angle
| Laravel 13 feature | Use here | Caveat |
|---|---|---|
Cache::lock($name, $seconds)->block($wait, $closure) | Cross-worker coalescing | Throws LockTimeoutException; needs a lock-capable store (Redis, database, Memcached...) |
Cache::remember | Fill once, reuse | A TTL cache alone still stampedes at expiry |
Cache::flexible($key, [fresh, stale], ...) | Stale-while-revalidate | Serves stale data; Discord's message path did not |
ShouldBeUniqueUntilProcessing + #[UniqueFor] | One pending commit per key | Unlocks before handle, so later updates schedule the next commit |
dispatch(...)->delay(30) | The 30-second deferred write | Delay support depends on the queue driver |
Redis facade dynamic commands (hget, hmset) | Hot counters | Commands go straight to Redis |
ShouldBroadcastNow | Typing without a queue hop | Uses the sync queue |
Echo whisper('typing', ...) / listenForWhisper | Client events that never hit the app | The broadcasting docs use typing as the example |
Laravel Reverb REVERB_SCALING_ENABLED=true | Horizontal WebSocket servers via Redis pub/sub | Above ~1,000 connections needs a non-stream_select event loop |
Solving the classic problems
Hot partition on a popular channel
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Bound partition size | ((channel_id, bucket), message_id) | Partitions stay under ~100 MB | Quiet channels scan several buckets |
| Request coalescing | One in-flight query per key | Removes duplicate reads at the source | Only concurrent identical requests |
| Affinity routing | Consistent hash on channel_id to one data-service instance | Makes coalescing effective | One instance carries a hot channel (inference) |
| Concurrency limit to the database | Bounded workers per partition (2023 goal) | Protects the cluster from unbounded concurrency | Requests wait |
| Engine without GC pauses | ScyllaDB | Fewer latency spikes | Migration project |
The schema Discord describes (CQL, which is SQL-like), with this page's names, and a PostgreSQL read-state table for the Laravel example:
-- CQL (ScyllaDB / Cassandra): simplified from Discord's 2017 and 2023 posts.
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);
-- Newest 50 in the current bucket; the application walks older buckets if needed.
SELECT * FROM messages WHERE channel_id = 42 AND bucket = 1035 LIMIT 50;
-- PostgreSQL: read states for the Laravel write-behind example.
CREATE TABLE read_states (
user_id bigint NOT NULL,
channel_id bigint NOT NULL,
last_read_message_id bigint NOT NULL DEFAULT 0,
mention_count integer NOT NULL DEFAULT 0,
PRIMARY KEY (user_id, channel_id)
);Tombstone scans after mass deletes
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Shorter tombstone lifetime | 10 days to 2 days (repairs run nightly) | Less to scan | Unsafe if repairs stop |
| Track empty buckets | Skip buckets known to be empty | Worst case is one bucket | Extra metadata |
| Never write nulls | Write only set columns | 12 fewer tombstones per message | Application discipline |
Latency spikes from garbage collection
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Smaller heaps per process | Partitioned caches (Go), relays and ETS (Elixir) | Smaller pauses | More misses or more processes |
| No collector | Rust (Read States), ScyllaDB (C++) | No GC pauses | Rewrite |
| Tune the collector | min_bin_vheap_size on the BEAM | Cheap | Needs deep tracing to find |
Reconnect thundering herd
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Jittered first heartbeat | heartbeat_interval * jitter | Spreads reconnects | Slower average reconnect |
| Session resume | resume_gateway_url, last sequence | No full READY payload | State must survive |
| Start-session rate limit | Re-tuned per deployment shape | Backpressure at the gateway | Stale limits fail (2026) |
| Drain before scale-down | Admission webhook rejects updates until handoff | No mass session loss | Slower deploys |
Retry storm against an overloaded dependency
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Fail fast with a semaphore | Bound outstanding calls; reject the rest | No unbounded queues | Some requests rejected |
| Shed optional work | Turn off typing and read markers | Restores core function | Degraded UX |
| Circuit breaking in the API | Automatic demand reduction (2026 mention) | Protects databases | Must avoid "nothing gets through" states |
| Capacity headroom | Double small critical clusters | Room for a zone plus a node | Cost |
Bulk operations that span many nodes
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Batch by destination | One batch per (cluster, index) | One failed node fails one batch | More, smaller batches |
| Durable queue | Pub/Sub instead of Redis lists | No dropped messages under backlog | Managed-service dependency |
| Cells | Many small clusters | Smaller blast radius, cheaper master nodes | More clusters to run |
What you can copy
This is the section to reuse in your own designs: each Discord subsystem, the generic pattern behind it, and the chapter on this site that teaches the pattern.
| Discord subsystem | Generic pattern | Chapter to read |
|---|---|---|
| Gateway WebSockets, heartbeats, resume | Persistent connections, reconnect with jitter | Real-Time Communication |
| Guild process fan-out | Fan-out on write to online subscribers | Feeds: Fan-Out |
| Placement on a hash ring | Consistent hashing | Consistent Hashing |
| Message partitions and buckets | Partition key design, hot partitions | Sharding at System Level |
| Cassandra and ScyllaDB | Wide-column storage | Cassandra & ScyllaDB in Depth |
| Snowflake IDs | Time-ordered IDs | ID Generation at Scale |
| Request coalescing | Single-flight, batching | Write Buffering & Coalescing |
| Read states cache | Write-behind caching | Caching |
| Push pipeline | Backpressure, load shedding | Backpressure, Load Shedding |
| Voice SFU over UDP | UDP media, regional placement | TCP & UDP, Latency Budgets |
| Search cells | Search architecture | Search Systems |
| MongoDB to Cassandra to ScyllaDB with dual writes | Safe migrations | Strangler Fig |
| Incidents | Cascades, retries, breakers | Cascading Failures |
| Kubernetes deployments | Containers, graceful termination | Containers & Kubernetes |
| Dagster + dbt | Batch data platform | Big Data Architectures |
Choosing
| Your situation | Do what Discord did? | Extra technique | Reason |
|---|---|---|---|
| Chat with small groups (under ~100 per room) | No relays, no passive sessions | Plain pub/sub (Redis, Laravel Reverb) | Fan-out is cheap at that size (inference) |
| Rooms with tens of thousands online | Yes: per-node batching, passive subscribers | Summaries for idle members | Work grows with the square of online members |
| Append-heavy, read-recent history | Partition by (conversation, time bucket) | Snowflake or ULID IDs | Bounded partitions, contiguous reads |
| Many identical reads at the same instant | Coalescing with affinity routing | Short-TTL cache in front | Removes the stampede at the source |
| Long-lived big in-memory heap with tail SLO | Measure GC first; consider partitioning or a no-GC runtime | GOMEMLIMIT, off-heap stores | Discord's spikes came from heap scanning |
| Group voice over about 4 people | SFU, client-server | Regional placement by participants | P2P mesh cost grows with participants |
| Search is a minor feature | Lazy indexing, bulk ingest | Refresh on demand | Keeps search cheaper than storage |
| Notifications in bursts | Bounded demand, shedding buffer | Collapse duplicate notifications (inference) | Recovery beats completeness |
| Small, critical database cluster | Extra headroom, careful zonal operations | Check cache hit rate before proceeding | 2023 outage |
| Large stateful services on Kubernetes | Drain-before-terminate checks | Admission webhook | 2026 outage |
In architecture: from a single process to a distributed system
Discord's own path is the best illustration: it started as one product on one database and grew each part only when a number forced it.
Monolith: one process, one database
Discord's first version was built "in just under two months" with everything in one MongoDB replica set, but "planned everything for easy migration" (2017). The monolith equivalent today: a Laravel app with a messages table keyed by (channel_id, id), Reverb for WebSockets, Redis for presence and typing, a queue for push. Inference: this is enough for thousands of concurrent users; do not start with data services.
Modular monolith: boundaries without the network
The HTTP API is still one Python codebase in 2026, organised by feature groups with owners and tiers, and deployed as several hundred Kubernetes deployments that each take a slice of traffic or background tasks. The 2017 search design deliberately shipped a library instead of a microservice: "if it did need to be moved to it's own service, it could easily be wrapped in an RPC layer". Example: a chat module (messaging tier S, typing tier E) whose typing endpoint can be deployed and shed separately without a separate codebase.
Microservices: what crosses the boundary
The services that are separate exist for runtime reasons: Elixir for millions of long-lived connections, Rust data services to control database concurrency, the Rust authentication service, voice signalling and SFUs. A multi-service flow (assembled from posts; order is inference): POST /messages in the Python API, gRPC to a data service (routing key = channel_id), insert into ScyllaDB, publish to the guild process, Manifold to session nodes, a push request for offline users, a Pub/Sub message for the search indexer. Each hop has its own failure policy, and the 2023 and 2026 incidents show what happens when one hop's retries or reconnects are not bounded.
Distributed data: replicas, caches, sharded stores, regions
Messages are replicated three times across three zones with quorum reads and writes; that tolerates one zone, not one zone plus a degraded node (2023). Search keeps only the inverted index and reads bodies from the primary store, so search results are eventually consistent with edits and deletes (inference from the 2017 design). Shard maps live in Cassandra with a Redis cache (2017); edge voice hosts register in Valkey with a ten-minute TTL (2026). Voice placement picks one SFU host per call, so a call is as good as the network path from every participant to that one host.
Scaling path: 1x, 10x, 100x
| Scale | What Discord's history suggests | Source or status |
|---|---|---|
| 1x (launch) | One database, one app, one region | 2015 MongoDB |
| 10x | Move the biggest table to a store that scales by adding nodes; bucket partitions | 2016-2017 Cassandra |
| 10x | Make fan-out cheaper: per-node batching, copy-free shared data, semaphores | 2017 Elixir |
| 100x | Split big rooms (relays), do less (passive sessions), move hot structures to native code | 2019, 2023 |
| 100x | Protect the database with a data-service layer; then change engines | 2022-2023 |
| 100x | Cells for search; Kubernetes for operability; edge PoPs for voice | 2025-2026 |
Lab
The Go part is single-process and was run for this page; the outputs below are real. The Laravel part needs a Laravel 13 app with Redis and a queue worker: expected, not run.
Setup.
cd docs/snippets/system-design/case-study-discord/go
go vet ./... && go test ./...ok academy/case-study-discord/before
ok academy/case-study-discord/coalesce
ok academy/case-study-discord/fanout
ok academy/case-study-discord/pusher
ok academy/case-study-discord/readstates
ok academy/case-study-discord/snowflake- The cost of the naive read state. Run
go test -v -run EveryEvent ./before/. 500 mentions, one ack and one read cost 1,002 database round trips. Then rungo test -v -run ManyUpdates ./readstates/: the same 500 mentions become exactly one commit after the 30-second window. - A hot channel, coalesced. Run
go test -v -run HotRow ./coalesce/: 1,000 concurrent readers, one query, 999 shared results. Change the test so readers use 1,000 different keys and watch the query count rise to 1,000: coalescing only helps identical concurrent requests. - Routing is what makes coalescing work. In
TestRingIsStableAndSpreads, the same channel always maps to one instance and 3,000 channels spread across all three. Thought experiment: round-robin instead and each instance would coalesce only its own share. - Passive sessions.
go test -v -run Passive ./fanout/delivers to 1,000 of 10,000 sessions when 90% are passive;TestOneSendPerNodeNotPerSessionshows 30,000 recipients reached with 10 node sends. - Shedding instead of collapsing.
go test -v -run Burst ./pusher/accepts 10 and sheds 990 when nobody consumes;TestNeverMoreThan100Pendingnever exceeds 100 in flight. - Laravel coalescing (expected, not run). With Redis as the cache store, fire 200 concurrent requests at a route that calls
CoalescedMessageReader::latest(42)(for examplehey -n 200 -c 200 http://127.0.0.1:8000/channels/42/messages) while query logging is on:
# expected, not run
[query] select * from "messages" where "channel_id" = 42 and "bucket" = ... order by "message_id" desc limit 50
# one query per bucket scanned, once; 199 requests served from the cache after waiting on the lockCommon misconceptions
| Belief | Reality |
|---|---|
| Discord rewrote its backend in Rust | The API is Python (2026); real time is Elixir; Rust powers selected hot paths |
| ScyllaDB removed hot partitions | Discord says hot partitions can still happen; coalescing and routing do the protecting |
| Go is unsuitable for low latency | The 2020 issue was GC scanning a huge LRU on Go 1.9-era runtimes; the lesson is about heap shape |
| Voice is peer-to-peer | All media goes through Discord's SFUs, for scale, IP privacy and moderation |
| Search indexes every message immediately | Indexing is lazy (first search) and in bulk; search freshness is traded for cost |
| Every push notification is delivered | Under extreme bursts some are shed by design |
| Three zones with quorum survive any single problem | One zone down plus one degraded node broke quorum performance in 2023 |
| More shards always make search faster | Discord uses one primary shard per index except for Big Freaking Guilds |
| One process per guild cannot scale | It scales with relays, passive sessions and offloaded workers; the single process stays for full-view state |
| Typing and presence are as important as messages | They are the first features switched off under load |
Cheat sheet
| Topic | Remember |
|---|---|
| Core idea | "most of it boils down to pub/sub" (2017) |
| Processes | One GenServer per session, one per guild; consistent-hash placement |
| Manifold | One send per remote node; partitioner hashes PIDs per core |
| FastGlobal | Constant-pool shared data: 0.33 µs vs 7.64 µs ETS (README) |
| Large guilds | Relays of up to 15,000 sessions; ~90% passive sessions |
| Message key | ((channel_id, bucket), message_id), 10-day buckets |
| Storage history | MongoDB (2015), Cassandra 12 to 177 nodes, ScyllaDB 72 nodes (May 2022) |
| Data services | Rust, gRPC per query, request coalescing, routing by channel ID |
| Read states | One per user per channel; LRU; commit on eviction and after 30 s; Go to Rust for GC spikes |
| Voice | WebRTC clients, C++ SFU (2018), voice server per guild, etcd discovery; edge PoPs (2026) |
| Search | Elasticsearch, lazy, bulk; refresh on demand; cells, Pub/Sub, BFG multi-shard (2025) |
| Push | GenStage, demand 100 (Firebase XMPP limit), shedding buffer |
| Gateway knobs | Heartbeat with jitter, resume, 120 events/60 s, zlib-stream or zstd-stream |
| Incidents | 2023 auth: zonal upgrade + degraded disk + retry storm; 2026 voice: scale-down without handoff |
| Inference rule | Anything not in a Discord post is marked inference |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why did Discord bucket messages by time when Cassandra allows 2 GB partitions? Must-know
Answer
Answer: Partitions over about 100 MB caused GC pressure during compaction and cluster expansion and could not be spread across nodes; a channel can live for years. A 10-day bucket derived from the Snowflake keeps partitions bounded. See Message storage.
2 — What problem does request coalescing solve that a TTL cache does not, and why does it need routing? Important
Answer
Answer: It merges identical requests that are in flight at the same moment, so a stampede after an announcement costs one read with no stale data. Without consistent-hash routing by channel ID, identical requests land on different instances and each makes its own query. See Data services.
3 — The Read States service in Go was fast on average. What exactly was wrong, and what did the Go-side mitigation cost? Important
Answer
Answer: Every two minutes Go forced a GC that scanned the whole LRU of tens of millions of entries, causing latency spikes. Smaller partitioned caches reduced spikes but raised p99 because more lookups missed and went to the database. See Read states.
4 — What do Manifold and FastGlobal each optimise? Good to know
Answer
Answer: Manifold reduces fan-out cost by sending once per remote node instead of once per PID. FastGlobal makes large, rarely-changing shared data (the hash ring) readable without copying, using the BEAM constant pool. See Real-time gateway.
5 — Give two reasons Discord routes voice through its own servers rather than peer-to-peer. Must-know
Answer
Answer: Cost grows prohibitively with participants in P2P; routing through servers keeps users' IP addresses private (DDoS protection) and allows moderation such as server mute. See Voice.
6 — Why did a single Elasticsearch node failure fail about 40% of bulk index operations, and how was it fixed? Important
Answer
Answer: A 50-message batch spread across up to 50 nodes, so one failed node was likely to be in many batches and the whole batch failed. The 2025 router groups messages by destination cluster and index before bulk indexing. See Search.
7 — During the 2023 authentication outage, what did engineers switch off first, and why those features? Important
Answer
Answer: Sending typing events and marking messages as read: both generate heavy authenticated traffic and are safe to lose temporarily. It restored about half of users. See Presence and typing and Reliability.
8 — What are passive sessions and how much did they save? Good to know
Answer
Answer: User-guild connections for guilds the user is not looking at; they get periodic updates instead of every event. About 90% of connections in large guilds were passive, cutting fan-out work by about 90%; PASSIVE_UPDATE_V2 then cut their bandwidth from 35% to 5% of gateway traffic. See Large guilds.
9 — Name the trigger and the amplifier of the March 2026 voice outage. Good to know
Answer
Answer: Trigger: a Kubernetes change scaled session pods down before they could hand off, stopping 17% of sessions. Amplifier: mass reconnects and call re-creation flooded a single supervisor process in the voice syncers' connection pool, which also blocked etcd registration. See Reliability.
10 — In an interview, which statements about Discord must you label as inference? Important
Answer
Answer: Anything not in Discord's own posts or docs: estimated message sizes and peak factors, the exact order of steps in the send path, whether a component was rewritten, how internal client limits compare to the bot limits. See the evidence rule at the top.
Glossary
| Term | Meaning |
|---|---|
| Discord | Chat, voice and community platform; "servers" are called guilds internally |
| Guild | Internal name for a Discord server; one Elixir process routes its events |
| Elixir | Functional language on the Erlang VM; Discord's real-time core |
| Erlang | Language and runtime (OTP) Elixir builds on |
| BEAM | The Erlang virtual machine: lightweight processes, per-process heaps and GC |
| GenServer | Generic server process in Elixir/OTP; handles one mailbox message at a time |
| WebSocket gateway | Discord's ingress/egress service for all client WebSocket traffic |
| Session (process) | One process per connected device; forwards events to its WebSocket |
| Manifold | Discord library: groups PIDs by node so a send happens once per node |
| FastGlobal | Discord library: shared read-only data via the BEAM constant pool |
| Semaphore (library) | Discord library: bounded concurrency using :ets.update_counter/4 |
| ETS | Erlang Term Storage: in-memory tables shared by processes |
| NIF | Native Implemented Function: C or Rust code called from the BEAM |
| Relay | Process between guild and sessions doing fan-out for up to 15,000 sessions |
| Passive session | User-guild connection that gets only periodic summaries |
| Concurrent users | Users connected at the same moment (5M in 2017, 11M in 2019 title) |
| Voice | Discord audio calls; voice servers per guild, SFU media relay |
| WebRTC | W3C/IETF real-time audio, video and networking standards used by Discord clients |
| SFU | Selective forwarding unit: forwards media streams without mixing |
| Voice syncers | Elixir service that places calls on SFUs and sends them RPCs (2026) |
| Rust | Systems language without a GC; used for data services, Read States, NIFs |
| Message storage | The messages cluster: MongoDB, then Cassandra, then ScyllaDB |
| MongoDB | Discord's first database (2015) |
| Cassandra | Wide-column database Discord used for messages from ~2016 to 2022 |
| ScyllaDB | Cassandra-compatible C++ database, shard-per-core, no GC |
| Data service | Discord's Rust gRPC layer between the API and ScyllaDB |
| Request coalescing | Merging concurrent identical requests into one backend query |
| Hot partition | A partition receiving so much traffic its nodes slow everyone down |
| Read states | Per user per channel read position and mention counters |
| GC latency | Latency added by garbage-collection pauses or scans |
| Go to Rust | The 2020 Read States rewrite that removed GC spikes |
| Elasticsearch | Search engine Discord uses for message search |
| Message search | Discord's full-text search over messages, indexed lazily |
| Cell | Group of smaller Elasticsearch clusters for one dimension (guilds, DMs, BFGs) |
| Presence | Online status and activity, fanned out by guilds |
| Typing indicator | Ephemeral TYPING_START event; first to be shed under load |
| Push notifications | Mobile pushes for inactive users through Firebase |
| GenStage | Elixir behaviour for producer/consumer stages with demand-based backpressure |
| Kubernetes | Container orchestrator for Discord's API and, increasingly, Elixir services |
| Data orchestration | Scheduling and dependency management of data pipelines (Dagster) |
| Snowflake | 64-bit time-ordered ID: 42-bit timestamp, worker, process, increment |
| Incident | Production outage; Discord publishes postmortems on its blog |
| Inference | A statement on this page not taken from Discord's own sources |
References
Discord engineering blog (all fetched and read; HTTP 200):
- Stanislav Vishnevskiy, "How Discord Stores Billions of Messages", 13 January 2017
- Jake Heinz, "How Discord Indexes Billions of Messages", 16 March 2017
- Stanislav Vishnevskiy, "How Discord Scaled Elixir to 5,000,000 Concurrent Users", 6 July 2017
- Jesse Howarth, "How Discord handles push request bursts of over a million per minute with Elixir's GenStage", 12 December 2016
- Jozsef Vass, "How Discord Handles Two and Half Million Concurrent Voice Users using WebRTC", 10 September 2018
- Matt Nowack, "Using Rust to Scale Elixir for 11 Million Concurrent Users", 17 May 2019
- Jesse Howarth, "Why Discord is switching from Go to Rust", 4 February 2020
- Glen Oakley, "How Discord Supercharges Network Disks for Extreme Low Latency", 15 August 2022
- Bo Ingram, "How Discord Stores Trillions of Messages", 6 March 2023
- Yuliy Pisetsky, "Maxjourney: Pushing Discord's Limits with a Million+ Online Users in a Single Server", 25 October 2023
- Mark Smith, "25% or 6 to 4: The 11/6/23 Authentication Outage", 15 November 2023
- Zach Bluhm, "How Discord Uses Open-Source Tools for Scalable Data Orchestration & Transformation", 12 July 2024
- Austin Whyte, "How Discord Reduced Websocket Traffic by 40%", 20 September 2024
- Vicki Niu, "How Discord Indexes Trillions of Messages", 24 April 2025
- Bo Ingram and Stephen Birarda, "You've Got (Too Much) Mail: Behind the Scenes of the 3/25/26 Voice Outage", 29 April 2026
- Peter French, "How Discord Automates ScyllaDB Clusters at Scale", 8 May 2026
- David Chen, "How We Moved Discord Voice to the Edge", 9 June 2026
- Jim Benton, "Cost Attribution in Discord's API", 30 June 2026
- Engineering category index: discord.com/category/engineering
Discord open source and documentation:
- discord/manifold, discord/fastglobal, discord/sorted_set_nif (READMEs)
- Discord developer documentation source: Gateway, Reference (Snowflakes), Opcodes and Status Codes, Rate Limits
Framework documentation used for the Laravel code:
- Laravel 13: Cache, Queues, Broadcasting, Reverb, Redis