Fault-Tolerant Meeting Bot Dispatch and Lifecycle Service
Medium · System Design · Software Engineer · Onsite
Prompt
Architect the dispatch and lifecycle orchestration backend sitting between a web client and a pool of virtual conference-call bots. When a customer submits a conference URL along with optional join credentials, the backend acknowledges the request asynchronously, claims a free bot worker atomically, and pushes live session status updates—including joined, disconnected, ended, and failed—to the browser. Design for 100,000 simultaneous live calls at peak and 1,000,000 calls per day.
Operating assumptions and failure modes: - Zero silent loss: Every submission acknowledged by the API must reliably reach a visible terminal outcome rather than vanishing silently. - Duplicates and mid-call crashes: Internal or client messages may be delivered multiple times, and bot workers may die partway through an active call. - Design choices to clarify up front: Decide whether access credentials are persisted encrypted or only forwarded in memory, and establish the latency target for delivering status transitions to the client UI.
Scope & Expectations
- APIs and real-time client delivery: Define the asynchronous submission contract, idempotency semantics, credential-handling model, and low-latency browser push channel.
- Data model and atomic allocation: Show how requests, bot workers, and assignments are stored and locked so each call claims exactly one idle bot without silent drops.
- Fleet sizing and burst scaling: Plan capacity and warm-pool management for
100,000concurrent calls,1,000,000daily calls, and top-of-the-hour join spikes. - Crash recovery and observability: Detail liveness detection, mid-call bot replacement, fencing against stale workers, and key operational trade-offs.
Step-by-step walkthrough
Clarify requirements and scope
Imagine building an automated dispatch desk between a web app (where users paste a Zoom, Google Meet, or Microsoft Teams link) and a fleet of 100,000 virtual meeting bots that join calls as participants to record or transcribe audio. Before drawing boxes, clarify what "accepted," "atomic assignment," and "fault tolerant" require in practice—every database table and timeout in the design flows from those three promises.
Functional requirements
- Asynchronous submission: Clients post a conference link, optional passcode credentials, an optional scheduled
join_attimestamp, and a bot display name. The API immediately returns an acceptance receipt (request_id) while joining happens in the background. - Atomic bot allocation: Assign exactly one idle bot from the matching platform pool to each active meeting request—never two bots to one request, and never two requests to one bot.
- Live state streaming: Push every lifecycle change to the user's browser:
QUEUED,ASSIGNED,JOINING,IN_LOBBY(waiting room),JOINED,DISCONNECTED(bot lost, replacement on the way),ENDED,FAILED(with a clear error code), orCANCELED. - User cancellation & deduplication: Users can cancel an active request (causing the bot to leave immediately). If three teammates from the same company account submit the exact same meeting URL, they share one bot rather than spawning three bots in the room.
Non-functional requirements
- Scale: 1,000,000 meetings per day and 100,000 concurrent live meetings at peak.
- Zero silent loss: Once the API returns
202 Accepted(an HTTP status code meaning "durably received and queued for background processing"), the request is guaranteed to reach a visible terminal state (ENDED,FAILEDwith a reason, orCANCELED). A meeting may legitimately fail (for example, wrong passcode), but it may never silently vanish. - Duplicate tolerance (idempotency): Network retries, double-clicked browser buttons, and duplicated internal messages must never spawn duplicate bots or corrupt state transitions.
- Mid-session crash recovery: If a bot container crashes, freezes, or loses network mid-meeting, detect the failure and send a replacement bot within ~45 seconds.
Key product and security clarifications
- Request-scoped encrypted storage vs. transient forwarding for credentials: Store encrypted strictly for the request's active lifetime. Forwarding passcodes purely in memory sounds attractive, but when a bot worker dies 20 minutes into a call, its replacement needs that passcode again—and we cannot interrupt an absent organizer to re-enter it. We store credentials encrypted inside a dedicated vault and wipe them permanently as soon as the session enters a terminal state.
- Target latency for pushing status transitions to the client UI: Within 1–2 seconds (
p99). Multi-second HTTP polling feels laggy and wastes connections, so each browser tab opens a lightweight SSE (Server-Sent Events) stream—a standard one-way HTTP channel that pushes server updates immediately and reconnects seamlessly using a version cursor.
- Asynchronous submission: Clients post a conference link, optional passcode credentials, an optional scheduled
Back-of-the-envelope numbers
Meeting traffic has a crucial real-world quirk: people schedule meetings at
:00and:30on the clock, creating massive top-of-the-hour join spikes. Let's calculate both steady load and boundary bursts.1. Meeting concurrency & the :00 / :30 clock burst Daily volume 1,000,000 meetings / 86,400 s = ~11.6 starts/s average Average meeting duration assume 45 min (2,700 s) Average concurrency 11.6 starts/s x 2,700 s = ~31,300 concurrent bots (Little's Law: avg active items = arrival rate x average duration) Peak concurrency (given) 100,000 concurrent bots (~3.2x average during business-hour overlap) Starts per hour at peak 100,000 active / 0.75 hours = ~133,000 starts/hour Top-of-hour (:00 / :30) burst assume 50% of starts cluster into 1-minute windows at :00 and :30: ~66,500 across two boundaries -> ~33,000 joins in 60 s at :00 = ~550 joins/s (design control plane for 1,000 joins/s) 2. Bot compute fleet (the dominant hardware cost) Resources per bot container 1 vCPU, 1.5 GB RAM (headless browser + WebRTC audio capture) 100,000 busy bots at peak 100,000 vCPU, 150 TB RAM -> ~1,600 worker VMs (64 vCPU, 128 GB RAM each) Boundary overlap at 10:00 Single-use bots for 10:00 (~33,000 warm idle) must already be booted at 9:59 BEFORE the 9:00-10:00 meetings finish freeing their VMs: 100,000 busy + 33,000 warm idle = ~133,000 containers -> ~2,100 VMs Audio egress from bots ~64 kbps compressed audio x 100,000 = ~6.4 Gbps total 3. Control-plane database & liveness traffic Bot heartbeats 133,000 bots / every 5 s = ~26,600 heartbeats/s (ephemeral -> Redis) Durable state transitions ~8 per meeting x 1M/day = 8M writes/day (~93 tx/s average) Peak :00 transition burst 33,000 joins x 4 early states (QUEUED->ASSIGNED->JOINING->JOINED) in 60 s = ~2,200 transactions/s fleet-wide (~220 tx/s per cell across 10 cells) Browser SSE fan-out ~2,200 events/s at peak x ~200 B = ~440 KB/s total Metadata storage ~3 KB per meeting (row + event history) x 1M/day = ~3 GB/dayThree insights jump out of these numbers: 1. The control plane is tiny compared to the media fleet: 220 short SQL transactions per second per cell is effortless for PostgreSQL, letting us use strict ACID transactions to prevent double assignment instead of fragile distributed locks. 2. Heartbeats outnumber state transitions 10x (26,600/s vs. 2,200/s) and carry no historical value, so they belong in in-memory Redis keys with automatic expiration, never in PostgreSQL. 3. Cold-starting 33,000 browsers at
10:00:00takes minutes, so meeting the 30-second join SLA requires a forecast-driven warm pool booted ahead of:00and:30.API and bot wire protocol
1. Browser-facing HTTPS API
POST /v1/bot-requests Headers: Authorization: Bearer <token> Idempotency-Key: <UUID generated by browser when form renders> Body: { "meeting_url": "https://zoom.us/j/123456789", "credentials": { "passcode": "948201" }, // optional; never logged "join_at": "2026-11-30T15:00:00Z", // optional; defaults to now() "bot_name": "Team Notetaker" } Responses: 202 Accepted -> { "request_id": "c04-01JDX...", "state": "QUEUED", "version": 1, "events_url": "/v1/bot-requests/c04-01JDX.../events" } 200 OK -> same payload (returned on duplicate Idempotency-Key or existing team meeting) 422 -> UNSUPPORTED_URL | IDEMPOTENCY_KEY_PAYLOAD_MISMATCH GET /v1/bot-requests/{request_id} -> current snapshot { state, version, attempt, reason, ... } GET /v1/bot-requests/{request_id}/events -> SSE stream (supports Last-Event-ID: <version> on reconnect) POST /v1/bot-requests/{request_id}/cancel -> idempotent user cancellation- An
Idempotency-Keyis a client-generated unique token attached to a write request so that if the user clicks "Join" twice or retries after a Wi-Fi drop, the server returns the originalrequest_idinstead of creating a second bot request.
2. Bot-to-Control-Plane gRPC stream (via Bot Gateway)
bot -> Register { bot_id, pool_id: "zoom:us-east:v42", node_id } bot -> Heartbeat { bot_id, assignment_id?, attempt?, local_state, last_seq } // every 5 s ctl -> Assign { assignment_id, request_id, attempt, meeting_url, join_at, credential_ticket } bot -> Accept { assignment_id } bot -> Report { assignment_id, attempt, seq, state: JOINING | IN_LOBBY | JOINED | ENDED | FAILED, reason } ctl -> Ack { assignment_id, seq, lease_valid_for_ms: 20000 } ctl -> Leave { assignment_id, reason: USER_CANCELED | FENCED_BY_NEWER_ATTEMPT }attemptacts as a monotonic fencing token: Attempt 1 is the first bot assigned; if it crashes, its replacement receivesattempt = 2. Every receiver (control plane and audio pipeline) rejects messages or audio carrying an olderattempt.credential_ticketis a short-lived, single-use token; the bot exchanges it directly with the Credential Vault over TLS so plaintext passcodes never pass through Kafka, logs, or control-plane tables.
- An
Data model and request state machine
Every request moves monotonically by
version(1, 2, 3...) through this state machine:[ QUEUED ] ---- allocator locks bot ----> [ ASSIGNED ] ---- bot starts ----> [ JOINING ] ^ | | | | (10s offer timeout: bot never accepted) | | | (no waiting room) +------------------------------------------+ | v | v [ JOINED ] ---> [ ENDED ] | [ IN_LOBBY ] ^ | | | (host admits) | +------+ Mid-session recoverable crash (from ASSIGNED / JOINING / IN_LOBBY / JOINED): ---> [ DISCONNECTED ] ---- allocator assigns warm bot (attempt + 1) ----> [ ASSIGNED ] Unrecoverable error or retry cap (attempt == 3) from any active state: ---> [ FAILED ] (reason: WRONG_PASSCODE | DENIED_BY_HOST | REMOVED_BY_HOST | LOBBY_TIMEOUT | NO_CAPACITY | ...) User action from any non-terminal state: ---> [ CANCELED ]Distinguishing recoverable from final reasons is essential: - Recoverable (
DISCONNECTED-> new bot):BOT_CRASHED,HEARTBEAT_TIMEOUT,NODE_PREEMPTED,PLATFORM_5XX. - Final (FAILED-> stop immediately):WRONG_PASSCODE,DENIED_BY_HOST,REMOVED_BY_HOST,MEETING_NOT_FOUND,LOBBY_TIMEOUT(10 min),TOO_MANY_ATTEMPTS(max 3). Importantly,REMOVED_BY_HOSTis final—if a human host kicks the bot out of a confidential call, our system must never rudely send another bot back in!Relational schema (one PostgreSQL database per cell shard):
bot_requests request_id PK (cell prefix + ULID), account_id, user_id, idempotency_key, body_hash, pool_id, platform, platform_meeting_id, meeting_url, credential_ref NULL, join_at, give_up_at, state, state_deadline_at, version, attempt, reason NULL, current_assignment_id NULL, created_at, updated_at UNIQUE (account_id, idempotency_key) UNIQUE (account_id, platform, platform_meeting_id) WHERE state NOT IN ('ENDED', 'FAILED', 'CANCELED') INDEX (pool_id, state, join_at) INDEX (state_deadline_at) WHERE state NOT IN ('ENDED', 'FAILED', 'CANCELED') assignments assignment_id PK, request_id, bot_id, attempt, last_seq, state (OFFERED | ACTIVE | RELEASED), release_reason NULL, created_at, released_at NULL UNIQUE (request_id) WHERE state IN ('OFFERED', 'ACTIVE') -- DB-enforced: <= 1 live bot per request UNIQUE (bot_id) WHERE state IN ('OFFERED', 'ACTIVE') -- DB-enforced: <= 1 live request per bot bots bot_id PK, pool_id, node_id, az, state (STARTING | IDLE | BUSY | GONE), current_assignment_id NULL, idle_since INDEX (pool_id, state, idle_since) request_events (request_id, version, PK (request_id, version), state, attempt, reason, created_at) outbox (outbox_id PK, request_id, version, payload, created_at)Two schema features carry massive weight here: - Partial unique indexes (
UNIQUE (...) WHERE ...) let PostgreSQL enforce invariants only on currently active rows—allowing historical released assignments while making it physically impossible for a bug to commit twoACTIVEbots for one request, or two live requests for the same(account_id, platform, platform_meeting_id). -state_deadline_atgives every non-terminal state an explicit expiration clock (+10 sforASSIGNED,+2 minforJOINING,+10 minforIN_LOBBY,+4 hmax duration forJOINED,give_up_atforQUEUED/DISCONNECTED), ensuring no request can ever get stuck silently forever.High-level architecture
[ Web Browser ] | ^ | | SSE live stream (Last-Event-ID: <version>) | +---------------------------- [ Stateless SSE Gateways ] <---+ | POST /v1/bot-requests ^ | v (Idempotency-Key) | Kafka: state-events (~2.2k msg/s) [ Stateless Request API ] | | | routes by account's home cell | | v | | =========================== Cell Shard (x10, ~10k concurrent meetings) =========================== [ Cell PostgreSQL (Primary + Sync Standby AZ2) ] ---> [ Transactional Outbox Relay ] ------------+ ^ ^ ^ | SKIP LOCKED | check expired | scale pools (forecast + schedule) v | v [ Allocators ] [ Supervisor ] [ Warm Pool Manager ] ---> [ Kubernetes Node Autoscaler ] | ^ | v | check 30s TTL v [ Bot Gateways ] --+------------> [ Cell Redis: hb:{bot_id} ] [ Single-Use Bot Containers ] ^ (Core + Platform Adapter) | bidirectional gRPC (5s heartbeats, Assign, Report) | | +----------------------------------------------------------------+ | ===================================================================================|============== | +---------------------------------------------------------------------------+ v v v [ Credential Vault (KMS) ] [ Zoom / Meet / Teams ] [ Media Ingest Pipeline ] (redeem single-use ticket) (external meeting call) (verifies attempt token)Deep dive 1: zero-loss acceptance and atomic bot assignment
1. Answering
202 Acceptedwithout ever losing a requestIf the API stored a passcode, pushed a job to an in-memory queue, and returned
202before hitting disk, a server crash 1 millisecond later would break our zero-silent-loss durability guarantee. Instead, the Request API executes one synchronous database transaction: 1. If credentials were provided, encrypt them in the Credential Vault using envelope encryption (encrypting the passcode with a fresh per-request key wrapped by a cloud KMS master key) to obtaincredential_ref. 2. RunINSERT INTO bot_requests ... ON CONFLICT DO NOTHINGalongside insertingrequest_events(version = 1, state = 'QUEUED') and anoutboxrow (a transactional outbox table written in the same commit so downstream Kafka events are never lost even if Kafka blinks). 3. Wait for commit confirmation from both the primary and its synchronous standby replica in a second availability zone, then return202 Accepted.If
ON CONFLICT DO NOTHINGinserts zero rows, the API queries the conflicting row: ifidempotency_keymatches with the samebody_hash, it returns the existing request (200 OK); if(account_id, platform, platform_meeting_id)already has a live request from a teammate, it returns that shared request (200 OK).2. Using PostgreSQL
FOR UPDATE SKIP LOCKEDas the atomic allocatorAt 220 peak transactions/s per cell, keeping the queue right inside
bot_requestsavoids dual-write bugs between a separate queue and the database. Crucially, the allocator queries perpool_id(zoom,meet,teams) so a temporary shortage of Zoom bots never causes head-of-line blocking for Google Meet requests when Meet bots are sitting idle!FOR UPDATE SKIP LOCKEDtells PostgreSQL: "Lock the first matching unlocked row for me, and immediately skip over any row another allocator worker is currently locking instead of waiting in line."BEGIN; -- 1. Lock the most urgent waiting or reconnecting request for THIS platform pool. -- Includes DISCONNECTED (join_at = now()) so mid-meeting crashes jump to the front! SELECT request_id, attempt FROM bot_requests WHERE pool_id = :pool_id AND state IN ('QUEUED', 'DISCONNECTED') AND join_at <= now() + interval '45 seconds' ORDER BY join_at ASC LIMIT 1 FOR UPDATE SKIP LOCKED; -- 2. Lock the longest-waiting IDLE bot in the exact same platform pool. SELECT bot_id FROM bots WHERE pool_id = :pool_id AND state = 'IDLE' ORDER BY idle_since ASC LIMIT 1 FOR UPDATE SKIP LOCKED; -- 3. Atomically bind bot <-> request and advance fencing token (attempt + 1). UPDATE bots SET state = 'BUSY', current_assignment_id = :assignment_id WHERE bot_id = :bot_id AND state = 'IDLE'; UPDATE bot_requests SET state = 'ASSIGNED', attempt = attempt + 1, version = version + 1, current_assignment_id = :assignment_id, state_deadline_at = now() + interval '10 seconds', updated_at = now() WHERE request_id = :request_id AND state IN ('QUEUED', 'DISCONNECTED'); INSERT INTO assignments (assignment_id, request_id, bot_id, attempt, last_seq, state) VALUES (:assignment_id, :request_id, :bot_id, :attempt + 1, 0, 'OFFERED'); INSERT INTO request_events (request_id, version, state, attempt, created_at) VALUES (:request_id, :new_version, 'ASSIGNED', :attempt + 1, now()); INSERT INTO outbox (request_id, version, payload, created_at) VALUES (:request_id, :new_version, :event_json, now()); COMMIT;If step 2 finds zero
IDLEbots in:pool_id, the allocator simply rolls back and leaves the request untouched inQUEUED(orDISCONNECTED) until a bot frees up.Two-phase handshake (
OFFERED->ACTIVE): AfterCOMMIT, the Bot Gateway sendsAssignover the bot's gRPC stream. When the bot repliesAccept, the assignment becomesACTIVE. What if the bot crashed 50 ms beforeAssignarrived, or the allocator crashed right afterCOMMIT? - Every 5-secondHeartbeatreports the bot's currentassignment_id; if the DB saysOFFEREDwhile the bot reportsidle, the gateway immediately re-sendsAssign. - Otherwise, afterstate_deadline_at(10 seconds), the Supervisor marks that unresponsive botGONE, releases theOFFEREDrow, and puts the request back toQUEUED(preserving its originaljoin_atpriority) for the next warm bot.Deep dive 2: mid-meeting bot crashes, self-fencing leases, and zombie protection
Suppose
bot-42(attempt = 1) is 20 minutes into recording a meeting when its VM freezes or loses network. We have two competing goals: replacebot-42fast, and never let two bots sit in the same call recording duplicate audio.Coordinated lease timing (
20 sbot self-fence vs.30 ssupervisor replacement):Time since last sent heartbeat: t = 0 s bot-42 sends Heartbeat -> Gateway writes Redis key hb:bot-42 (TTL = 30 s) -> returns Ack t = 5 s network partitions or bot-42 hangs; heartbeats stop reaching Gateway ... t = 20 s [BOT SELF-FENCES] bot-42 sees 20 s elapsed since its last acknowledged heartbeat send-time. It immediately hangs up from Zoom/Meet and stops streaming audio on its own! ... t = 30 s [SUPERVISOR REPLACES] Redis key hb:bot-42 expires (30 s since last received beat). Supervisor atomically releases assignment 1, marks request DISCONNECTED (join_at = now(), give_up_at = now() + 10 min), and Allocator dispatches warm bot-88 with attempt = 2!Notice why the clocks cannot cross:
bot-42starts its 20-second countdown when it sends a heartbeat, whereas the Supervisor starts its 30-second countdown later, when it receives that heartbeat. That built-in 10-second safety margin absorbs clock skew and network jitter so a partitioned bot takes itself out of the meeting beforebot-88is ever dispatched. (Note: why do we refreshgive_up_at = now() + 10 minon crash? Because the original start-timegive_up_atexpired 10 minutes into the call—keeping the old timestamp would falsely fail a 20-minute-in crash asNO_CAPACITY!)What if
bot-42was frozen by a 45-second OS pause and wakes up as a "zombie"? We never rely solely on polite bot behavior—every receiver enforces theattemptfencing token: 1. Whenbot-42sends a lateReport(attempt=1, state=ENDED)orHeartbeat(attempt=1), the Bot Gateway sees the request is now onattempt = 2, drops the stale report so it cannot overwritebot-88'sJOINEDstate, and sendsLeave(FENCED_BY_NEWER_ATTEMPT). 2. Every audio packet sent to the Media Ingest Pipeline carries(request_id, attempt). Onceattempt = 2starts, packets taggedattempt = 1are dropped at the edge so duplicate audio never corrupts the transcript. 3. To stop "poison meetings" (a malformed URL or platform change that crashes every browser opening it) from draining the whole bot pool,attemptis capped at 3 (FAILED: TOO_MANY_ATTEMPTS).Deep dive 3: surviving the top-of-hour burst and streaming live states
1. Single-use bots + predictive warm pool for
:00and:30Each bot container runs a full headless browser. Reusing the same browser across two customers risks leaking session cookies, WebRTC buffers, or memory leaks, so every bot container is single-use: when a meeting ends, the container is destroyed and replaced on freed VM space.
Because cold-booting a VM takes 60–120 seconds and starting Chromium takes 10–15 seconds, waiting until
10:00:00to boot 33,000 bots would miss our 30-second join SLA. Every 30 seconds, each cell's Warm Pool Manager computes:needed_warm_bots(next 10 min, pool) = known_scheduled_meetings(join_at in [now, now + 10m]) -- exact query on bot_requests! + p95_adhoc_submissions(same_weekday, same_10m_slot) -- historical baseline for instant links + 10% safety bufferAt
09:45, the Pool Manager pre-scales Kubernetes VMs; between09:50and09:59, it smoothly starts ~3,300 warmIDLEcontainers per cell (~5.5 container starts/s/cell). When10:00:00hits, 33,000IDLEbots are already registered and join in 5–12 seconds. If an unexpected viral spike still exhausts a cell's pool, requests stayQUEUED(showing"Waiting for available bot"in the UI) up togive_up_at(start + 10 min), and if still unserved, transition visibly toFAILED: NO_CAPACITY.2. Gapless sub-2-second SSE streaming to browsers
Every database state transition writes both
request_events(request_id, version)andoutbox. An Outbox Relay tailsoutboxevery 50 ms and publishes to astate-eventsKafka topic partitioned byrequest_id.Because fleet-wide state changes peak at only ~2,200 tiny events/s (~440 KB/s), every stateless SSE Gateway subscribes to all Kafka partitions and forwards matching events to locally connected browser tabs—zero fragile "which gateway holds user X?" routing table required!
When a user's laptop Wi-Fi drops and reconnects sending
Last-Event-ID: 3, the SSE Gateway prevents race-condition gaps with a strict two-step merge: 1. First, start buffering live Kafka events forrequest_idin memory. 2. Second, query the cell PostgreSQL primary forSELECT * FROM request_events WHERE request_id = :id AND version > 3 ORDER BY version, flush those rows, and then flush any buffered Kafka events withversion > max_db_version.Scaling, failure modes, and trade-off summary
Cell-based horizontal architecture (10 cells, ~10,000 concurrent meetings each):
Each customer
account_idis mapped to a home cell in its geographic region (cached by the Request API), and everyrequest_idcarries its cell prefix (c04-...). Pinning an account to one home cell is crucial: it guarantees both(account_id, idempotency_key)and single-bot-per-meeting deduplication (UNIQUE (account_id, platform, platform_meeting_id)) are enforced inside a single local PostgreSQL database without slow cross-shard distributed transactions!End-to-end failure matrix:
Failure scenario System recovery & why zero requests are silently lost ----------------------------------------------------------------------------------------------------- API crashes before DB commit Client gets 5xx/timeout and safely retries with same Idempotency-Key. API crashes after commit, pre-202 Client retry hits UNIQUE(account_id, idempotency_key) -> returns 200 OK. Allocator crashes mid-SQL PostgreSQL rolls back lock; another allocator claims the request. Bot crashes mid-meeting Bot self-fences at 20s; Supervisor marks DISCONNECTED at 30s -> new bot. Cell Redis restarts (empty) Supervisor pauses dead-bot checks for 30s (1 full TTL) while bots re-beat. PostgreSQL primary AZ fails Automatic ~20-30s failover to synchronous AZ2 replica (zero committed loss). Zoom / Teams platform outage Per-platform circuit breaker pauses retries with backoff; UI shows platform issue. Bug stalls a request past deadline Watchdog SQL (`state_deadline_at < now() - 5m`) alerts SRE & fails visibly.Core trade-offs summarized: Using PostgreSQL
SKIP LOCKED+ partial unique indexes + transactional outbox gives ironclad "zero silent loss" and "zero double assignment" at ~220 tx/s/cell; Redis absorbs the 27,000/s ephemeral heartbeats;20 s / 30 sself-fencing leases plusattempttokens prevent duplicate bots in calls; and single-use containers backed by a schedule-aware warm pool buy clean tenant isolation and sub-30-second joins at:00.
Intuition & how it works
Picture an agency that dispatches human court stenographers to 100,000 live conference calls across a city. When a customer books a stenographer online, three things must go right: you must write the booking in a permanent ledger before handing the customer a confirmation ticket (so no booking is ever forgotten), two dispatchers must never grab the same stenographer for two different calls at the same time, and if a stenographer's taxi breaks down mid-meeting, a backup stenographer must take over using the meeting's saved passcode while ensuring the first stenographer does not wander in late and talk over the replacement.
A naive design breaks on all three counts. Returning "Accepted" after pushing a request onto an in-memory queue loses meetings whenever a server restarts; checking "is Bot 7 idle?" and running "mark Bot 7 busy" in two separate queries lets concurrent servers double-book Bot 7 under load; and immediately spawning a backup bot on a 1-second network hiccup puts two awkward bots inside the same Zoom room. Worse, cold-starting 33,000 headless browsers right at 10:00:00 takes minutes, missing the start of every top-of-the-hour meeting.
Here is how our design handles a booking and a mid-meeting crash step by step:
1. Durable acceptance (t = 0 ms): A user submits zoom.us/j/999 with client Idempotency-Key k-1 (a unique retry token). The API encrypts the passcode in a vault, commits one PostgreSQL transaction writing the QUEUED request (version = 1) plus a transactional outbox row (an event row saved in the same commit so downstream notifications cannot be lost) across two availability zones, and returns 202 Accepted.
2. Atomic allocation (t = 80 ms): A zoom-pool allocator runs SELECT ... FOR UPDATE SKIP LOCKED (locking one waiting Zoom request and one warm IDLE Zoom bot bot-42 while skipping rows locked by other workers), sets attempt = 1 (version = 2), and pushes the assignment to bot-42, which joins and emits JOINED (version = 3) over SSE (Server-Sent Events) to the browser in < 1 s.
3. Self-fenced crash recovery (20 min later): bot-42's VM loses network. After 20 seconds without a heartbeat acknowledgment, bot-42's self-fencing lease expires and it hangs up locally. At 30 seconds, the cell Supervisor sees hb:bot-42 expire in Redis, transitions the request to DISCONNECTED (join_at = now()), and the allocator immediately assigns warm bot-88 with attempt = 2 (a monotonic fencing token).
4. Zombie rejection: bot-88 rejoins using the vaulted passcode in ~10 seconds. If bot-42 ever unfreezes and sends a late packet tagged attempt = 1, both the gateway and audio pipeline see 1 < 2 and drop it immediately.
Key trade-offs
- PostgreSQL
FOR UPDATE SKIP LOCKEDvs. an external message broker for queuing. Keeping waiting requests directly insidebot_requests(queried perpool_idso an empty Zoom pool never head-of-line blocks idle Google Meet bots) means there is only one source of truth, scheduledjoin_attimes are a simple B-tree index scan, and "no silent loss" holds from a single ACID commit. A broker like Kafka handles millions of claims/s, but at ~220 peak transactions/s per cell PostgreSQL is nowhere near saturation and avoids dual-write drift between a broker and the database. - Database transaction + partial unique indexes vs. Redis
SPOPor distributed locks for assignment. Bindingbot_requests,bots, andassignmentsinside one SQL transaction backed by partial unique indexes (UNIQUE (bot_id) WHERE state IN ('OFFERED', 'ACTIVE')) guarantees crash-safe, exactly-once pairing. Popping idle bots from Redis is slightly faster, but a crash betweenSPOPand the database write either leaks bots forever or risks double assignment on Redis failover. - Heartbeat timeout duration (
20 slease /30 sreplacement) vs. faster recovery. Waiting 30 seconds to declare a bot dead plus ~10 seconds for a warm bot to join produces a ~40-second transcript gap on a hard crash. Shrinking the timeout to 8 seconds cuts the crash gap in half, but triggers false replacements whenever a browser hits a brief garbage-collection pause or network blip—and every false replacement creates its own rejoin gap. - Single-use bot containers + forecast warm pool vs. reusing browser containers. Destroying each headless browser container after one meeting guarantees zero cross-customer leakage of cookies, audio buffers, or memory leaks, at the cost of needing ~133,000 simultaneous container slots across VMs at
:00boundaries (33,000 pre-warmed bots for10:00booted before09:00–10:00meetings exit). Forecasting from known scheduledjoin_atrows plus historicalp95ad-hoc traffic keeps idle waste down to ~10 minutes every half-hour instead of paying for a giant static idle pool all day. - Encrypted request-scoped credential storage vs. pure pass-through. Storing passcodes encrypted under cloud KMS keys (redeemed only via short-lived, single-use tickets and wiped on terminal state) adds a high-security vault component, but makes unattended mid-meeting crash replacement possible—whereas pure pass-through forces the meeting recording to die permanently on any bot crash.
- Account-pinned home cells vs. global random load balancing. Routing every request from
account_idto its assigned regional cell lets PostgreSQL enforceIdempotency-Keyuniqueness and one-bot-per-meeting deduplication locally inside one shard. The trade-off is that huge enterprise accounts must be placed on dedicated cells so one tenant cannot overload a shared shard.
Common mistakes
- Returning
202 Acceptedbefore durable multi-AZ persistence. Putting a submitted URL into process memory or an asynchronous fire-and-forget queue before answering202silently loses acknowledged meetings whenever that API pod restarts. - Two-step non-atomic allocation ("read an idle bot, then update it"). Without row locking (
FOR UPDATE SKIP LOCKED) and conditionalWHERE state = 'IDLE'updates, two allocator threads under top-of-hour burst load will assign the exact same idle bot to two different meetings. - Global queue scanning across all platforms without filtering
pool_id. Grabbing the oldest 50QUEUEDrows across all platforms means a surge of unserved Zoom meetings blocks Google Meet and Microsoft Teams meetings behind them even when hundreds of Meet/Teams bots are sittingIDLE. - Replacing bots without fencing tokens or host-removal awareness. Without a monotonic
attempttoken checked on both state reports and audio packets, a paused old bot waking up overwrites the replacement bot'sJOINEDstate withENDEDand mixes duplicate audio; and treatingREMOVED_BY_HOSTas a crash makes bots rudely barge back into meetings the host kicked them out of! - Writing 27,000/s bot heartbeats into PostgreSQL. Ephemeral liveness pings create massive disk write amplification and table bloat in relational databases; store heartbeats in Redis with a
30 sTTL (time-to-live) so only real state changes touch PostgreSQL. - Forgetting to refresh
give_up_aton mid-meetingDISCONNECTEDrecovery. Ifgive_up_atwasstart_time + 10 minand a bot crashes 25 minutes into a call, requeuing with the originalgive_up_atimmediately fails the replacement asNO_CAPACITY. - Sizing compute for average concurrency (~31,000) instead of peak (100,000) plus the
:00warm-pool overlap (~133,000).
Follow-up questions
- How do you guarantee a meeting never gets two bots and a bot never gets two meetings? We prevent double assignment across three layers: submission, database allocation, and runtime fencing. At submission, routing every account to a deterministic home cell lets
UNIQUE (account_id, idempotency_key)absorb client retries and a partial unique index on active(account_id, platform, platform_meeting_id)merge duplicate submissions from teammates into a single request. At allocation, one ACID transaction locks one waiting request and oneIDLEbot viaFOR UPDATE SKIP LOCKED, updates both withWHERE state = ...guards, and inserts intoassignmentswhere partial unique indexes physically forbid two live bots per request or two live requests per bot. At runtime, bots self-fence and hang up if unacknowledged for20 s(before the30 sreplacement fires), and every assignment increments a monotonicattemptfencing token enforced by both the Bot Gateway and Media Ingest Pipeline so stale messages or audio from an old bot are dropped. - Where do conference-provider adapters (such as Zoom, Meet, or Teams) plug into your architecture? Every bot container pairs a platform-agnostic Bot Core (gRPC control stream,
20 slease watchdog, virtual audio device capture, media streaming withattemptheaders) with a pluggable Platform Adapter implementing a uniform interface (parse_url,join,wait_in_lobby,observe_call_events,leave) for Zoom, Google Meet, or Microsoft Teams. Crucially, the adapter translates messy platform-specific DOM/SDK failures into our standard control-plane error taxonomy—separating retryable faults (PLATFORM_5XX,BROWSER_CRASH) from final ones (WRONG_PASSCODE,REMOVED_BY_HOST) so the central Supervisor and Allocator stay 100% platform-blind. Sharingparse_urlwith the Request API rejects unsupported URLs at submission, and partitioning warm pools byplatform:region:adapter_versionlets us canary a hotfix when Zoom changes its web UI (routing 5% of joins first) or trip a per-platform circuit breaker during a Teams outage without impacting other platforms.
Follow-up questions
- How do you guarantee a meeting never gets two bots and a bot never gets two meetings?
- Where do conference-provider adapters (such as Zoom, Meet, or Teams) plug into your architecture?
Similar questions
- Presenting and Justifying a Production Data Pipeline Architecture
- Real-Time Collaborative Document Editor Backend
- Versioned Key-Value Store with Snapshot Commits and Rollover Compaction
- Evaluate Infix Arithmetic Expressions
- Minimum Neighbor-GCD Replacements to Reach All Ones
- Projects Tied for Largest Headcount
More Otter.Ai interview questions
- Real-Time Collaborative Document Editor Backend Medium
- Minimum Neighbor-GCD Replacements to Reach All Ones Medium
- Presenting and Justifying a Production Data Pipeline Architecture Medium Pro
- Evaluate Infix Arithmetic Expressions Medium Pro
- Versioned Key-Value Store with Snapshot Commits and Rollover Compaction Easy Pro
- Projects Tied for Largest Headcount Medium Pro
- Top Earners per Department Medium Pro
- Fixed-Width Line Justification Medium Pro
- Infix Arithmetic Expression Evaluator Medium Pro
- Scoped Key-Value Store Supporting Nested Transactions Medium Pro