Five Backend Designs: Callbacks, Geo Search, Chat, Pipelines, Payments
System DesignModel answerLast updated
Sketch five independent large-scale backends in one time-boxed session: event callbacks, nearby-place search, team messaging, a CI/CD engine, and payment processing.
Overview
You have one onsite-style session to sketch five unrelated backend systems. Breadth and judgment matter more than completeness. For each system, give a crisp design, name its dominant bottleneck, and spend your time on the one or two hardest trade-offs. Reuse patterns across systems only where they genuinely fit.
For every system, be ready to cover:
- Requirements, stated assumptions, and the back-of-the-envelope numbers behind your choices
- Main components and how they fit together
- Data model and storage choices
- How you reach the scale, availability, and latency targets
- How you handle failure, retries, and consistency
Before designing, state each system's read/write ratio and its dominant bottleneck. You may simplify, but say so.
Questions to raise up front
- How deep should each system go? If forced to pick, where should you go deepest?
- For each system, which axis matters most: throughput, tail latency, durability, or cost?
- Where must correctness beat availability (no lost events, no double charges), and where may the system degrade?
- What is the read/write ratio, and is eventual consistency acceptable on reads?
- Is a single region enough for a first pass, or is multi-region required?
System 1: Event-triggered callback (webhook) delivery
Clients register a subscription that maps an eventId (string or number) to one callback URL. Each eventId maps to exactly one URL. When an event fires, the system sends an HTTP request carrying the event data to that URL. Clients can query per-event delivery status: success, failure, and the history of retry attempts.
- Scale: up to 1 billion events/day (about 11.6k/s on average, with peaks of 3-5x).
- Accepted events must never be silently lost. At-least-once delivery is fine, and receivers dedupe with idempotency.
- Delivery within a few seconds is acceptable.
- Multi-tenant, with only authorized clients allowed to manage their own subscriptions.
Cover APIs, storage, ingestion, dispatch workers, retries, and monitoring.
System 2: Nearby places search
Build a service that manages and searches places worldwide. Each place has id, name, location (lat/lon), place_type, and optional metadata (rating, address, hours).
- Create, update, and delete places.
- Search by user location and place type, returning the N closest places, optionally within a maximum radius. Rank mainly by distance, with secondary signals such as rating.
- Hundreds of millions of places, high read volume, p95 search latency under 100 ms.
- Writes may take a while to become visible.
Cover storage, geospatial indexing, type and attribute filtering, global sharding and replication, hotspots, and caching.
System 3: Team messaging
Design a messaging platform with 1:1 and group conversations.
- Send messages, create groups, add and remove members (keep permissions simple).
- Notify recipients of new messages.
- Support images and other media, stored efficiently outside the main message store.
- Let users delete their own messages. Clarify whether that means delete-for-everyone or hide-for-self.
- Many concurrent users, near-real-time delivery to online users, durable and queryable history, and graceful handling of reconnecting clients.
Cover the services, how real-time connections work, the data model, message versus media storage, per-conversation ordering and reliability, and deletion.
System 4: Distributed CI/CD workflow engine
Design an engine that reacts to repository events (push, pull request opened, tag created, schedule) by running workflows defined as config files (e.g. YAML) stored in the repo itself.
- Detect events and map them to workflows.
- Create a run with multiple jobs and steps, and schedule jobs onto a distributed pool of container or VM runners.
- Manage the run lifecycle: queueing, execution, retries, timeouts, cancellation. Store logs and artifacts, and report status back to the git host.
- Multi-tenant, with tens to hundreds of thousands of concurrent runs, fair scheduling and rate limiting across orgs, and strong isolation between workflows.
Cover event ingestion, locating and parsing the config from the triggering commit, orchestration and job dependencies, runner infrastructure, storage, scaling, and failure handling.
System 5: Payment processing
Design a payment processing backend that accepts charge requests from merchants, talks to external payment providers, and records the outcome. Correctness dominates here: no double charges and no unrecorded money movement. Cover the API, idempotency, the ledger and data model, handling provider timeouts and failures, reconciliation, and security.
Hints
Hint 1
Use the same skeleton for every system: requirements, rough numbers, components, data model, failure handling. Then pick the single hardest trade-off in each (retry policy, geo index choice, ordering, fair scheduling, double-charge prevention).
Hint 2
Look for shared primitives: a durable partitioned log plus worker fleet (callbacks, chat fan-out, CI jobs), idempotency keys (callbacks, payments), and per-tenant quotas (callbacks, CI, payments). Do not force a fit where eventual consistency is fine, as in place search.
Hint 3
For geo search, index by cell (geohash, S2, or H3), scan the target cell and its neighbors, then re-rank by exact distance. For chat, partition by conversation ID so ordering and history fall out naturally. For payments, write the ledger and an outbox entry in one transaction and make every external call idempotent.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
How to run the session
Open with the clarifying questions, then give each system roughly the same skeleton: requirements and numbers, components, data model, hardest trade-off, failure handling. Say aloud where you would go deeper with more time.
1. Callback delivery
Numbers. 11.6k events/s average and about 60k/s at peak. At ~1 KB per event that is roughly 1 TB/day of raw payload, so retention of a few days is affordable.
Flow. The ingest API authenticates the tenant, validates the event, and writes it to a partitioned replicated log (Kafka-style), keyed by eventId. It acknowledges only after the write is durable, which gives accept-then-dispatch. A lookup of eventId → URL happens in the dispatcher, using a cache in front of the subscription DB.
Dispatch. Stateless workers consume partitions, POST to the URL with a short timeout (e.g. 5 s), and record the result. Per-destination concurrency limits and circuit breakers stop one slow receiver from starving others. Slow endpoints are moved to a separate lane so they cannot block healthy ones.
Retries. Use exponential backoff with full jitter (e.g. 1 s, 5 s, 30 s, 5 min, up to hours), with a max-attempts or TTL cap. Implement delays through delay-tier topics or a scheduled-retry store rather than sleeping in workers. After the cap, the event goes to a dead-letter queue with an admin requeue endpoint.
Data. Subscriptions live in a relational or KV store (tenant_id, eventId, url, secret). Delivery attempts live in a wide-column or KV store keyed by eventId (attempt number, status code, latency, error, terminal state) with TTL.
Security. Per-tenant authz, HTTPS-only URLs, SSRF protection (block private IP ranges, re-resolve DNS at connect time), an HMAC signature header with timestamp to resist replay, and a stable delivery-id header so receivers can dedupe.
Monitoring. Track lag per partition, success rate per tenant and per endpoint, p99 delivery latency, and DLQ depth. Alert on lag growth.
Common mistakes. Acknowledging before persisting; retrying in-process and losing state on crash; unbounded retries against a dead endpoint; claiming exactly-once.
2. Nearby places search
Split stores. A source-of-truth DB (sharded by place ID) handles writes. A read-optimized geo index is updated asynchronously through a change stream. The relaxed write-visibility requirement justifies this eventual consistency.
Index. Use S2, H3, or geohash cells at a fixed level (e.g. cells of roughly 1-5 km). Index key is (place_type, cell_id), with values holding place ID, coordinates, and rating. A query computes the cell covering the user's radius, fetches those plus neighbors, filters by exact haversine distance, and ranks by distance with rating as a tiebreaker or blend. If too few results come back, expand to the next ring of cells. A quadtree with adaptive depth is an alternative for uneven density.
Scale. 300M places at ~200 bytes of index data is about 60 GB, which is small. The challenge is query rate, not size. Shard by region or cell prefix, replicate read-only copies per region, and route users to the nearest region via geo DNS.
Hotspots. City centers produce dense cells. Use adaptive cell levels (split dense cells), cache hot cell results in memory with short TTLs, and cache full query results keyed by (rounded location, type). Rounding location to a cell is what makes caching effective.
Trade-offs. Geohash has edge distortions at cell borders and poles and needs the neighbor-cell lookup. S2 and H3 handle these better. Always re-rank by exact distance, because cell membership is only a candidate filter.
Common mistakes. Using a plain lat/lon B-tree range query; forgetting neighbor cells at borders; making writes synchronous to the index.
3. Team messaging
Architecture. Clients keep a WebSocket to a stateless gateway tier that handles auth, heartbeats, and presence. A routing layer (a session registry in Redis mapping user to gateway) lets any service push to a user. A chat service handles send, membership, and history APIs.
Send path. Persist first, then publish. The chat service writes the message to the store with a per-conversation monotonically increasing sequence number, then publishes an event to a log keyed by conversation_id. Fan-out workers push to online members through their gateways. For offline members they update unread counts and send a mobile push notification. Clients dedupe by message ID (client-generated) and detect gaps via the sequence number, then fetch missing messages on reconnect using "messages after seq N".
Data model. messages(conversation_id, seq, sender_id, body, media_id, created_at, deleted) in a wide-column store partitioned by conversation_id and clustered by seq, which gives ordering and cheap paginated history. Separate tables hold conversations, memberships(user_id, conversation_id, last_read_seq), and users. Large groups use fan-out on read for unread state instead of per-member writes.
Media. The client requests a pre-signed URL, uploads directly to object storage, and sends a message referencing the media ID. A CDN serves downloads, and a background job generates thumbnails and scans for malware.
Deletion. Support delete-for-everyone as a tombstone (deleted=true, body cleared), emitted as a message-update event so connected clients remove it in real time and later history fetches return the tombstone. Hide-for-self is a per-user marker. Mention retention or compliance constraints that may require hard deletion of the content and media later.
Common mistakes. Tying ordering to wall-clock timestamps; pushing before persisting; storing media blobs in the message DB.
4. CI/CD engine
Ingestion. Git host webhooks land in a queue. A trigger service resolves the commit, fetches the workflow files from that exact SHA, parses and validates them, matches trigger filters (branch, path, event type), and creates a run record.
Orchestration. The run is a DAG of jobs. A state machine per run (queued, running, succeeded, failed, cancelled) persists in a transactional store. When a job finishes, the orchestrator checks dependencies and enqueues newly ready jobs. All transitions are idempotent and driven by events so the orchestrator is restartable.
Scheduling. Jobs enter per-org queues. A scheduler pulls using weighted fair queuing with per-org concurrency quotas and rate limits, so one tenant cannot starve others. Runners register with labels (OS, size) and lease jobs with a heartbeat. A missed heartbeat re-queues the job, and job steps must tolerate re-execution.
Isolation. Ephemeral microVMs (e.g. Firecracker) or hardened containers per job, no shared state, scoped short-lived secrets, and egress controls. Untrusted fork PRs get no secrets.
Storage. Run metadata in a relational DB (sharded by org). Logs streamed in chunks to object storage with a live-tail path through a pub/sub channel. Artifacts and caches in object storage with TTLs.
Failure handling. Per-job timeouts, bounded automatic retries for infrastructure failures (not for test failures), cancellation propagated through the lease channel, and status reported back to the git host with retry on API failure.
5. Payments
Principle. Correctness over availability. A request should fail or pend rather than risk a double charge.
API. POST /payments requires an Idempotency-Key. The service stores (merchant, key) → request hash, response under a unique constraint. A replay returns the stored result, and the same key with a different body is rejected.
State machine. created → authorizing → authorized → captured (or failed, refunded). Transitions are persisted before and after each provider call, with the provider call using its own idempotency key derived from the payment ID.
Ledger. An append-only double-entry ledger (debit and credit rows that must sum to zero) in a strongly consistent relational DB, never updated in place. Balances are derived or maintained transactionally. Writes that must trigger downstream work (webhooks, emails) go to an outbox table in the same transaction, and a relay publishes them to the log.
Timeouts. If the provider call times out, the outcome is unknown. Mark the payment pending, then resolve it by querying the provider with the same idempotency key, or wait for the provider webhook. Never blindly retry with a new key.
Reconciliation. A daily job compares the ledger against provider settlement files and flags mismatches for review.
Security. Do not store raw card data. Use tokenization via the provider or a PCI-scoped vault, TLS everywhere, per-merchant API keys with scopes, rate limits, and audit logs.
Common mistakes. Treating a timeout as a failure; updating balances without a ledger; writing to the DB and the queue separately without an outbox.
Cross-cutting summary
| System | Dominant bottleneck | Consistency stance |
|---|---|---|
| Callbacks | Dispatch throughput, slow receivers | Durable, at-least-once |
| Place search | Read QPS, hot cells | Eventual |
| Chat | Connections, fan-out | Per-conversation ordering |
| CI/CD | Runner capacity, fairness | Strong run state |
| Payments | Correctness | Strong, idempotent |
Shared patterns that do carry over are the durable log plus worker fleet, idempotency keys, outbox, and per-tenant quotas.