Stock Ledger and Support Chat: Two Backend Services
System DesignModel answerLast updated
Design an oversell-proof book stock service with search, plus a real-time one-to-one support chat with delivery receipts, history and offline handling.
Two Services for an Online Book Retailer
An online book retailer wants two separate backend services. Describe the design of each and justify the technology choices.
Service A: Stock and Catalog
Build a service that keeps track of book titles, their authors, and how many copies sit in each warehouse.
- Stock must never go negative or be sold twice during checkout, so decrements need strong consistency.
- Customers can search by title or author.
- Scale: about 10 million SKUs and about 5,000 requests per second overall.
Service B: Support Chat
Build a service where a customer talks to a support agent in real time.
- One-to-one conversations only.
- Each message shows a status of sent, delivered, or read.
- Past messages in a conversation can be retrieved.
- Scale: about 100,000 users connected at the same time.
What to cover for each service
- Interface: the main operations (for example a checkout call and a send-message call), with their inputs and outputs.
- Storage: which database type you pick (relational or NoSQL), and the schema.
- Architecture: how a request flows end to end, including load balancing, caching, and where state is kept.
- Failure handling and trade-offs: for instance, what happens to a chat message sent to someone who is offline, or to a checkout request that is retried after a timeout.
Back your choices with rough capacity numbers.
Hints
Hint 1
Ask which service needs correctness above all and which needs low-latency fan-out and write throughput; let that decide storage and protocol for each.
Hint 2
For stock, avoid read-then-write. Think about a single conditional UPDATE, a short-lived reservation with an expiry, and an idempotency key so a retried checkout cannot decrement twice.
Hint 3
For chat, a persistent connection lets the server push. Persist a message before acknowledging it, track read/delivered state as a per-user watermark rather than per-message rows, and keep connection routing in a fast shared store.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The two services pull in opposite directions. Stock is about correctness: never sell a copy that does not exist. Chat is about low-latency delivery and cheap, durable writes. Saying this up front justifies using a relational database for one and a wide-column store plus persistent connections for the other.
Service A: Stock and Catalog
Sizing
- Catalog: 10M SKUs at roughly 2 KB each is about 20 GB. Stock rows: 10M SKUs times about 5 warehouses is about 50M small rows. Both fit on one relational primary.
- 5,000 RPS is read-heavy. Assuming 90% reads leaves about 500 writes/s (reservations and checkouts), which a well-indexed Postgres primary handles comfortably.
Interface
GET /books/{sku} -> metadata + total availability
GET /search?q=&author=&cursor= -> paginated results
POST /reservations {sku, qty, idempotency_key} -> reservation_id, expires_at
POST /checkout {reservation_ids[], payment_token, idempotency_key} -> order_id
POST /reservations/{id}/release
The idempotency key is essential: clients retry on timeout, and a retry must return the original result rather than decrement again.
Data model (PostgreSQL)
books(sku PK, title, isbn, price, ...)
authors(author_id PK, name); book_authors(sku, author_id)
stock(sku, warehouse_id, on_hand, reserved, PK(sku, warehouse_id))
reservations(id PK, sku, warehouse_id, qty, status, expires_at, idempotency_key UNIQUE)
orders(order_id PK, user_id, status, idempotency_key UNIQUE)
Relational is the right fit because checkout touches stock, reservations and orders atomically, and unique constraints give idempotency for free.
Preventing oversell
Use one atomic conditional update instead of read-then-write:
UPDATE stock SET reserved = reserved + :qty
WHERE sku = :sku AND warehouse_id = :wh
AND on_hand - reserved >= :qty;
-- 0 rows updated => out of stock
Run it in the same transaction as the reservation insert. Row-level locks serialize buyers of the same SKU.
Checkout flow:
- Reserve with a TTL (about 10 minutes).
- Charge payment outside any DB lock.
- Commit:
on_hand -= qty, reserved -= qty, mark order paid.
A sweeper releases expired reservations. A payment failure is then just a release, not a compensating restock.
Hot SKUs (a launch day bestseller) make one row the bottleneck. Options: split the counter into N sub-rows per warehouse and pick one at random, or put a Redis DECR gate in front to reject early while the database stays authoritative.
Architecture
Client -> CDN (images, static pages) -> L7 LB -> stateless API pods
-> Redis (metadata cache, short-TTL availability)
-> Postgres primary (writes) + read replicas (reads)
-> CDC -> Kafka -> Elasticsearch (title/author search)
- Catalog reads hit cache and replicas. An "in stock" badge can be a few seconds stale.
- Only reserve and checkout touch the primary, and the final check happens there, so stale reads cannot cause overselling.
- Search is eventually consistent, fed by change data capture.
Failure cases
- Retried checkout: the unique idempotency key returns the existing order.
- Crash between reserve and charge: the TTL sweeper frees stock.
- Payment succeeds but commit fails: a reconciliation job matches payment records to orders and finishes or refunds.
- Primary failure: synchronous or semi-synchronous replica promotion; accept brief write unavailability rather than risk lost decrements.
Service B: Support Chat
Sizing
- 100k concurrent connections. At one message per user per 30 s, that is about 3.3k msg/s, with peaks near 10k/s.
- At about 1 KB per message, sustained peak is hundreds of GB per day. The workload is append-heavy and read by conversation.
Why WebSockets
Plain request/response cannot push. Polling every second from 100k clients is 100k RPS of mostly empty replies, or else adds seconds of latency. A WebSocket gives one persistent bidirectional channel, so delivery is immediate. Long-polling is the fallback where WebSockets are blocked.
Interface
WebSocket events:
send_message {client_msg_id, conversation_id, body} -> ack {message_id, ts} // "sent"
message {message_id, conversation_id, sender, body, ts} // pushed
ack_delivered / ack_read {conversation_id, up_to_message_id}
REST:
GET /conversations/{id}/messages?before=&limit=50
POST /conversations {customer_id} -> assigns an agent
Data model
- Messages in Cassandra or ScyllaDB:
PRIMARY KEY (conversation_id, message_id)with a time-sortable ID (Snowflake or ULID), clustered descending. History is a single-partition range scan. Add a time bucket to the partition key for very long conversations. - Receipts as watermarks:
receipts(conversation_id, user_id, last_delivered_id, last_read_id). A message is read if its id is at or belowlast_read_id. This makes status updates O(1) per acknowledgment rather than one write per message. - Conversations and agent assignment in SQL: small and relational.
Architecture
Client --WS--> L4 LB -> Chat gateways (~10-20 nodes, ~10k conns each)
Gateway -> Chat service -> Cassandra -> Redis pub/sub or Kafka
Redis: user_id -> gateway_id (TTL, refreshed by heartbeat)
Send path:
- Gateway receives
send_message. - Service dedupes on
client_msg_idand persists first. - Sender gets the "sent" ack.
- Service looks up the recipient's gateway in Redis and publishes to it.
- Gateway pushes; the recipient's client replies with
ack_delivered.
Gateways hold only connection state. A crash simply makes clients reconnect to another node and resync.
Failures and offline users
- Recipient offline: no presence entry, but the message is already durable. Send a mobile push notification; on reconnect the client requests everything after its last seen message id and then advances its delivered watermark.
- Duplicate sends:
client_msg_idmakes retries idempotent. - Ordering: order by
message_idwithin a conversation; clients sort on it. - Stale routing entry: if the push fails, fall back to the offline path. The data is safe anyway.
- Reconnect storms: jittered backoff and connection-rate limits at the gateway.
Common mistakes
- Using an eventually consistent store for stock decrements.
- Holding a database transaction open across the payment call.
- Forgetting idempotency on checkout and message send.
- Storing one receipt row per message instead of a watermark.
- Keeping chat connection state only in gateway memory with no shared routing or persistence.
- Acking "sent" before the message is durably stored.