Design a Multi-Location Book Reservation & Inventory System
System DesignModel answerLast updated
Architect a distributed inventory, reservation, and circulation platform across multiple physical locations with transactional guarantees, idempotency, and search index synchronization.
Architect a backend system for a multi-branch public library network. While every library branch stores and manages its local physical inventory, users must be able to search the global catalog, discover item availability per branch, and reserve or check out books seamlessly.
Requirements
Functional Requirements
- Unified Search: Users can search titles across the entire library network and view real-time availability broken down by branch.
- Holds & Reservations: Users can place a hold on an available copy at a target branch, preventing double-booking and locking the copy until checkout or hold expiration.
- Circulation Workflow: Support state transitions for physical copies:
AVAILABLE$\rightarrow$RESERVED$\rightarrow$CHECKED_OUT$\rightarrow$AVAILABLE(upon return). - Branch Ownership & Tracking: Maintain tracking of where each physical copy belongs and its current state across the network.
Non-Functional Requirements
- Strict Concurrency Control: Guarantee strong consistency for physical copy state transitions. Prevent race conditions where multiple users attempt to reserve or check out the last available copy concurrently.
- High Availability vs. Consistency Trade-off: The system must degrade gracefully during network partitions or search index lag while keeping reservation/checkout operations strongly consistent.
- Idempotent Operations: Network timeouts and retry attempts by clients (or branch barcode scanners) must not cause duplicate state updates or secondary side-effects.
- Fault Tolerance: Ensure side-effects (e.g., audit logging, user notifications, search indexing updates) do not corrupt transactional state if downstream components experience mid-operation failures.
Hints
Hint 1
Distinguish between read-heavy search requirements (tolerates eventual consistency) and write-heavy item state transitions (requires strong consistency).
Hint 2
Use database-level locking mechanisms like SELECT ... FOR UPDATE SKIP LOCKED for concurrent item reservations to avoid race conditions.
Hint 3
Implement the Transactional Outbox pattern to reliably bridge relational database state updates with downstream event streams (Kafka/Search Indexers).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirement Clarification & Capacity Estimation
Scale & Traffic Profile
- System Footprint: 500 physical library branches, 5 million distinct book titles, 20 million total physical copies, and 10 million registered members.
- Read Workloads (Search): ~2,000 queries per second (QPS) at peak.
- Write Workloads (Holds, Checkouts, Returns): Peak write volume is relatively low (~100–200 writes/sec), but every write requires strict transactional guarantees.
- Consistency Constraints:
- Holds & Checkouts: Strongly consistent (ACID). Under no circumstances can a single physical copy be assigned to two active holds or checkouts concurrently.
- Search & Discovery: Eventually consistent. A lag of 1–2 seconds between database commits and search index updates is acceptable.
2. API Specifications
All state-modifying requests require an Idempotency-Key header to handle retries safely.
Search Catalog
GET /v1/catalog/search?query=dune&branch_id=b_101&limit=20
Response (200 OK):
{
"results": [
{
"title_id": "t_9981",
"title": "Dune",
"author": "Frank Herbert",
"branches": [
{
"branch_id": "b_101",
"available_copies": 2,
"total_copies": 5
}
]
}
],
"as_of": "2023-10-25T14:30:00Z"
}
Place Reservation / Hold
POST /v1/reservations
Idempotency-Key: 8c8d32b8-f02a-464a-9b11-92f76f7f2122
{
"user_id": "u_4412",
"title_id": "t_9981",
"branch_id": "b_101"
}
Response (201 Created / 409 Conflict):
{
"reservation_id": "res_5510",
"copy_id": "c_88123",
"status": "RESERVED",
"expires_at": "2023-10-27T14:30:00Z"
}
Circulation Check Out / Return
POST /v1/circulation/checkout
Idempotency-Key: 3a2c11e7-2b89-4911-a832-111bc32e9211
{
"user_id": "u_4412",
"copy_id": "c_88123",
"reservation_id": "res_5510"
}
POST /v1/circulation/return
Idempotency-Key: 55a29f01-1182-411c-9912-32a8190012bc
{
"copy_id": "c_88123",
"branch_id": "b_101"
}
3. Data Storage & Schema Design
To guarantee ACID properties for physical copy management, the primary system of record is a relational database (PostgreSQL/Aurora MySQL).
CREATE TYPE item_status AS ENUM (
'AVAILABLE',
'RESERVED',
'CHECKED_OUT',
'IN_TRANSIT',
'LOST'
);
CREATE TABLE branches (
branch_id VARCHAR(64) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
address TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE titles (
title_id VARCHAR(64) PRIMARY KEY,
isbn VARCHAR(13) UNIQUE NOT NULL,
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
metadata JSONB
);
CREATE TABLE copies (
copy_id VARCHAR(64) PRIMARY KEY,
title_id VARCHAR(64) REFERENCES titles(title_id),
home_branch_id VARCHAR(64) REFERENCES branches(branch_id),
current_branch_id VARCHAR(64) REFERENCES branches(branch_id),
status item_status NOT NULL DEFAULT 'AVAILABLE',
version BIGINT NOT NULL DEFAULT 1,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE reservations (
reservation_id VARCHAR(64) PRIMARY KEY,
user_id VARCHAR(64) NOT NULL,
copy_id VARCHAR(64) REFERENCES copies(copy_id),
status VARCHAR(32) NOT NULL, -- 'ACTIVE', 'FULFILLED', 'EXPIRED', 'CANCELLED'
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Partial Unique Index: Prevents double-booking at DB level regardless of application bugs
CREATE UNIQUE INDEX idx_active_copy_reservation
ON reservations (copy_id)
WHERE status = 'ACTIVE';
CREATE TABLE idempotency_keys (
key VARCHAR(255) PRIMARY KEY,
user_id VARCHAR(64) NOT NULL,
request_hash VARCHAR(64) NOT NULL,
response_payload JSONB NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE outbox (
event_id VARCHAR(64) PRIMARY KEY,
aggregate_type VARCHAR(64) NOT NULL,
aggregate_id VARCHAR(64) NOT NULL,
payload JSONB NOT NULL,
processed BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
4. High-Level Architecture
┌────────────────────────────────────────┐
│ API Gateway │
└───────────────────┬────────────────────┘
│
┌────────────────────────┴────────────────────────┐
▼ ▼
┌──────────────────────┐ ┌──────────────────────┐
│ Search Service │ │ Lending Service │
└───────────┬──────────┘ └──────────┬───────────┘
│ │
▼ ▼
┌──────────────────────┐ ┌──────────────────────┐
│ Elasticsearch Cluster│ │ Relational DB Primary│
└──────────────────────┘ └──────────┬───────────┘
▲ │
│ Outbox / CDC (Debezium)
│ │
│ ▼
│ ┌──────────────────────┐
│ │ Kafka Topic │
│ └──────────┬───────────┘
│ │
├────────────────────────┬───────────────────────┤
│ │ │
┌───────────┴──────────┐ ┌───────────┴──────────┐ ┌───────────┴──────────┐
│ Search Sync Worker │ │ Notification Service │ │ History & Analytics │
└──────────────────────┘ └──────────────────────┘ └──────────────────────┘
Component Breakdown
- Search Service: Serves fast, full-text catalog queries with branch availability facets from Elasticsearch.
- Lending Service: Handles state changes for holds, checkouts, and returns using ACID transactions against the relational database.
- Outbox / CDC (Debezium): Reads outbox records (or transaction logs) from the relational DB and streams them to Kafka.
- Async Workers: Consume Kafka events to update Elasticsearch indices, trigger notifications, or record audit logs.
5. Key Design Deep-Dives
Deep-Dive 1: Preventing Double-Booking Under High Concurrency
When multiple users attempt to reserve the same title at the same branch simultaneously, the Lending Service must prevent race conditions without stalling system performance.
The Protocol: SKIP LOCKED
Clients request a hold on a title at a branch, not a specific physical copy_id. The server picks an available copy and locks it in a single atomic database query:
BEGIN;
-- Lock and retrieve one available copy
SELECT copy_id, version
FROM copies
WHERE title_id = 't_9981'
AND current_branch_id = 'b_101'
AND status = 'AVAILABLE'
LIMIT 1
FOR UPDATE SKIP LOCKED;
-- If a row is found (e.g., copy 'c_88123'):
UPDATE copies
SET status = 'RESERVED',
version = version + 1,
updated_at = NOW()
WHERE copy_id = 'c_88123';
INSERT INTO reservations (reservation_id, user_id, copy_id, status, expires_at)
VALUES ('res_5510', 'u_4412', 'c_88123', 'ACTIVE', NOW() + INTERVAL '48 hours');
INSERT INTO outbox (event_id, aggregate_type, aggregate_id, payload)
VALUES ('evt_1001', 'RESERVATION', 'res_5510', '{"event": "RESERVATION_CREATED", "copy_id": "c_88123"}');
COMMIT;
Why FOR UPDATE SKIP LOCKED?
Instead of blocking multiple threads on the same copy lock, SKIP LOCKED causes concurrent transactions to bypass locked rows and lock the next available physical copy. If all copies are locked or reserved, the query returns zero rows, allowing the application to immediately return 409 Conflict (No Copies Available) without deadlock or contention penalties.
Deep-Dive 2: Guaranteeing Idempotency Across Retries
Network failures between the client/desk scanner and the API Gateway can lead to duplicate requests. Every state-altering call uses the idempotency_keys table inside the same transaction:
BEGIN;
-- 1. Check if Idempotency Key exists
SELECT response_payload FROM idempotency_keys WHERE key = '8c8d32b8-...';
-- If found: RETURN stored response immediately (abort rest of logic).
-- 2. Execute reservation logic...
-- 3. Store response before commit
INSERT INTO idempotency_keys (key, user_id, request_hash, response_payload)
VALUES ('8c8d32b8-...', 'u_4412', 'hash_val', '{"reservation_id": "res_5510", ...}');
COMMIT;
If a client retries due to a timeout, the system observes the existing key, skips execution, and returns the cached payload safely.
Deep-Dive 3: Handling Mid-Transaction Failures (Transactional Outbox Pattern)
Updating the database and directly calling external downstream systems (e.g., publishing to Kafka, calling a third-party notification vendor) within the same thread introduces dual-write risks:
- If the DB commits but Kafka throws a network error, the event is lost.
- If Kafka succeeds but the DB commit rolls back, an invalid event was published.
Solution: Transactional Outbox Pattern
- Writes to the
copies,reservations, andoutboxtables occur in a single database transaction. - A separate Log-Based CDC process (e.g., Debezium) tails the database transaction log (WAL) and publishes rows committed to
outboxinto Kafka. - Consumers (Elasticsearch Indexer, Notification Engine) process Kafka events asynchronously.
[Lending Service] ---> (Atomically Commits State + Outbox Row to RDBMS)
│
PostgreSQL WAL
│
[Debezium CDC Engine]
│
[Kafka Pipeline Topic]
┌─────────────┴─────────────┐
▼ ▼
[Search Index Worker] [Notification Worker]
This guarantees at-least-once delivery without distributed 2-Phase Commit (2PC) protocols, keeping system availability high.
Deep-Dive 4: Availability vs. Consistency in Catalog Search
- Read Path (Elasticsearch): Optimized for low-latency searches across millions of records.
- Synchronization Lag: Elasticsearch index updates lag behind DB commits by a brief window (typically < 1 second).
Handling Edge Cases
- Search Stale Positives: Elasticsearch reports a copy is available, but another user reserved it 200ms ago.
- Mitigation: The reservation step hits the primary relational DB. The system rejects the hold request with a user-friendly message (
409 Conflict) if the copy was taken in that brief window.
- Mitigation: The reservation step hits the primary relational DB. The system rejects the hold request with a user-friendly message (
- Branch Partition Isolation: If an individual branch loses connectivity to the central cloud gateway:
- Desk terminals transition to an Offline Queue Mode, storing local checkouts/returns in a local persistent storage queue (SQLite/RocksDB).
- Upon reconnection, the offline queue replays actions using original timestamps and idempotency keys to resolve conflicts deterministically.
6. Key Takeaways & Trade-Offs
| Option Selected | Alternative Evaluated | Design Justification |
|---|---|---|
Relational DB + SKIP LOCKED | Redis / Distributed Locks | DB row locking keeps consistency guarantees and inventory data co-located without lock expiration/lease risk. |
| Transactional Outbox Pattern | Direct Kafka Publish | Eliminates dual-write anomalies; guarantees asynchronous state notification even on database worker crashes. |
| CQRS (RDBMS + Search Index) | Single Database for Search & Writes | Separates heavy read-search traffic from transactional write operations, ensuring peak traffic surges do not degrade lending consistency. |