Thread-Safe Tag Index and Online Bookstore Architecture
System DesignModel answerLast updated
Design a concurrent in-memory tagging system with correct multi-index atomicity, then architect a scalable bookstore handling high-read browsing and consistent purchases.
The Problem
This question has two independent parts. Budget roughly 15–20 minutes on Part 1 and 25–30 minutes on Part 2.
Part 1: Concurrent Document-Tag Index
Build an in-memory library that associates arbitrary string tags with documents. Multiple threads will call it simultaneously.
Your design must support:
- Attaching or detaching a tag from a document
- Retrieving all tags on a given document
- Retrieving all documents that carry a given tag
- (Bonus) Retrieving documents that carry every tag in a given set
What the interviewer is looking for:
- A clean class structure that separates entity representation from index management
- Correct identification of the atomicity problem that arises when two indexes must stay in sync
- At least two locking strategies with their trade-offs, including how to avoid deadlock when striping
- Returning safe, immutable views to callers
- Complexity analysis for the intersection query
Part 2: Scalable Online Bookstore
Design the back-end of a bookstore that lets users browse a catalog and place orders for physical or digital books.
Core capabilities:
- Full-text and category search across a catalog of millions of titles
- Viewing book details, pricing, and stock availability
- A shopping cart
- Checkout with payment, no overselling, no duplicate charges
- Order history
What the interviewer is looking for:
- Explicit scale assumptions backed by rough numbers
- A clear API surface
- A data model that separates read-heavy catalog data from strongly-consistent inventory and order data
- Caching strategy with stated TTLs and invalidation approach
- How the checkout flow prevents race conditions (concurrent buyers, duplicate submissions)
- Where the system degrades gracefully versus where it must not
Hints
Hint 1
For Part 1, think about what 'atomic' means when a single logical operation touches two separate maps — per-map thread safety is necessary but not sufficient. Name the specific failure mode a reader can observe if you don't guard both maps together.
Hint 2
For lock striping in Part 1, the key question is: what rule prevents two threads from deadlocking when they each need two stripes? Write that rule down before you code anything.
Hint 3
For Part 2, the read:write ratio on a bookstore is roughly 1000:1. Let that ratio drive every architectural decision: where you cache, what consistency level you need, and which storage engine you pick for each data type.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Thread-Safe Document-Tag Index
Requirements check
Before designing, nail down a few things: Is tag existence tied to documents, or can a tag exist on its own? Does the intersection query need "all tags match" or "any tag matches"? Is the workload in-process only? Assume: tags are implicit (they live as long as a document uses them), intersection means "all", and everything is in-process and multi-threaded with many more reads than writes.
Class structure
Keep entities dumb. Document carries only identity and content — it should not know about the tagging index. Tag is a normalized value object: lowercase, trimmed, and hashable. A separate TagService owns the two indexes:
doc_id → set[tag]tag → set[doc_id]
Putting both indexes in one place is what makes the atomicity problem tractable.
The core concurrency problem
A single "add tag" call writes to both maps. If you protect each map independently, a reader between the two writes sees a half-applied state: the doc→tag entry exists, but the tag→doc entry does not. That reader then returns an inconsistent result. The pair of writes must appear atomic.
Three viable strategies:
1. Single read-write lock (default choice)
One RWLock guards both maps together. Multiple readers run concurrently; a writer gets exclusive access. This is correct, simple, and right for most workloads.
2. Lock striping
Hash doc_id and tag to N stripes (e.g., 64). When an operation needs two stripes, always acquire them in ascending index order. That ordering rule is what prevents deadlock — two threads wanting the same pair will always race for the lower-index stripe first, so one blocks rather than cycles. Name this rule explicitly; it's what interviewers listen for.
3. Copy-on-write Readers get immutable snapshots. Writers build a new set and swap it in atomically. Works well when writes are very rare; GC pressure is the cost.
The single RWLock is the right default. Mention striping as the next step if profiling shows write contention.
One more rule: always return copies or frozen sets from getters. Handing out a live reference lets callers iterate while another thread mutates.
import threading
from collections import defaultdict
class RWLock:
def __init__(self):
self._readers = 0
self._mu = threading.Lock()
self._no_readers = threading.Condition(self._mu)
def acquire_read(self):
with self._mu:
self._readers += 1
def release_read(self):
with self._mu:
self._readers -= 1
if self._readers == 0:
self._no_readers.notify_all()
def acquire_write(self):
self._mu.acquire()
while self._readers > 0:
self._no_readers.wait()
def release_write(self):
self._mu.release()
class TagService:
def __init__(self):
self._doc_tags: dict[str, set] = defaultdict(set)
self._tag_docs: dict[str, set] = defaultdict(set)
self._rw = RWLock()
@staticmethod
def _norm(tag: str) -> str:
return tag.strip().lower()
def add_tag(self, doc_id: str, tag: str) -> None:
t = self._norm(tag)
self._rw.acquire_write()
try:
self._doc_tags[doc_id].add(t)
self._tag_docs[t].add(doc_id)
finally:
self._rw.release_write()
def remove_tag(self, doc_id: str, tag: str) -> None:
t = self._norm(tag)
self._rw.acquire_write()
try:
self._doc_tags.get(doc_id, set()).discard(t)
docs = self._tag_docs.get(t)
if docs is not None:
docs.discard(doc_id)
if not docs:
del self._tag_docs[t] # reclaim empty tag entries
finally:
self._rw.release_write()
def tags_of(self, doc_id: str) -> frozenset:
self._rw.acquire_read()
try:
return frozenset(self._doc_tags.get(doc_id, ()))
finally:
self._rw.release_read()
def docs_with_all(self, *tags: str) -> frozenset:
self._rw.acquire_read()
try:
# Sort by set size: intersecting from the smallest first prunes fastest
sets = sorted(
(self._tag_docs.get(self._norm(t), set()) for t in tags),
key=len
)
if not sets:
return frozenset()
result = set(sets[0])
for s in sets[1:]:
result &= s
return frozenset(result)
finally:
self._rw.release_read()
Complexity:
add_tag/remove_tag: O(1) averagetags_of: O(k) where k is the number of tags on the documentdocs_with_all: O(k × |smallest set|) — sorting by size first is the optimization to call out
Known limitation: this RWLock favors readers. Under constant read load, writers can starve. A writer-preferring variant (track pending writers and block new readers once a writer is waiting) fixes this. Mention it proactively.
Part 2: Scalable Online Bookstore
Scale assumptions
| Dimension | Estimate | Implication |
|---|---|---|
| Daily active users | 20M | — |
| Browse page views | ~20/user/day → ~5k QPS avg, 25k peak | Cache aggressively |
| Orders | ~1M/day → ~12/s avg, up to 2k/s on a flash sale | Transactions and idempotency required |
| Catalog size | 10M titles × 5KB metadata | ~50GB — fits in a few DB nodes; cover images go to object storage + CDN |
Read:write ratio is roughly 1000:1. That single number justifies most of the architectural choices below.
API surface
GET /books?q=&category=&page= # search and browse
GET /books/{id} # detail page with stock status
POST /cart/items {book_id, qty} # add to cart
DELETE /cart/items/{book_id}
POST /orders {cart_id, payment_token} # Idempotency-Key header required
GET /orders/{id}
GET /users/{id}/orders
Data model
Catalog (Postgres with read replicas, or a document store): Book(id, title, authors, isbn, price, category, description, image_url). Mostly static; long cache TTL is safe.
Search index (Elasticsearch/OpenSearch): fed by change events from the catalog. Decoupled so a catalog write doesn't block a search query.
Inventory (Postgres, strongly consistent): (book_id PK, available INT, reserved INT, version INT). Version supports optimistic locking.
Orders: Order(id, user_id, status, total, idempotency_key UNIQUE, created_at) and OrderItem(order_id, book_id, qty, price_at_purchase). Shard by user_id for order history queries.
Cart: Redis hash keyed by session/user with a TTL. Flush to a persistent store for logged-in users who want their cart to survive a session.
Architecture
Client
→ CDN (static assets, cover images, cached catalog pages)
→ Load balancer / API gateway (auth, rate limiting, TLS)
→ Stateless microservices:
Catalog service → Redis cache (1hr TTL) → Postgres read replica
Search service → Elasticsearch cluster
Cart service → Redis
Order service → Postgres (primary, transactions)
Payment service → external PSP
→ Async: Kafka / SQS for inventory updates, notifications, search re-indexing
Checkout flow and concurrency
This is where most candidates lose points. Two problems to solve:
Overselling: Use an optimistic lock on inventory.
UPDATE inventory
SET available = available - :qty,
reserved = reserved + :qty,
version = version + 1
WHERE book_id = :id
AND available >= :qty
AND version = :expected_version;
-- If rows_affected == 0, retry or return "out of stock"
Under high contention (flash sale), fall back to a queue-based reservation: buyers get a hold, confirmed asynchronously.
Duplicate charges: The POST /orders endpoint accepts an Idempotency-Key header. The order service inserts it into the idempotency_key UNIQUE column before calling the payment provider. A retry with the same key hits the unique constraint and returns the original result. The payment call itself must be idempotent on the PSP side too — pass the same key through.
Caching strategy
- Catalog detail pages: cache-aside, ~1 hour TTL. Invalidate on price or stock change.
- Stock availability shown on the detail page: shorter TTL (30–60s) or a separate lightweight endpoint. Showing slightly stale stock is acceptable; actual enforcement happens in the checkout transaction.
- Search results: cache by query string, short TTL (a few minutes), since the index lags the catalog anyway.
Failure modes to mention
- Elasticsearch down: fall back to basic SQL catalog browsing; search is degraded, not dead.
- Redis down: cart service falls back to the database; catalog service bypasses cache and hits the read replica (higher latency but correct).
- Payment provider timeout: the order stays in
PENDING. A background job retries using the stored idempotency key. Never retry without it. - Flash sale spike: rate-limit at the API gateway per user, queue order submissions, and pre-warm inventory in Redis with a count-down counter (atomic DECR) to avoid hammering Postgres.