Global Customer Support Ticketing Platform
Hard · System Design · Software Engineer · Onsite
Prompt
Design a distributed customer-support ticketing platform for a fast-growing global online service. Customers submit and follow up on support cases via web forms, mobile apps, and inbound email, while globally distributed support specialists handle incoming work matched by real-time availability, language fluency, domain skill, and urgency tier.
Functional Capabilities
- Customer Self-Service: Open new support cases, read current ticket status and conversation threads, and post follow-up messages.
- Specialist Workspace: Claim unassigned cases, send replies, resolve completed issues, or transfer tickets to another queue or specialist.
- Lifecycle & Audit Log: Track canonical ticket states (
New,Assigned,Pending,Resolved) alongside a complete, immutable history of every state transition. - Supervisor Visibility: Power a live operational dashboard displaying active ticket totals across queues, statuses, and regions.
Scale, Workload & Reliability Constraints
- Volume & Incident Surges: Process
500,000tickets per day under normal traffic, with burst headroom to survive sharp multi-fold spikes during major service incidents. - Payload & Access Ratio: Ticket descriptions average
~2 KB, with a5:1read-to-write ratio across the platform. - Latency & Consistency: Keep ticket creation fast for customers and deliver assignment updates with minimal lag to globally distributed specialists; eventual consistency is acceptable for analytics and supervisor counters, whereas ticket ownership requires strong consistency.
- Durability & SLA Enforcement: Guarantee high availability with zero lost tickets once acknowledged, and meet strict response-time SLAs (for example,
< 1 hourtime to first human response on standard cases).
Illustrative Scenario
During a busy afternoon, a Portuguese-speaking user submits a P1 login-lockout case (15-minute first-response SLA) right behind 12,000 low-priority P3 general inquiries, while two available specialists in Lisbon and Sao Paulo click Claim on an older pt/account case (SUP-9K4M2P, version = 1) in the exact same millisecond. Your platform must durably acknowledge the P1 case in milliseconds, route it past the P3 backlog, award SUP-9K4M2P to exactly one specialist while returning a clean conflict to the other, and update live supervisor counts within seconds.
Scope & Expectations
- System Topology: Present an end-to-end architecture decoupling multi-channel durable ticket intake from priority-aware routing, global specialist workspaces, and live supervisor dashboards.
- API Contracts: Define customer submission and read endpoints alongside concurrency-safe specialist claim, reply, state-change, and real-time streaming interfaces.
- Storage Architecture: Justify where relational (
ACID) databases versusNoSQLand object stores fit across mutable ticket state, audit trails, and high-volume unstructured payloads. - Overload & Spike Resilience: Explain rate limiting, load shedding, and incident-burst mitigation so neither server saturation nor duplicate outage floods collapse response SLAs.
Step-by-step walkthrough
Clarify requirements, SLA rules, and scope
At
500,000 tickets/day, raw database throughput is modest (~6 tickets/second on average). What makes a global support system genuinely hard is four correctness and operational constraints:- Zero lost tickets once a customer sees
"Ticket received", even if the database is failing over. - Strict SLAs — here an SLA (Service Level Agreement) is a promised maximum wait time, such as sending a human first response within
1 hour. - Exclusive assignment so two globally distributed agents never work the same ticket at once.
- Outage bursts, where tens of thousands of users report the exact same platform issue within minutes, overwhelming human agent capacity.
Clarifying assumptions to confirm with the interviewer
Question Assumed rule for this design What priority tiers and SLAs exist? P1 Urgent (payment failure, account locked): 15 minfirst response; P2 Standard:1 hour; P3 Low (general how-to):4 hours.What counts as "first response"? The first public message written by a human agent (or an explicitly approved incident broadcast) — never the automated "We received your ticket"email.Push or pull assignment? Both: automated routers push tickets to online agents matching (language, skill), and agents can also manually claim from queues.What does an outage spike look like? Up to +100,000tickets in30 minutes(~10x–15x normal traffic), heavily concentrated in one category.Consistency requirements? Strong consistency for ticket ownership and status; eventual consistency (a few seconds of lag) is fine for supervisor dashboards and analytics. - Zero lost tickets once a customer sees
Back-of-the-envelope numbers: why humans are the real burst bottleneck
Let's turn the prompt's numbers (
500K tickets/day,2 KBdescription,5:1read-to-write ratio) into concrete rates:Ticket ingestion rate Average daily rate 500,000 / 86,400 s = ~5.8 creates/s Normal busy hour (2x avg) ~41,700 / hour = ~11.6 creates/s Outage spike (+100K / 30m) +100,000 / 1,800 s = +55.6 creates/s (~68 creates/s total) Provisioned intake target 1,000 creates/s (~15x outage burst) -> 1,000 x 2 KB = 2 MB/s Transactional writes and reads State writes per ticket ~8 over its lifetime (create, enrich, assign, ack, 2 agent replies, 1 customer reply, resolve) Transactional write rate 500,000 x 8 = 4M writes/day -> ~46 writes/s avg, ~93/s peak hour Read rate (5:1 read:write) 20M reads/day -> ~230 reads/s avg, ~460/s peak hour Storage sizing Structured + message state ~1 KB ticket row + 2 KB description + 3 replies x 2 KB + ~1.6 KB event history = ~10.6 KB / ticket Transactional DB growth 500,000 x 10.6 KB = ~5.3 GB/day (~480 GB for a 90-day hot window) Unstructured logs & payloads Raw emails, webhook bodies, ML classifier traces, delivery logs: ~25 KB/ticket -> ~12.5 GB/day (~4.5 TB/year) Binary attachments Screenshots/PDFs stored directly in object storage (S3) Human agent capacity (the hidden bottleneck!) Agent throughput ~6 tickets/hour (10 minutes per ticket) Agents online at peak hour 41,700 tickets/hr / 6 = ~6,950 concurrent agents globally 100,000-ticket outage burst 100,000 / 41,700 = ~2.4 hours of 100% of ALL online agents!Two insights shape the entire design:
- Database write load (~93 writes/s peak) easily fits on a single PostgreSQL primary with regional read replicas — sharding SQL across dozens of nodes would add complexity for throughput we do not need.
- During an outage, machines survive easily, but human agents cannot. Answering 100,000 duplicate outage tickets one by one takes 2.4 hours of every agent's time, guaranteeing mass SLA breaches unless we detect incidents and group duplicates.
API design for customers, agents, and supervisors
Customer endpoints
POST /v1/tickets Headers Authorization: Bearer <customer_jwt> Idempotency-Key: <client_uuid> # prevents duplicate tickets on network retry Body {"channel": "web" | "mobile", "subject": "Locked out after 2FA reset", "description": "...", # avg 2 KB, max 32 KB "category": "account", # optional user hint "language": "pt", # optional; auto-detected if omitted "attachment_ids": ["att_91a"]} # uploaded beforehand via presigned S3 URLs 202 {"ticket_id": "01JDX4Q8ZK...", "display_id": "SUP-9K4M2P", "status": "RECEIVED"} 429 {"error": "RATE_LIMITED", "open_ticket_id": "SUP-9K4M2P", "retry_after_s": 60} GET /v1/tickets/{ticket_id}?min_version=4 # reads regional replica (falls back to primary if behind) POST /v1/tickets/{ticket_id}/messages {"body": "...", "attachment_ids": []}Inbound emails follow the exact same intake pipeline: an Inbound Mail Worker saves the raw MIME email to object storage, threads replies onto existing tickets via
In-Reply-Toheaders orsupport+SUP-9K4M2P@...addresses, and submits new emails to Intake using the email'sMessage-IDheader as the idempotency key (a unique request identifier that makes retries return the original result instead of creating duplicates).Agent and supervisor endpoints
PUT /v1/agents/me/presence {"state": "AVAILABLE" | "AWAY", "max_concurrent": 5} POST /v1/queues:claim-next {"queues": ["pt/account", "en/account"]} 200 {"ticket": {...}, "version": 2} | 204 (queues empty) POST /v1/tickets/{id}:claim {"expected_version": 1} 200 {"version": 2} | 409 {"error": "ALREADY_ASSIGNED", "assignee_id": 842} POST /v1/tickets/{id}:ack {"expected_version": 2} # confirms agent opened the pushed ticket POST /v1/tickets/{id}/messages {"body": "...", "public": true} # first public reply stamps first_response_at POST /v1/tickets/{id}:set-pending | :resolve | :reassign {"expected_version": 3, ...} WS /v1/agents/me/stream # low-latency push of assignments, customer replies, SLA warnings GET /v1/dashboard/active?group_by=status,queue,region WS /v1/dashboard/stream # 1-second supervisor counter snapshots (eventually consistent)Returning
202 Acceptedon creation decouples user-perceived latency from database maintenance, while requiringexpected_versionon every agent mutation implements optimistic locking (rejecting stale writes cleanly with409 Conflictif another agent modified the ticket first).Data model: SQL for ticket state vs. NoSQL for unstructured logs
A central storage decision is whether ACID relational storage (where ACID means Atomic, Consistent, Isolated, Durable transactions) or NoSQL fits best. The right answer splits mutable transactional state from high-volume unstructured logs:
Workload Chosen store Why this store wins Mutable ticket state, ownership, agent capacity, SLA deadlines, state-change audit history PostgreSQL (1 primary + synchronous standby in a 2nd Availability Zone + regional read replicas) Needs atomic multi-row transactions (claiming a ticket AND incrementing agents.open_counttogether), conditionalversionchecks, and partial B-tree indexes ordered byfirst_response_due_at. At ~93 writes/s peak, one primary handles the load effortlessly.High-volume unstructured logs (raw webhook/email payloads, ML classification debug traces, outbound email/push delivery logs, activity clickstreams) NoSQL wide-column / document store (e.g., DynamoDB / Cassandra keyed by (ticket_id, ts)) + S3 for large blobsAppend-only, schema-flexible, 5x–10x higher write volume than state changes, and never needs multi-row locks. Keeping these out of PostgreSQL prevents buffer-cache pollution and Write-Ahead Log bloat. Full-text ticket search OpenSearch (fed asynchronously from events) Inverted indexes for keyword search across millions of message bodies without LIKE '%...%'scans on PostgreSQL.Live agent presence & dashboard counters Redis Sub-millisecond 15-second heartbeat TTLs and atomic HINCRBYsupervisor counters.PostgreSQL schema and lifecycle invariants
CREATE TABLE tickets ( ticket_id TEXT PRIMARY KEY, -- ULID (time-sortable 128-bit unique ID) display_id TEXT UNIQUE NOT NULL, -- human-friendly code e.g. 'SUP-9K4M2P' customer_id BIGINT NOT NULL, channel TEXT NOT NULL, -- 'web' | 'mobile' | 'email' subject TEXT NOT NULL, category TEXT, language TEXT, priority SMALLINT NOT NULL, -- 1 (15m SLA), 2 (1h SLA), 3 (4h SLA) status TEXT NOT NULL, -- 'NEW' | 'ASSIGNED' | 'PENDING' | 'RESOLVED' routing_state TEXT NOT NULL, -- 'UNROUTED' | 'QUEUED' | 'DEAD_LETTERED' queue_id TEXT, -- e.g. 'pt/account' assignee_id BIGINT, incident_id BIGINT, -- links duplicate tickets during an outage version INT NOT NULL DEFAULT 1, created_at TIMESTAMPTZ NOT NULL, assigned_at TIMESTAMPTZ, acked_at TIMESTAMPTZ, first_response_due_at TIMESTAMPTZ NOT NULL, first_response_at TIMESTAMPTZ, resolved_at TIMESTAMPTZ, CHECK (status <> 'NEW' OR assignee_id IS NULL), CHECK (status <> 'ASSIGNED' OR assignee_id IS NOT NULL) ); -- Partial indexes keep the working set tiny (only open/unanswered tickets are indexed!) CREATE INDEX idx_queue_edf ON tickets (queue_id, first_response_due_at) WHERE status = 'NEW'; CREATE INDEX idx_sla_watch ON tickets (first_response_due_at) WHERE first_response_at IS NULL AND status IN ('NEW', 'ASSIGNED'); CREATE TABLE agents ( agent_id BIGINT PRIMARY KEY, home_region TEXT NOT NULL, languages TEXT[] NOT NULL, skills TEXT[] NOT NULL, max_concurrent INT NOT NULL DEFAULT 5, open_count INT NOT NULL DEFAULT 0 CHECK (open_count >= 0) -- exact count of ASSIGNED tickets ); CREATE TABLE ticket_messages ( message_id TEXT, ticket_id TEXT, author_type TEXT, author_id BIGINT, is_public BOOLEAN, body TEXT, created_at TIMESTAMPTZ ) PARTITION BY RANGE (created_at); CREATE TABLE ticket_events ( ticket_id TEXT, version INT, event_type TEXT, actor_id BIGINT, from_status TEXT, to_status TEXT, payload JSONB, created_at TIMESTAMPTZ, PRIMARY KEY (ticket_id, version, created_at) ) PARTITION BY RANGE (created_at); CREATE TABLE idempotency_keys ( customer_id BIGINT, idem_key TEXT, ticket_id TEXT, body_hash BYTEA, created_at TIMESTAMPTZ, PRIMARY KEY (customer_id, idem_key) ); CREATE TABLE outbox (id BIGSERIAL PRIMARY KEY, topic TEXT, msg_key TEXT, payload JSONB);Ticket status state machine (every transition bumps `version` + writes `ticket_events` + `outbox`): assign / claim agent waits on user customer replies NEW -----------------> ASSIGNED -----------------------> PENDING -------------------+ ^ | | | | unacked > 2 min OR | | agent resolves customer reopens (<= 7d) | +-- reassign to queue --+ +---------------> RESOLVED ---------------------------+ | (returns to ASSIGNED on same owner, or NEW if offline)Notice the strict invariant on
agents.open_count: it always equals that agent's exact count ofASSIGNEDtickets. MovingASSIGNED -> PENDING,RESOLVED, orNEWdecrementsopen_countby1. When a customer replies to aPENDINGticket (PENDING -> ASSIGNED), we incrementopen_countby1without enforcing< max_concurrent(so the customer stays with the agent who already knows their issue, while naturally pausing new assignments to that agent until they clear their active load).High-level architecture
Web / Mobile Clients Inbound Email (MX) | | | +--------v---------+ | | Mail Parser |--> Raw MIME to S3 + NoSQL logs | +--------+---------+ v v +-------------------------------------------------------------+ | Regional Intake API (Auth, Rate Limit, Redis Idempotency, | | Fast Rule Pre-Triage -> generates ULID + leased display_id) | +-----------------------------+-------------------------------+ | Kafka produce (acks=all, 3 AZs) +----------------+----------------+ v v v [intake.p1] [intake.p2] [intake.p3] <-- Priority-isolated topics | | | v v v +-------------------------------------------------------------+ +-----------------------+ | Dedicated P1 / P2 / P3 Writer + Enricher Worker Pools | | Ticket Command Svc | | - Idempotent DB insert; language/category/SLA enrichment | | (claim, reply, state) | +-----------------------------+-------------------------------+ +-----------+-----------+ | | +------------------------+------------------------+ v +---------------------------+ NoSQL Log Store <------------------------| PostgreSQL Primary |---> Regional Read Replicas (raw payloads, ML traces, delivery logs) | + Sync Standby (2nd AZ) | (US, EU, APAC) +-------------+-------------+ | WAL / CDC Outbox Relay (Debezium) v [Kafka: ticket-events] +------------+------+------+-------------+ v v v v +------------+ +----------+ +-----------+ +------------+ | Queue | | SLA | | Dashboard | | Search & | | Routers | | Monitor | | Counter | | Analytics | | (EDF+CAS) | | (DB scan)| | (Redis) | | Consumers | +-----+------+ +----------+ +-----+-----+ +------------+ | | v v +-----------------------------------------------+ | Regional WebSocket Gateways (US, EU, APAC) | +-----------------------------------------------+Here an AZ (Availability Zone) is an isolated data center with independent power and networking inside a cloud region, and a transactional outbox is a table written inside the exact same SQL transaction as
ticketsand tailed from PostgreSQL's WAL (Write-Ahead Log) via CDC (Change Data Capture) so downstream Kafka consumers never miss a database commit or see uncommitted events.Deep dive 1: Zero-loss intake and priority-bypass queues
Log-first durability. Writing straight to PostgreSQL from
POST /v1/ticketswould expose customers to database failovers (~30–60 seconds) and outage connection spikes. Instead, the Intake API executes five fast steps in< 15 ms:- Validate auth, enforce payload size (
<= 32 KB), and check per-customer token-bucket rate limits (e.g., max 5 new tickets/minute). - Generate a ULID (Universally Unique Lexicographically Sortable Identifier — a 128-bit ID combining a timestamp with 80 random bits) for
ticket_id, allocate a collision-free humandisplay_idfrom a pre-leased block of 10,000 sequence numbers in memory, and assign an initial priority (P1,P2,P3) from fast rules (enterprise plan,"account compromised"category). - Claim
idem:{customer_id}:{key}in Redis (SET ... NX EX 30asPENDINGwith body hash). - Append the payload to Kafka topic
intake.p1,intake.p2, orintake.p3withacks=allacross 3 AZs (min.insync.replicas = 2). - Mark the Redis idempotency key
DONE(EX 86400), cache a lightweightRECEIVEDstub in Redis for 60 minutes (so immediate customerGETcalls succeed before the DB write lands), and return202 Accepted.
The Writer Worker then inserts into
idempotency_keysandticketsinside one SQL transaction usingON CONFLICT DO NOTHINGbefore committing its Kafka offset. Because Kafka guarantees at-least-once delivery and PostgreSQL deduplicates retries via(customer_id, idem_key)andticket_id, zero acknowledged tickets can be lost or duplicated.Priority-bypass worker pattern. A single FIFO (first-in, first-out) Kafka topic would trap a
P1locked-account ticket behind80,000P3tickets during a spike. Splitting intake intointake.p1,intake.p2, andintake.p3with dedicated consumer pools guarantees that an over-provisionedP1worker pool drains urgent tickets into routable state in< 1 second, completely unaffected byP3lag. ML language/category enrichment also runs with a tight timeout (200 ms) and fails open to rule-based defaults if the model service slows down.- Validate auth, enforce payload size (
Deep dive 2: SLA-aware routing and race-free ticket assignment
Ordering within each
(language, skill)queue: Earliest Deadline First (EDF). Every ticket getsfirst_response_due_at = created_at + SLA_window(+15mfor P1,+60mfor P2,+240mfor P3). OrderingNEWtickets byfirst_response_due_at ASCnaturally puts a brand-newP1(due in 15m) ahead of a brand-newP2(due in 60m), while also rescuing a 3-hour-48-minute-oldP3(due in 12m) before it breaches! Pure strict priority (P1 > P2 > P3regardless of age) starvesP3indefinitely during busy afternoons.Why naive assignment double-assigns, and how atomic CAS prevents it:
Naive broken flow (SELECT then UPDATE): Atomic conditional UPDATE (CAS): t1: Agent A reads ticket #9 (status='NEW', v=1) t1: Agent A runs UPDATE ... WHERE status='NEW' AND v=1 t2: Agent B reads ticket #9 (status='NEW', v=1) t2: Agent B runs UPDATE ... WHERE status='NEW' AND v=1 t3: Agent A sets assignee=A -> 200 OK t3: PostgreSQL row lock lets A commit (v becomes 2)! t4: Agent B sets assignee=B -> 200 OK (OVERWRITES!) t4: B unblocks, re-checks WHERE (status='ASSIGNED', v=2), Both agents now write replies to the customer! updates 0 rows -> ROLLBACK -> clean 409 Conflict!Both automated push routers and manual agent claims execute the exact same single-primary SQL transaction:
BEGIN; -- Step 1: Atomically claim the ticket ONLY if still NEW at expected_version UPDATE tickets SET status = 'ASSIGNED', assignee_id = :agent_id, assigned_at = now(), version = version + 1 WHERE ticket_id = :ticket_id AND status = 'NEW' AND version = :expected_version; -- Step 2: Atomically reserve 1 capacity slot on the agent (if either touches 0 rows -> ROLLBACK!) UPDATE agents SET open_count = open_count + 1 WHERE agent_id = :agent_id AND open_count < max_concurrent; INSERT INTO ticket_events (ticket_id, version, event_type, actor_id, from_status, to_status, created_at) VALUES (:ticket_id, :expected_version + 1, 'ASSIGNED', :agent_id, 'NEW', 'ASSIGNED', now()); INSERT INTO outbox (topic, msg_key, payload) VALUES ('ticket-events', :ticket_id, :event_json); COMMIT;For
"Claim Next"(POST /v1/queues:claim-next), the query selects the earliest-due ticket usingFOR UPDATE SKIP LOCKED(a PostgreSQL clause that skips rows currently being locked by another concurrent transaction instead of waiting in line), so 50 agents clicking "Claim Next" simultaneously grab 50 different tickets with zero lock contention. And if a pushed ticket is not acknowledged (:ack) within2 minutesor the agent's 45-second Redis presence TTL expires, a reaper transaction returns the ticket toNEWpreserving its originalfirst_response_due_atso it stays at the very front of the queue.Database-backed SLA Monitor. Separate from Kafka events, an SLA Monitor scans the tiny
idx_sla_watchpartial index every30 seconds:- 50% of SLA elapsed and still
NEW: widen routing eligibility to secondary-language and cross-region overflow agents. - 80% of SLA elapsed: push urgent alerts to queue supervisors and allow
+1burst overmax_concurrent.
Global agent latency. Agents in US, EU, and APAC hold persistent WebSockets to their nearest regional gateway; assignments fan out from
ticket-eventsin< 250 ms. Clicking "Claim" or "Reply" crosses the ocean once (~80–200 msround trip to the primary), which feels instantaneous for human UI actions while preserving single-primary consistency.- 50% of SLA elapsed and still
Deep dive 3: Load shedding, category spikes, and incident grouping
We separate machine overload from human agent overload:
1. Machine load shedding (shed non-critical work, never drop tickets)
- Bulkheads (isolated resource pools so a failure or flood in one component cannot sink another): separate API deployments for customer traffic vs. agent workspace traffic, plus separate Kafka consumer pools for
P1,P2, andP3. - Priority shedding ladder when CPU or DB utilization crosses 75%:
- Pause analytics warehouse consumers and slow supervisor dashboard pushes from
1sto10s. - Delay search indexing and non-urgent outbound email notifications (Kafka buffers them safely).
- Bypass ML classification for
P2/P3tickets (use zero-cost form/keyword rules). - Apply adaptive concurrency limits (
503 Retry-After) on customer ticket-list polling (GET /v1/tickets), while keepingPOST /v1/ticketsintake and all Agent APIs 100% open.
- Pause analytics warehouse consumers and slow supervisor dashboard pushes from
2. Human overload during outage spikes (incident grouping & deflection)
When a broken checkout deploy triggers
100,000billing tickets in 30 minutes:- Automated spike detection: A streaming job tracks 5-minute arrival rates per category against historical baselines; a
>= 5xsurge combined with text-embedding/keyword clustering opens a candidateincident_idand pages supervisors. - Pre-submission banner deflection: The web/mobile help center immediately renders
"We're aware of a billing issue — subscribe for live updates", deflecting half the tickets before creation. - Group once, reply to thousands: Incoming matching tickets are tagged with
incident_idand routed to a dedicated Incident Queue capped at at most 30% of generalist agent capacity — insulating unrelatedP1/P2queues from starvation! When an incident lead writes one verified update, a fanout worker posts that human message across all linked tickets.
- Bulkheads (isolated resource pools so a failure or flood in one component cannot sink another): separate API deployments for customer traffic vs. agent workspace traffic, plus separate Kafka consumer pools for
Multi-region scaling, failure handling, and trade-off summary
Failure mode System recovery Primary DB AZ goes down Synchronous standby in AZ-2 has zero-data-loss commits and promotes in ~30–45 s; Intake keeps returning 202via Kafka the entire time.Queue Router crashes Kafka consumer group rebalances owned queues to surviving routers in seconds, which rebuild their EDF heaps from idx_queue_edf.Poison message / unroutable ticket Retried with priority-scaled backoff ( 10s/30sfor P1 vs1m/5mfor P3), then markedrouting_state = 'DEAD_LETTERED'on a live supervisor escalation board so its SLA is still tracked.Supervisor Redis counter drift Every 5 minutes, a background query ( SELECT status, queue_id, COUNT(*) ...on a read replica) reconciles Redis counters to exact truth.10x long-term company growth or EU data residency Partition into regional cells (US, EU, APAC), each with its own Intake, Kafka, and PostgreSQL primary; cross-region overflow agents route to the ticket's home cell. Core trade-offs summarized:
- Kafka-first
202intake vs. synchronous SQL insert: Survives DB failovers and 1,000-req/s spikes with< 15 mswrite latency, trading off a< 1sasync persistence gap masked by a Redis intake stub. - PostgreSQL for ticket state + NoSQL for unstructured logs: Gives rock-solid ACID conditional assignment and deadline indexes where needed while keeping multi-terabyte raw payloads and traces off the transactional primary.
- Earliest Deadline First + priority topics + 30% incident cap: Prevents
P3starvation in normal load, keepsP1fast in the pipeline, and stops a single category outage from collapsing company-wide SLAs.
- Kafka-first
Intuition & how it works
Picture this support platform as a hospital emergency-room triage system. First, the front window immediately stamps a durable wristband (202 Accepted into a replicated log) for every arriving patient so nobody is ever turned away even if examination rooms are full. Second, chest-pain emergencies (P1) go through a dedicated express door that bypasses the routine waiting-room line (P3). Third, every patient chart sits in a single authoritative slot where grabbing a chart requires flipping its lock tag atomically, making it physically impossible for two doctors to claim the same patient. Finally, if 500 people arrive from the same stadium food-poisoning outbreak, staff group them under one shared outbreak response instead of running 500 isolated intakes while unrelated emergencies wait.
A naive design inserts tickets directly into a database during the HTTP request, pushes every ticket into a single first-in-first-out queue, and assigns work by running SELECT to check if status = 'NEW' followed by UPDATE. That breaks under real-world conditions: a 30-second database failover drops customer submissions, an outage backlog of 50,000 low-priority tickets buries urgent locked-account requests past their 15-minute SLA (Service Level Agreement, the promised maximum response time), and two agents reading status = 'NEW' in the same millisecond overwrite each other and send conflicting replies.
Trace our busy-afternoon scenario alongside two specialists (Carla in Lisbon and Diego in Sao Paulo):
- Durable intake + priority bypass: Right behind
12,000queuedP3general inquiries, a Portuguese-speaking customer submits aP1login-lockout case (C_urgent). The Intake API generates a unique ULID (time-sortable unique ID), replicates the payload across 3 Availability Zones (isolated data centers) in Kafka topicintake.p1, and returns202 Acceptedin12 ms. Even whileintake.p3drains12,000routine inquiries, the dedicatedP1worker pool commitsC_urgentinto PostgreSQL within200 mswithfirst_response_due_at = now + 15m. - Earliest-Deadline-First (EDF) routing: Inside queue
pt/account, olderP3ticketSUP-9K4M2P(filed 3 hours 50 minutes ago,due in 10m) sits ahead ofC_urgent(due in 15m), preventing agingP3tickets from starving while keepingP1far ahead of freshP2/P3work. - Race-free claim: Carla and Diego both click Claim on
SUP-9K4M2P(version = 1) in the exact same millisecond. Both executeUPDATE tickets SET status='ASSIGNED', version=2 ... WHERE ticket_id='01JDX...' AND status='NEW' AND version=1. PostgreSQL's row lock serializes them: Carla commits (versionbecomes2andopen_countincrements), while Diego'sWHEREclause matches0 rows, rolls back, and returns a clean409 Already Assigned.
Key trade-offs
- Kafka-first
202intake vs. synchronous database writes. Acknowledging a ticket as soon as Kafka replicates it across 3 Availability Zones (acks=all) insulates ticket creation from database failovers and traffic spikes. The trade-off is a sub-second window before the PostgreSQL row exists, which we bridge with a short-lived Redis intake record so immediate"View my ticket"reads still succeed. - PostgreSQL (ACID) for ticket state vs. NoSQL for unstructured logs. Storing mutable tickets, agent
open_count, and SLA deadlines in PostgreSQL gives atomic multi-row transactions and partial deadline indexes (WHERE status = 'NEW') for ~93 peak writes/second, while offloading multi-terabyte raw MIME emails, webhook payloads, and ML traces to a NoSQL store (such as DynamoDB or Cassandra) and object storage keeps heavy append-only logs from bloating SQL memory and replication. - Single-primary SQL region (or regional cells) vs. multi-master writes. Routing state mutations for a ticket to one authoritative PostgreSQL primary turns "never double-assign" into one conditional
UPDATEwithout fragile distributed lock servers. Remote agents pay one cross-region network hop (~80–200 ms) when clicking"Claim"or"Reply", while reading locally from regional replicas and receiving sub-second WebSocket pushes. - Earliest Deadline First (EDF) + separate priority intake topics vs. strict priority. Separate Kafka topics (
intake.p1/p2/p3) prevent ingestion head-of-line blocking, while ordering routable queues byfirst_response_due_atpreventsP3starvation during normal load. Because EDF alone degrades when total arrivals exceed human staffing, we pair it with automated incident grouping during outages. - Event-driven routing + periodic database SLA sweeps. Driving routers from a transactional outbox (events written in the same SQL transaction and streamed from the Write-Ahead Log) gives sub-second assignment, while a 30-second SQL scan over
idx_sla_watchacts as an independent safety net so a dropped consumer or dead-lettered ticket can never silently breach its SLA.
Common mistakes
- Over-engineering database sharding for ~6 creates/second while completely missing that a 100,000-ticket outage burst overwhelms human agent hours, not SQL IOPS.
- Returning
200 OKfrom an in-memory queue oracks=1broker, losing acknowledged customer tickets when a single server or broker crashes. - Putting
P1,P2, andP3into one shared FIFO queue, letting a flood of low-priority questions delay urgent account-recovery tickets past their 15-minute SLA. - Using
SELECTfollowed by an unconditionalUPDATE(or TTL-based Redis locks alone) for claiming, allowing race conditions or garbage-collection pauses to assign two agents to one ticket. - Decrementing
agents.open_countonPENDINGwithout incrementing it again when a customer replies (PENDING -> ASSIGNED), causingopen_countto drift negative and break agent concurrency limits. - Shedding
POST /v1/ticketsor agent APIs during load spikes instead of shedding analytics, search indexing, dashboard refresh rate, and non-urgent emails first. - Counting an automated receipt email as the "first response", hiding real SLA breaches from supervisors.
- Sending dead-lettered tickets into an unmonitored Kafka topic where their SLA clock expires unseen.
Follow-up questions
- How would you handle dead-letter routing so tickets that fail automated assignment never sit unnoticed until their SLA expires? Tickets fail automated routing either from transient processing errors (enrichment/router exceptions) or from structural mismatches (an unsupported language, a deleted skill queue, or repeated unacknowledged agent pushes). Transient failures route through priority-scaled retry topics so backoff never eats the SLA (
10s -> 30s -> 60sfor a 15-minuteP1, versus1m -> 5m -> 15mfor a 4-hourP3), while structural mismatches or exhausted retries publish to a dead-letter queue (DLQ) and update PostgreSQL torouting_state = 'DEAD_LETTERED'with an error reason. Crucially, the ticket never disappears into Kafka: it surfaces immediately on a supervisor"Needs Manual Triage"dashboard, remains visible to the 30-second SLA Monitor (which auto-widens routing to a fallback English + machine-translation queue before breach), triggers PagerDuty if anyP1enters the DLQ, and supports safe one-click replay thanks to our idempotentversion-checked updates. - When one issue category suddenly surges 10x during a platform incident, what rate-limiting, load-shedding, and grouping controls keep both servers and other queues healthy? On the infrastructure side, 10x peak traffic (~120 creates/second) is well within our pre-provisioned
1,000 creates/secondKafka intake, so we never drop new tickets; instead we enforce per-customer token-bucket rate limits (429pointing repeat submitters to their open ticket), isolate customer vs. agent API pools (bulkheads), apply adaptive concurrency limits on read-heavy endpoints, and shed low-priority background work first (pause warehouse consumers, slow dashboard pushes to 10s, skip ML enrichment onP3). On the human-capacity side — where a 10x spike in"account"or"billing"would otherwise starve every other category — a streaming anomaly detector spots the>= 5xsurge + text similarity, posts a known-issue deflection banner on the submission form, links matching tickets under oneincident_idfor single-click mass agent updates, and caps the incident queue at 30% of generalist agents so unrelatedP1/P2queues keep meeting their SLAs. - How do you guarantee exclusive ticket ownership so two concurrent agents or routing workers never claim the same ticket? Every ticket belongs to one authoritative PostgreSQL primary (globally at current scale, or within its home regional cell at 10x scale), and both automated push routing and manual agent claims execute the same compare-and-swap (CAS) transaction:
UPDATE tickets SET status='ASSIGNED', assignee_id=:agent, version=version+1 WHERE ticket_id=:id AND status='NEW' AND version=:v, paired in the same transaction withUPDATE agents SET open_count=open_count+1 WHERE agent_id=:agent AND open_count < max_concurrent. PostgreSQL's row-level lock serializes simultaneous attempts on the same row: the first transaction commits and bumpsversion, so the second transaction re-evaluatesWHERE, matches zero rows, rolls back cleanly, and returns409 Conflict(while"Claim Next"queries useFOR UPDATE SKIP LOCKEDso concurrent agents automatically grab distinct tickets without colliding). Partitioning queues across single-owner router instances minimizes wasted retries in the common case, while the database conditional update guarantees strict exclusivity even during Kafka consumer rebalances or network partitions.
Follow-up questions
- How would you handle dead-letter routing so tickets that fail automated assignment never sit unnoticed until their SLA expires?
- When one issue category suddenly surges 10x during a platform incident, what rate-limiting, load-shedding, and grouping controls keep both servers and other queues healthy?
- How do you guarantee exclusive ticket ownership so two concurrent agents or routing workers never claim the same ticket?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System