Design Discord
hard 50 minDesign a service for communities like Discord: huge groups with text channels, voice rooms that are always open, and detailed roles.
See it run
Connect, send, join a voice room, serve a giant community, check rights and run bots, one hop at a time.
Operations
Connect and send
From the first handshake to a stored message and a voice request.
Step 1 of 13
Identify
op
identify
The app opens a WebSocket and says who it is and which events it wants.
Step 1: Identify
def identify(token, intents): session = new_session(check(token), intents) attach_to_groups(session) return ready(session)def post(user, channel, content, nonce): require(permissions(user, channel) & SEND) mid = new_id() # time inside data.store(channel, bucket(mid), mid, content) group_process(channel).event(mid) return 200, mid- Latency
- about 100 ms
- Load
- 46,000/s
- Peak (3x)
- 139,000/s
Events come over the gateway. Writes go over HTTP, where an error code is clear.
In the real world
The same discord doing real jobs. Pick one and step through it.
Four people are talking.
Step 1 of 5
Silence
The voice server stops.
Step 1: Silence
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Sending everything to all connected people
critical100,000 people and ten events are a million sends a second.
Wrongfor s in all_sessions: s.send(event)Rightfor s in sessions_viewing(event.channel): s.send(event)One partition per channel
majorIt grows for years and becomes slow to read and repair.
WrongPRIMARY KEY (channel_id, message_id)RightPRIMARY KEY ((channel_id, bucket), message_id)Applying role rules one after another
criticalThe result then depends on the order of roles. Join all denies and allows first.
Wrongfor r in roles: bits = bits & ~r.deny | r.allowRightdeny = join(r.deny for r in roles)allow = join(r.allow for r in roles)bits = bits & ~deny | allowSending lost voice again
majorIt arrives late and holds back what follows.
Wrongtcp.send(frame)Rightudp.send(frame) # hide a loss in the decoderA wrong bucket size
majorAn id divided by ten billion is about 2.4 seconds, not months: 10,000,000,000 / 4,194,304 is 2,384 ms.
Wrongbucket = message_id // 10_000_000_000Rightbucket = (message_id >> 22) // (10 * 86_400_000)
Interview tips
Skip the known
- Take ordinary chat as given.
- Name the giant and the voice.
- Ask for the largest community.
Count packets
- 50 a second per stream.
- 120M a second in all.
- Silence sends nothing.
Reduce, then spread
- Passive sessions: nine in ten.
- Relays: 15,000 each.
- Lists: visible rows only.
Fail apart
- Text down, voice goes on.
- Room moves in seconds.
- Keep a third spare.