Skip to content

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 forGo to
The whole system in three tablesEverything in one minute
Why Discord is worth studying, and the main trade-offWhy it exists
What changed over time, post by postWhere it comes from
Step 1 and 2: requirements and numbersScope, Estimate
Step 3: the high-level pictureHigh-level design
Gateway, sessions, guilds, Manifold, FastGlobalReal-time gateway
Million-member servers, relays, passive sessionsLarge guilds
MongoDB to Cassandra to ScyllaDBMessage storage
Hot partitions and request coalescingData services
Read states, GC latency, Go to RustRead states
WebRTC, SFU, voice servers, the edgeVoice and video
Elasticsearch, lazy indexing, cellsSearch
Presence and typing indicatorsPresence and typing
Push notifications and GenStagePush
Python API, Rust, KubernetesAPI and infrastructure
Dagster, dbt, BigQueryData platform
Outages and what they taughtReliability and incidents
Gateway opcodes, close codes, rate limits, knobsMechanics
CodeGo, Laravel
Classic failures and their fixesSolving the classic problems
Which generic chapter each subsystem maps toWhat you can copy
Decision tableChoosing
Monolith to distributed systemIn architecture
Run the models yourselfLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Subsystems and what Discord says it built.

SubsystemWhat Discord builtFirst public sourceGeneric pattern
Real-time gatewayElixir WebSocket gateway; one GenServer per session and one per guild2017 Elixir postPub/sub fan-out over persistent connections
Large guildsRelays (up to 15,000 sessions each), passive sessions, Rust NIF sorted set2019, 2023 postsSplit fan-out, do less work
Message storageMongoDB, then Cassandra, then ScyllaDB; key ((channel_id, bucket), message_id)2017, 2023 postsPartition by access pattern, bound partition size
Hot partitionsRust data services with request coalescing and consistent-hash routing2023 postSingle-flight plus affinity routing
Read statesLRU cache in front of Cassandra; rewritten from Go to Rust2020 postWrite-behind cache; pick a runtime for the tail
Voice and videoWebRTC clients, in-house C++ SFU, voice servers per region, later edge PoPs2018, 2026 postsSelective forwarding unit, client-initiated failover
SearchElasticsearch, application-level sharding, lazy indexing; later cells on Kubernetes2017, 2025 postsIndex lazily, batch by destination, cells
PushGenStage producer/consumer with demand of 100 and a shedding buffer2016 postBackpressure plus load shedding
APIPython codebase, over 1,700 endpoints, several hundred Kubernetes deployments2026 postModular monolith deployed many ways
Data platformDerived, replaced by Dagster + dbt on BigQuery2024 postDeclarative orchestration

Numbers Discord published (with the year they were true).

NumberValueYearSource post
Concurrent usersNearly 5 million2017Scaled Elixir to 5,000,000
Concurrent users11 million (title)2019Rust to scale Elixir
Messages per dayWell past 120 million2017Stores billions
Concurrent voice usersMore than 2.6 million, 220 Gbps, 120 Mpps egress2018Voice with WebRTC
Cassandra nodes for messages12 (2017), 177 (early 2022)2017, 2023Stores billions / trillions
ScyllaDB nodes after migration72, 9 TB disk each2022Stores trillions
Historical-fetch p9940-125 ms on Cassandra, 15 ms on ScyllaDB2022Stores trillions
Largest guildMidjourney: over 10 million members, over 1 million online2023Maxjourney
Search26 billion documents (2017); trillions of messages, 40 clusters (2025)2017, 2025Indexes billions / trillions
SFU instancesMore than 25,00020263/25/26 voice outage

The decisions in one line each.

DecisionOne-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 foreverUsers come back on any device and expect history (2017)
Cassandra over MongoDBLinear scalability, automatic failover, predictable performance, open source (2017)
ScyllaDB over CassandraNo garbage collector, shard-per-core isolation, faster repairs (2023)
A data-service layerControl concurrency to hot partitions; coalesce identical reads (2023)
Rust for Read StatesGo's GC caused latency spikes every ~2 minutes (2020)
Own SFU, no ICE, client-server voiceLarge calls, IP privacy, DDoS protection, moderation (2018)
Lazy search indexingNot everyone searches; index only on first search (2017)
Drop some push notificationsBetter 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 nowPush less, or later
Every session gets every event it may seePassive sessions get periodic deltas only
Simple client, simple mental modelClient must catch up when the user opens the guild
Work grows with online members squared per guildWork grows with active members
Typing, presence, read markers all real timeTyping and read markers can be switched off under load
Search sees messages within a secondSearch 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 ​

  1. "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.
  2. "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.
  3. "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.

DatePostWhat changed
Early 2015Stores billions (2017)Original Discord built "in just under two months"; everything in one MongoDB replica set
Nov 2015Stores billions100 million stored messages; data and index no longer fit in RAM
~2016Stores billionsMessages move to Cassandra after a dark launch with double reads/writes; MongoDB phased out "within a week"
Summer 2016Push with GenStage (Dec 2016)Push notifications choke on bursts; rebuilt with GenStage and Firebase XMPP
Jan 2017Stores billions12-node Cassandra cluster, RF 3, over 120 million messages a day
Jan 2017Indexes billions (Mar 2017)Search launches on Elasticsearch with lazy indexing
Jul 2017Scaled ElixirNearly 5 million concurrent users; Manifold, FastGlobal and Semaphore released
Late 2017Reduced websocket traffic (2024)Gateway connections compressed with zlib
Sep 2018Voice with WebRTC850+ voice servers, 13 regions, 2.6 million concurrent voice users
May 2019Rust to scale ElixirMember list sorted set rewritten as a Rust NIF; Read States port to Rust completed
Feb 2020Go to RustRead States in Rust removes GC spikes; cache raised to 8 million Read States
By 2020Stores trillions (2023)Every database except cassandra-messages migrated to ScyllaDB
Aug 2022Network disks"Super-disk": Local SSD mirrored with Persistent Disk via RAID
May 2022Stores trillionsMessages switch to ScyllaDB; 177 Cassandra nodes become 72 ScyllaDB nodes
Oct 2023MaxjourneyRelays, passive sessions, worker processes with ETS for a 1M-online guild
Nov 2023Authentication outage50-minute outage during a zonal ScyllaDB OS upgrade
Apr 2024Reduced websocket trafficzstd streaming rolled out; passive sessions v2 in late May; ~40% less gateway bandwidth
Jul 2024Data orchestrationIn-house Derived replaced by Dagster + dbt
Apr 2025Indexes trillionsSearch moved to Elasticsearch cells on Kubernetes, Pub/Sub queue
Feb 2025 onwardVoice to the edge (2026)Voice and video moved onto Cloudflare PoPs; over 80% of traffic there by 2026
Mar 2026Voice outage (Apr 2026)Session pods scaled down without handoff; voice syncers overwhelmed
Jun 2026Cost attributionPython API: 1,700+ endpoints, ~700 background tasks, several hundred Kubernetes deployments
2015Nov 20152016-2017early 2022May 2022MongoDBone replica set(channel_id, created_at)100M messagesindex out of RAMlatency unpredictableCassandra12 nodes, RF 3writes sub-ms, reads <5 ms177 Cassandra nodeshot partitions, GC pausescompaction backlog72 ScyllaDB nodesRust data serviceshistory p99 15 msPartition design kept across both migrationsPRIMARY KEY ((channel_id, bucket), message_id)bucket = 10-day window derived from the Snowflake; message_id clusters newest-firstDates and numbers from Discord's 2017 and 2023 message-storage posts

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.

RequirementDiscord's words or factSource
Keep all history"store all chat history forever"Stores billions, 2017
Read/write mixReads "extremely random", read/write ratio "about 50/50"Stores billions, 2017
Latency targetAlert when API p95 goes above 80 msStores billions, 2017
No message cacheDid not want to cache messages in Redis or MemcachedStores billions, 2017
Real-time orderingClients "depend on linearizability of events"Scaled Elixir, 2017
Multiparty voiceEvery call multiparty; 1,000 people taking turns seenVoice, 2018
Search is an accessorySearch "shouldn't cost more than the actual storage of messages"Indexes billions, 2017
Self-healingSmall team, no dedicated devopsStores billions, Indexes billions
text
     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 rendering

Real 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.

QuantityValueStatus
Messages per day (2017)120 millionPublished
Average write rate120,000,000 / 86,400 ≈ 1,400 per secondInference (arithmetic)
Peak write rate≈ 4,200 per second at an assumed 3x peak factorInference (assumed factor)
Bytes per stored message~1 KB with metadataInference (assumption, not published)
Daily new storage (2017)~120 GB before replication, ~360 GB at RF 3Inference
Sessions per Erlang VMUp to 500,000 live sessionsPublished (2017)
Guilds per average user5Published (2017)
Fan-out, one message, 1M online guild1,000,000 deliveries; ~100,000 if 90% are passiveInference from published ratio
Relays for 1M active sessions1,000,000 / 15,000 ≈ 67Inference from published limit
Migration speedUp to 3.2 million messages per secondPublished (2023)
text
     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.

Clientsdesktop, web,iOS, AndroidGatewayElixir, WebSocket, zstdSessionsone GenServer per deviceGuild + relaysone GenServer per guildAPIPython, KubernetesData servicesRust, gRPC, coalescingScyllaDBmessages, users, authPub/Sub queueindex workers (Rust router)Elasticsearch cellsguild + user-DM cellsVoice SFU fleetUDP media, edge PoPsVoice syncersElixir, place callsPush pipelinecollector, pushers, FCMSolid: request path. Dashed: guild-originated work (voice state to syncers, offline users to push).
text
     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 later

Real 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).

text
     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)FixMeasured effect
Fan-out send costManifold: one send per remote nodePackets/sec dropped by half (README)
Ring lookup hot pathETS (7 µs) then FastGlobal constant pool (0.3 µs)17.5 s to 750 ms per node restart
Registry stampedeSemaphore on :ets.update_counter/4Sessions "did not even budge" in a later presence crash
Large messages to many nodesManifold pack_mode: :binary encodes once (README)Fewer ETF encodings
Sender busyManifold 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).

text
     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 firehose

Real 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:

TechniqueSourceEffect reported
Passive sessionsMaxjourney 2023Fan-out work about 90% cheaper in large servers
RelaysMaxjourney 2023Guilds in the hundreds of thousands of members
Members in ETS + worker processesMaxjourney 2023Expensive scans off the guild's hot loop
Member list SortedSet as a Rust NIFRust to scale Elixir 2019Worst case 3.68 µs at 1,000,000 items vs 640 µs pure Elixir at 250,000
PASSIVE_UPDATE_V2 deltasWebsocket post 2024From 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).

text
     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 reads

Real 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:

PhaseClusterMain painMain fix
2015 MongoDBOne replica set, index (channel_id, created_at)Index out of RAM at 100M messagesMove to Cassandra
2017 Cassandra12 nodes, RF 3, ~1 TB compressed per nodeTombstones, large partitions10-day buckets, 2-day tombstones
2022 Cassandra177 nodes, ~4 TB per nodeHot partitions, compaction backlog, GC pausesData services, then ScyllaDB
2022 ScyllaDB72 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).

GET ch 42 (API 1)GET ch 42 (API 2)GET ch 42 (API 3)GET ch 42 (API n)Hash routerrouting key =channel_iddata service Aother channelsdata service B1st request: spawn workerlater: subscribe to itone gRPC call per querydata service Cother channelsScyllaDB1 read for n callerspartition (42, bucket)Without the router, the n requests land on n instances and coalesce nothing.
text
     @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:

LayerWhat it doesLimit Discord admits
Request coalescingOne query per row for concurrent callersOnly helps identical, concurrent requests
Consistent-hash routingPuts identical requests on one instanceUneven if one channel is extremely hot (inference)
ScyllaDBNo GC, shard-per-core isolation"Hot partitions can still be a thing"
Super-disk storageLocal 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).

text
     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 States

Real 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:

OptionResult in the post
Tune GC percent on the flyNo change (not allocating fast enough to trigger more GCs)
Smaller, partitioned LRU cachesSmaller 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 copiesFurther memory and CPU savings
Raise cache to 8 million Read StatesAverage 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++)".

text
     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 reconnect

Real 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:

YearFactSource
2018850+ voice servers, 13 regions, 30+ data centers, 2.6M concurrent voice usersVoice with WebRTC
2018Gateway and Guilds on Google Cloud Platform; voice on physical servers at several providersVoice with WebRTC
2025-2026Voice moved onto Cloudflare PoPs (300+ cities); over 80% of voice/video traffic thereVoice to the edge
2026One SFU instance hosts a whole call; host placement matters more than coverage for mixed-region callsVoice to the edge
2026More than 25,000 SFU instances; voice syncers place calls and send RPCs to SFUs3/25/26 voice outage
2026Discovery for edge hosts in Valkey with a ten-minute TTL; etcd strained at 25,000 hostsVoice 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.

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).

text
     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 Cassandra

Real 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 maxedGoogle Cloud Pub/Sub with guaranteed delivery
A 50-message bulk spanned many nodes; one node down failed ~40% of batchesRouter batches by destination (cluster, index) with a tokio task per destination
200+ node clusters, master nodes OOMMany 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 indexBFG cell: reindex big guilds to multi-shard indices with dual-writes
No cross-DM searchSeparate 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.

text
     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 on

Real 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).

EventDelivery promise (inference from posts)Dropped under load?
MESSAGE_CREATEEvery active session that may see it, in orderNo
PRESENCE_UPDATEBest effort, rebuilt after crashesCan lag
TYPING_STARTBest effort, ephemeralYes, switched off in 2023
Read state ackEventually persistedYes, 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".

text
     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).

text
     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 here

Real 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 factSource
Gateway and Guilds on Google Cloud PlatformVoice, 2018
Stateless services on Kubernetes; stateful moved laterIndexes trillions, 2025
Elixir services migrating to Kubernetes ("the blessed path")Voice outage, 2026
Validating admission webhook blocks scale-down until pods hand offVoice outage, 2026
Scylla Control Plane (SCP) automates ScyllaDB operations; 7-person persistence teamAutomates 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).

text
     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 API

Real 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).

text
     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 healthy

What each incident changed:

IncidentTriggerAmplifierChanges Discord made
2017 guild registryBurst of reconnecting sessionsTimeouts left requests queued; retries piled upSemaphore to fail fast
2023 authenticationZonal OS upgrade + degraded NVMe diskRetry storm from the API; cold row cachesDoubled cluster, disk-degradation detection, Scylla control plane
2026 voicePods scaled down without handoffReconnect thundering herd; single supervisor bottleneckAdmission 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.

Guild processone per guild,one event at a timeRelay 1up to 15,000 sessionsRelay 2permission checksRelay kManifold: 1 send per nodesession node Asession node Bpassive sessionsgateway, WebSocketgateway, WebSocketonly periodic deltasWork per message grows with online members; per server it grows with their squareDiscord reports about 90% of user-guild connections in large guilds are passive

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 knobValueNote
Hello (op 10)heartbeat_interval, example 45000 msFirst message after connecting
First heartbeatAfter heartbeat_interval * jitter, jitter in 0..1Spreads reconnecting clients
Heartbeat (op 1) / ACK (op 11)No ACK between heartbeats = zombied connectionReconnect with a close code other than 1000/1001
Identify (op 2)1,000 per 24 hours per botResume does not count
Resume (op 6)session_id, last sequence, resume_gateway_urlMissed events replayed, then Resumed
Invalid Session (op 9)d: true means resumableOtherwise identify again
Outbound rate limit120 events per connection per 60 sExceeding disconnects
Transport compressionzlib-stream or zstd-streamDiscord's own clients moved to zstd in 2024
Shardingshard_id = (guild_id >> 22) % num_shardsGuild-based routing for bots
Identify concurrencymax_concurrency from session start limitExceeding gets op 9

Gateway close codes ​

CodeNameReconnect?
4000Unknown errorYes
4004Authentication failedNo
4007Invalid seqYes, new session
4008Rate limitedYes, slower
4009Session timed outYes, new session
4011Sharding requiredNo, shard first
4014Disallowed intent(s)No

REST rate limits ​

LimitValueSignal
Global (bots)50 requests per secondHTTP 429, X-RateLimit-Global
Per routeVaries, grouped by X-RateLimit-BucketRetry-After / retry_after
Invalid requests10,000 per 10 minutes per IP (401, 403, 429)Temporary Cloudflare ban

Identifiers and storage knobs ​

KnobValueSource
Snowflake timestampBits 63-22, ms since 1420070400000 (first second of 2015)Developer docs
Worker / process / increment5 / 5 / 12 bitsDeveloper docs
Message bucketAbout 10 days, keeps partitions under 100 MBStores billions
Replication / consistencyRF 3 across three zones; quorum reads and writesStores billions; auth outage
Tombstone lifetimeLowered from 10 days (default) to 2 daysStores billions
ScyllaDB diskRAID mirror of Local SSD + Persistent Disk; ~40 min sync at bootNetwork disks; auth outage
Elasticsearch index1 primary shard, 1 replica, refresh every 60 min (2017)Indexes billions
Elasticsearch index size target200M messages and 50 GB per index (2025)Indexes trillions
zstd gateway settingsLevel 6, chainlog 16, hashlog 16, windowlog 18Reduced websocket traffic
BEAM GC tuningmin_bin_vheap_size raised to a few MB for guildsMaxjourney
Firebase XMPPMax 100 pending requests per connectionPush with GenStage
Relay sizeUp to 15,000 sessions per relayMaxjourney

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".

go
// 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.

go
// 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
}
go
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.

go
// 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()
}
go
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.

go
// 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
}
go
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.

go
// 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 }
go
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.

go
// 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()
}
go
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 featureUse hereNote
Goroutine + channel mailboxGuild "process" that handles one event at a timeSame ordering property as a GenServer, no supervision tree
sync.Mutex per shardPartitioned LRUDiscord's Go mitigation was partitioning, too
container/listLRU orderPointer-heavy: exactly what made Go's GC scan expensive
context.WithoutCancel (Go 1.21+)Shared coalesced query survives the first callerSubscribers keep their own deadlines
golang.org/x/sync/singleflightProduction-grade coalescingPrefer it over the hand-written Group
Buffered channel + select defaultShedding collectorNon-blocking offer
Semaphore channelAt most 100 in flightThe "demand" of GenStage
GOGC, GOMEMLIMIT, debug.SetGCPercentGC tuningDiscord 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
<?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
<?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
<?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
<?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
<?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
<?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 featureUse hereCaveat
Cache::lock($name, $seconds)->block($wait, $closure)Cross-worker coalescingThrows LockTimeoutException; needs a lock-capable store (Redis, database, Memcached...)
Cache::rememberFill once, reuseA TTL cache alone still stampedes at expiry
Cache::flexible($key, [fresh, stale], ...)Stale-while-revalidateServes stale data; Discord's message path did not
ShouldBeUniqueUntilProcessing + #[UniqueFor]One pending commit per keyUnlocks before handle, so later updates schedule the next commit
dispatch(...)->delay(30)The 30-second deferred writeDelay support depends on the queue driver
Redis facade dynamic commands (hget, hmset)Hot countersCommands go straight to Redis
ShouldBroadcastNowTyping without a queue hopUses the sync queue
Echo whisper('typing', ...) / listenForWhisperClient events that never hit the appThe broadcasting docs use typing as the example
Laravel Reverb REVERB_SCALING_ENABLED=trueHorizontal WebSocket servers via Redis pub/subAbove ~1,000 connections needs a non-stream_select event loop

Solving the classic problems ​

Hot partition on a popular channel ​

SolutionHowAdvantageCost / limitation
Bound partition size((channel_id, bucket), message_id)Partitions stay under ~100 MBQuiet channels scan several buckets
Request coalescingOne in-flight query per keyRemoves duplicate reads at the sourceOnly concurrent identical requests
Affinity routingConsistent hash on channel_id to one data-service instanceMakes coalescing effectiveOne instance carries a hot channel (inference)
Concurrency limit to the databaseBounded workers per partition (2023 goal)Protects the cluster from unbounded concurrencyRequests wait
Engine without GC pausesScyllaDBFewer latency spikesMigration 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:

sql
-- 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 ​

SolutionHowAdvantageCost
Shorter tombstone lifetime10 days to 2 days (repairs run nightly)Less to scanUnsafe if repairs stop
Track empty bucketsSkip buckets known to be emptyWorst case is one bucketExtra metadata
Never write nullsWrite only set columns12 fewer tombstones per messageApplication discipline

Latency spikes from garbage collection ​

SolutionHowAdvantageCost
Smaller heaps per processPartitioned caches (Go), relays and ETS (Elixir)Smaller pausesMore misses or more processes
No collectorRust (Read States), ScyllaDB (C++)No GC pausesRewrite
Tune the collectormin_bin_vheap_size on the BEAMCheapNeeds deep tracing to find

Reconnect thundering herd ​

SolutionHowAdvantageCost
Jittered first heartbeatheartbeat_interval * jitterSpreads reconnectsSlower average reconnect
Session resumeresume_gateway_url, last sequenceNo full READY payloadState must survive
Start-session rate limitRe-tuned per deployment shapeBackpressure at the gatewayStale limits fail (2026)
Drain before scale-downAdmission webhook rejects updates until handoffNo mass session lossSlower deploys

Retry storm against an overloaded dependency ​

SolutionHowAdvantageCost
Fail fast with a semaphoreBound outstanding calls; reject the restNo unbounded queuesSome requests rejected
Shed optional workTurn off typing and read markersRestores core functionDegraded UX
Circuit breaking in the APIAutomatic demand reduction (2026 mention)Protects databasesMust avoid "nothing gets through" states
Capacity headroomDouble small critical clustersRoom for a zone plus a nodeCost

Bulk operations that span many nodes ​

SolutionHowAdvantageCost
Batch by destinationOne batch per (cluster, index)One failed node fails one batchMore, smaller batches
Durable queuePub/Sub instead of Redis listsNo dropped messages under backlogManaged-service dependency
CellsMany small clustersSmaller blast radius, cheaper master nodesMore 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 subsystemGeneric patternChapter to read
Gateway WebSockets, heartbeats, resumePersistent connections, reconnect with jitterReal-Time Communication
Guild process fan-outFan-out on write to online subscribersFeeds: Fan-Out
Placement on a hash ringConsistent hashingConsistent Hashing
Message partitions and bucketsPartition key design, hot partitionsSharding at System Level
Cassandra and ScyllaDBWide-column storageCassandra & ScyllaDB in Depth
Snowflake IDsTime-ordered IDsID Generation at Scale
Request coalescingSingle-flight, batchingWrite Buffering & Coalescing
Read states cacheWrite-behind cachingCaching
Push pipelineBackpressure, load sheddingBackpressure, Load Shedding
Voice SFU over UDPUDP media, regional placementTCP & UDP, Latency Budgets
Search cellsSearch architectureSearch Systems
MongoDB to Cassandra to ScyllaDB with dual writesSafe migrationsStrangler Fig
IncidentsCascades, retries, breakersCascading Failures
Kubernetes deploymentsContainers, graceful terminationContainers & Kubernetes
Dagster + dbtBatch data platformBig Data Architectures

Choosing ​

Your situationDo what Discord did?Extra techniqueReason
Chat with small groups (under ~100 per room)No relays, no passive sessionsPlain pub/sub (Redis, Laravel Reverb)Fan-out is cheap at that size (inference)
Rooms with tens of thousands onlineYes: per-node batching, passive subscribersSummaries for idle membersWork grows with the square of online members
Append-heavy, read-recent historyPartition by (conversation, time bucket)Snowflake or ULID IDsBounded partitions, contiguous reads
Many identical reads at the same instantCoalescing with affinity routingShort-TTL cache in frontRemoves the stampede at the source
Long-lived big in-memory heap with tail SLOMeasure GC first; consider partitioning or a no-GC runtimeGOMEMLIMIT, off-heap storesDiscord's spikes came from heap scanning
Group voice over about 4 peopleSFU, client-serverRegional placement by participantsP2P mesh cost grows with participants
Search is a minor featureLazy indexing, bulk ingestRefresh on demandKeeps search cheaper than storage
Notifications in burstsBounded demand, shedding bufferCollapse duplicate notifications (inference)Recovery beats completeness
Small, critical database clusterExtra headroom, careful zonal operationsCheck cache hit rate before proceeding2023 outage
Large stateful services on KubernetesDrain-before-terminate checksAdmission webhook2026 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 ​

ScaleWhat Discord's history suggestsSource or status
1x (launch)One database, one app, one region2015 MongoDB
10xMove the biggest table to a store that scales by adding nodes; bucket partitions2016-2017 Cassandra
10xMake fan-out cheaper: per-node batching, copy-free shared data, semaphores2017 Elixir
100xSplit big rooms (relays), do less (passive sessions), move hot structures to native code2019, 2023
100xProtect the database with a data-service layer; then change engines2022-2023
100xCells for search; Kubernetes for operability; edge PoPs for voice2025-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.

bash
cd docs/snippets/system-design/case-study-discord/go
go vet ./... && go test ./...
text
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
  1. 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 run go test -v -run ManyUpdates ./readstates/: the same 500 mentions become exactly one commit after the 30-second window.
  2. 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.
  3. 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.
  4. Passive sessions. go test -v -run Passive ./fanout/ delivers to 1,000 of 10,000 sessions when 90% are passive; TestOneSendPerNodeNotPerSession shows 30,000 recipients reached with 10 node sends.
  5. Shedding instead of collapsing. go test -v -run Burst ./pusher/ accepts 10 and sheds 990 when nobody consumes; TestNeverMoreThan100Pending never exceeds 100 in flight.
  6. Laravel coalescing (expected, not run). With Redis as the cache store, fire 200 concurrent requests at a route that calls CoalescedMessageReader::latest(42) (for example hey -n 200 -c 200 http://127.0.0.1:8000/channels/42/messages) while query logging is on:
text
# 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 lock

Common misconceptions ​

BeliefReality
Discord rewrote its backend in RustThe API is Python (2026); real time is Elixir; Rust powers selected hot paths
ScyllaDB removed hot partitionsDiscord says hot partitions can still happen; coalescing and routing do the protecting
Go is unsuitable for low latencyThe 2020 issue was GC scanning a huge LRU on Go 1.9-era runtimes; the lesson is about heap shape
Voice is peer-to-peerAll media goes through Discord's SFUs, for scale, IP privacy and moderation
Search indexes every message immediatelyIndexing is lazy (first search) and in bulk; search freshness is traded for cost
Every push notification is deliveredUnder extreme bursts some are shed by design
Three zones with quorum survive any single problemOne zone down plus one degraded node broke quorum performance in 2023
More shards always make search fasterDiscord uses one primary shard per index except for Big Freaking Guilds
One process per guild cannot scaleIt scales with relays, passive sessions and offloaded workers; the single process stays for full-view state
Typing and presence are as important as messagesThey are the first features switched off under load

Cheat sheet ​

TopicRemember
Core idea"most of it boils down to pub/sub" (2017)
ProcessesOne GenServer per session, one per guild; consistent-hash placement
ManifoldOne send per remote node; partitioner hashes PIDs per core
FastGlobalConstant-pool shared data: 0.33 µs vs 7.64 µs ETS (README)
Large guildsRelays of up to 15,000 sessions; ~90% passive sessions
Message key((channel_id, bucket), message_id), 10-day buckets
Storage historyMongoDB (2015), Cassandra 12 to 177 nodes, ScyllaDB 72 nodes (May 2022)
Data servicesRust, gRPC per query, request coalescing, routing by channel ID
Read statesOne per user per channel; LRU; commit on eviction and after 30 s; Go to Rust for GC spikes
VoiceWebRTC clients, C++ SFU (2018), voice server per guild, etcd discovery; edge PoPs (2026)
SearchElasticsearch, lazy, bulk; refresh on demand; cells, Pub/Sub, BFG multi-shard (2025)
PushGenStage, demand 100 (Firebase XMPP limit), shedding buffer
Gateway knobsHeartbeat with jitter, resume, 120 events/60 s, zlib-stream or zstd-stream
Incidents2023 auth: zonal upgrade + degraded disk + retry storm; 2026 voice: scale-down without handoff
Inference ruleAnything not in a Discord post is marked inference

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
DiscordChat, voice and community platform; "servers" are called guilds internally
GuildInternal name for a Discord server; one Elixir process routes its events
ElixirFunctional language on the Erlang VM; Discord's real-time core
ErlangLanguage and runtime (OTP) Elixir builds on
BEAMThe Erlang virtual machine: lightweight processes, per-process heaps and GC
GenServerGeneric server process in Elixir/OTP; handles one mailbox message at a time
WebSocket gatewayDiscord's ingress/egress service for all client WebSocket traffic
Session (process)One process per connected device; forwards events to its WebSocket
ManifoldDiscord library: groups PIDs by node so a send happens once per node
FastGlobalDiscord library: shared read-only data via the BEAM constant pool
Semaphore (library)Discord library: bounded concurrency using :ets.update_counter/4
ETSErlang Term Storage: in-memory tables shared by processes
NIFNative Implemented Function: C or Rust code called from the BEAM
RelayProcess between guild and sessions doing fan-out for up to 15,000 sessions
Passive sessionUser-guild connection that gets only periodic summaries
Concurrent usersUsers connected at the same moment (5M in 2017, 11M in 2019 title)
VoiceDiscord audio calls; voice servers per guild, SFU media relay
WebRTCW3C/IETF real-time audio, video and networking standards used by Discord clients
SFUSelective forwarding unit: forwards media streams without mixing
Voice syncersElixir service that places calls on SFUs and sends them RPCs (2026)
RustSystems language without a GC; used for data services, Read States, NIFs
Message storageThe messages cluster: MongoDB, then Cassandra, then ScyllaDB
MongoDBDiscord's first database (2015)
CassandraWide-column database Discord used for messages from ~2016 to 2022
ScyllaDBCassandra-compatible C++ database, shard-per-core, no GC
Data serviceDiscord's Rust gRPC layer between the API and ScyllaDB
Request coalescingMerging concurrent identical requests into one backend query
Hot partitionA partition receiving so much traffic its nodes slow everyone down
Read statesPer user per channel read position and mention counters
GC latencyLatency added by garbage-collection pauses or scans
Go to RustThe 2020 Read States rewrite that removed GC spikes
ElasticsearchSearch engine Discord uses for message search
Message searchDiscord's full-text search over messages, indexed lazily
CellGroup of smaller Elasticsearch clusters for one dimension (guilds, DMs, BFGs)
PresenceOnline status and activity, fanned out by guilds
Typing indicatorEphemeral TYPING_START event; first to be shed under load
Push notificationsMobile pushes for inactive users through Firebase
GenStageElixir behaviour for producer/consumer stages with demand-based backpressure
KubernetesContainer orchestrator for Discord's API and, increasingly, Elixir services
Data orchestrationScheduling and dependency management of data pipelines (Dagster)
Snowflake64-bit time-ordered ID: 42-bit timestamp, worker, process, increment
IncidentProduction outage; Discord publishes postmortems on its blog
InferenceA statement on this page not taken from Discord's own sources

References ​

Discord engineering blog (all fetched and read; HTTP 200):

Discord open source and documentation:

Framework documentation used for the Laravel code:

Built by Morteza Negahi