Design a Versioned Document Storage and Search Service
System DesignModel answerLast updated
Design a system that stores versioned text documents and supports full-text search across any historical version at scale.
Design a Versioned Document Storage and Search Service
Background
Your company builds a collaborative writing tool used by teams to draft, edit, and review long-form documents (think wikis, runbooks, and technical specs). Each document can be edited many times a day. Users need to:
- Read any past version of a document.
- Search for a keyword or phrase and see matching results — with the option to search only the latest version or any version of every document.
Functional Requirements
- Create, update, and delete documents.
- Retrieve document content at a specific version number.
- Full-text search across current versions (required), and optionally across all historical versions (stretch goal).
- Search results should include document ID, version number, a short snippet, and a relevance score.
Non-Functional Requirements
- Scale: 5 million documents, average 50 versions each, average document size 10 KB.
- Write throughput: ~2,000 document saves per second at peak.
- Search latency: p99 < 500 ms for current-version search.
- Read latency for content: p99 < 100 ms.
- Durability: no data loss on a single node failure.
What is expected
Design the end-to-end system. Cover:
- API design (key endpoints)
- Data model (how you store versions efficiently)
- Architecture (components and data flow)
- Indexing strategy for full-text search
- Deep dives on at least two areas of your choice (e.g., storage efficiency, index fan-out, consistency)
- Trade-offs you made and why
Hints
Hint 1
Think about whether you store each version as a full snapshot or as a diff/delta — what does each choice cost you at read time vs. storage?
Hint 2
A search index over all 250 million versions would be enormous; consider what subset you actually need to index and how you'd handle the stretch goal incrementally.
Hint 3
Consider how writes flow: the save path and the index update path can be decoupled with a queue to protect search availability from write spikes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Capacity Estimates
- Total versions: 5M docs × 50 versions = 250M version records
- Raw content storage: 250M × 10 KB = 2.5 TB (before compression)
- Current-version index corpus: 5M × 10 KB = ~50 GB of text — manageable in a single search cluster
- All-version index corpus: 2.5 TB of text — requires a much larger or tiered search cluster
- Write rate: 2,000 saves/s × 10 KB = ~20 MB/s sustained to storage
2. API Design
POST /documents → { doc_id }
PUT /documents/{doc_id} body: { content } → { doc_id, version }
GET /documents/{doc_id}?version=N → { content, version, updated_at }
DELETE /documents/{doc_id} (soft-delete)
GET /search?q=<query>&scope=current|all&limit=20&cursor=...
→ { results: [{ doc_id, version, snippet, score }], next_cursor }
Key decision: PUT always creates a new immutable version; no in-place mutation. Clients always read a specific version or implicitly get the latest.
3. Data Model
documents table (metadata, relational DB or wide-column store)
| column | type | notes |
|---|---|---|
| doc_id | UUID PK | |
| latest_version | int | updated atomically on each save |
| created_at, deleted_at | timestamp | soft-delete |
versions table
| column | type | notes |
|---|---|---|
| doc_id | UUID | FK |
| version | int | together form PK |
| content_key | string | pointer to object storage |
| delta_key | string | optional compressed diff vs. prior version |
| author_id | UUID | |
| created_at | timestamp |
Storage strategy — full snapshots vs. deltas:
Store every version as a full snapshot in object storage (e.g., compressed with zstd, ~3–4× reduction → ~700 GB total). Deltas would save more space but complicate reads: reconstructing version N requires replaying a chain of diffs, adding latency and failure points. With object storage costs at ~$0.02/GB, 700 GB costs ~$14/month — the simplicity wins. For very large documents (> 1 MB), switch to delta storage with a periodic full snapshot every 20 versions to cap reconstruction depth.
4. Architecture
Client
│
▼
API Gateway / Load Balancer
│
├──► Write Service
│ │
│ ├── 1. Write content blob → Object Store (S3-compatible)
│ ├── 2. Write version record → Versions DB (Postgres, sharded by doc_id)
│ ├── 3. Update latest_version in Documents table (optimistic lock)
│ └── 4. Publish event → Message Queue (Kafka topic: doc.saved)
│
├──► Read Service
│ └── Fetch version record → get content_key → stream from Object Store
│ (hot recent versions cached in Redis by doc_id:version)
│
└──► Search Service (Elasticsearch / OpenSearch cluster)
│
▼
Index Consumer (Kafka consumer group)
├── Receives doc.saved events
├── Fetches content from Object Store
└── Upserts document into current-version index (or all-versions index)
Why a queue between writes and indexing? The write path completes as soon as the blob and version record are durable — the caller gets a response in < 50 ms. Index updates are async, allowing search to lag by a few seconds without blocking saves during spikes.
5. Indexing Strategy
Current-version index (required):
- One Elasticsearch document per
doc_id, content = latest version text. - On each
doc.savedevent, the consumer performs an upsert by doc_id, replacing the indexed content. Index size stays bounded at 50 GB. - Sharding: 10 primary shards, 1 replica each; routing key = doc_id so shard affinity is consistent.
All-versions index (stretch goal):
- Separate index with document ID =
doc_id:version. - 250M documents × average indexed size — keep only the diff to avoid re-indexing unchanged paragraphs; alternatively, index only versions tagged as "published" or "milestone."
- Use index tiering: recent versions on hot nodes (SSD), older versions on warm nodes (HDD), versions > 1 year old archived from the search index entirely (still retrievable from object store, just not searchable).
6. Deep Dives
A. Storage efficiency at scale
Compression of text with zstd achieves ~4× on typical prose, bringing 2.5 TB → ~625 GB. Deduplication across versions is possible (many edits change < 5% of content) using a content-addressed store, but adds complexity. A pragmatic middle ground: store a delta for versions where diff_size < 0.3 × snapshot_size, else store a full snapshot. A background job periodically re-evaluates the chain and inserts a new full snapshot every 20 versions.
B. Consistency between the DB version record and the search index
The write service writes to the DB first, then publishes to Kafka. If the write succeeds but publishing fails, the Kafka consumer can replay by reading a versions changelog table (CDC via Debezium) rather than relying solely on the application event. This ensures at-least-once indexing. The search index is eventually consistent — acceptable for this use case; users expect search to reflect the last save within a few seconds.
7. Trade-offs Summary
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Full snapshot vs. delta | Full snapshot (with optional delta for large docs) | Pure delta chain | Simpler reads, predictable latency |
| Sync vs. async indexing | Async (Kafka) | Sync in write path | Protects write latency; slight staleness is acceptable |
| Single current-version index | Yes (required scope) | All-versions from day one | 50× smaller index, much lower cost; all-versions added incrementally |
| Object store for content | Yes | DB blob columns | Better throughput, cheaper, independently scalable |
Common Mistakes to Avoid
- Storing content in the relational DB as BLOBs: kills query performance as the table grows past millions of rows.
- Indexing all 250M versions immediately: the index will be 50× larger and more expensive than needed; start with current versions.
- No cache on read path: object store calls add 20–50 ms each; a Redis layer on recent versions keeps p99 reads well under 100 ms.
- Version counter using auto-increment without a lock: concurrent saves to the same document can produce duplicate version numbers. Use an optimistic lock (
UPDATE documents SET latest_version = N+1 WHERE latest_version = N) and retry on conflict.