In-Memory Document-Tag Store with Thread-Safe Concurrency
System DesignModel answerLast updated
Design an in-memory library that manages documents and tags, supports multi-tag intersection queries, and handles concurrent reads and writes safely.
Problem
You are building an in-memory library that associates documents with tags. The library will be used inside a single process and must expose a clean programmatic interface.
Required operations
- Create or delete a document
- Create or delete a tag
- Attach or detach a tag from a document
- Retrieve all documents carrying a given tag
- Retrieve all tags on a given document
- Find all documents that carry every tag in a supplied list (intersection query)
What to cover
Part 1 — Core design
Define the class interfaces and method signatures. Specify the internal data structures and any secondary indices you need. Describe how you handle:
- Duplicate tag names (e.g.
"ML"," ml ","Ml") - Idempotent operations (creating a tag that already exists, adding a tag a document already has)
- Invalid inputs (missing document ID, empty tag list)
State the time and space complexity of each operation.
Part 2 — Thread safety
Extend the design to support concurrent callers. Discuss:
- What makes "just use a concurrent map" insufficient
- Locking granularity options and their trade-offs (global RW lock, striped locks, copy-on-write)
- How you guarantee that both sides of every bidirectional index stay in sync
- Deadlock avoidance strategy
- How you would test that the concurrent implementation is actually correct
Hints
Hint 1
Start by identifying which structures must stay in sync on every mutation — that invariant is what drives the entire concurrency design.
Hint 2
For intersection queries, think about which tag set to iterate first and how that choice affects worst-case cost.
Hint 3
When evaluating locking options, consider what happens during a delete_tag on a tag with millions of associated documents — how does each strategy behave under that load?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Requirements and Assumptions
Before designing anything, state your assumptions explicitly.
- Scope: single-process, in-memory library. Not a distributed service, though sharding strategies are worth mentioning at the end.
- Scale: ~10M documents, ~100K tags, ~10 tags per document on average — roughly 100M edges.
- Workload: read-heavy, around 100:1 reads to writes. Intersection queries are the hot path.
- Normalization: tag names are case-insensitive and whitespace-trimmed. Apply Unicode NFKC normalization first, then
casefold()(notlower()—casefoldhandles"ß"→"ss"). Store the first-seen display form separately from the lookup key. - Duplicate semantics:
- Creating an existing tag is idempotent; return the existing object.
- Attaching a tag a document already carries is a no-op.
- Operations on a non-existent document raise
NotFound.
- Empty tag list in an intersection query raises an error rather than returning every document.
2. Class Interfaces
class Document:
id: str
title: str
created_at: float
class Tag:
key: str # normalized lookup key
display: str # original display form
class TagNormalizer:
def normalize(self, name: str) -> str:
# NFKC + strip + casefold; validate length and charset
...
class DocumentTagStore:
def create_document(self, doc_id: str, title: str) -> Document
def delete_document(self, doc_id: str) -> None
def create_tag(self, name: str) -> Tag
def delete_tag(self, name: str) -> None
def add_tag(self, doc_id: str, name: str) -> bool # True if newly added
def remove_tag(self, doc_id: str, name: str) -> bool
def documents_for_tag(self, name: str) -> list[str]
def tags_for_document(self, doc_id: str) -> list[Tag]
def query_all(self, names: list[str], limit: int | None = None) -> list[str]
TagNormalizer is a separate class so normalization policy (locale rules, allowed charset) can evolve independently of index logic.
3. Data Structures and Indices
| Structure | Type | Purpose |
|---|---|---|
docs | dict[doc_id, Document] | entity storage |
tags | dict[tag_key, Tag] | entity storage, deduplicated by normalized key |
doc_tags | dict[doc_id, set[tag_key]] | forward index: doc → its tags |
tag_docs | dict[tag_key, set[doc_id]] | inverted index: tag → its docs |
Core invariant: t in doc_tags[d] if and only if d in tag_docs[t]. Every mutation must update both sides together. This is the central correctness requirement and the main driver of the concurrency design.
Intersection query algorithm:
- Normalize all input names and deduplicate.
- If any tag is unknown, return an empty list immediately.
- Sort the corresponding sets by cardinality (ascending).
- Iterate the smallest set; retain a candidate only if it appears in every other set.
Cost: O(k · |S_min|) rather than O(sum of all sizes). At scale, sets can be replaced with sorted posting lists or compressed bitmaps (e.g. Roaring Bitmaps), which support galloping intersection and SIMD acceleration.
4. Complexity Summary
| Operation | Time |
|---|---|
| create / delete tag (no edges) | O(1) |
| add / remove tag on document | O(1) average |
| tags_for_document | O(t), t = tags on doc |
| documents_for_tag | O(n), n = docs with tag |
| delete_document | O(t), must unlink from each tag set |
| delete_tag | O(n), must unlink from each doc set |
| query_all (k tags) | O(k log k + k · |S_min|) |
Space: O(D + T + E) where E is edge count. At 100M edges, with string keys, memory pressure is real — the argument for integer IDs and bitmap sets.
5. Thread Safety
Why a concurrent map alone is not enough
add_tag touches four things in sequence: verify the document exists, verify the tag exists, write to doc_tags, write to tag_docs. A concurrent delete_document can interleave between steps 3 and 4, leaving an orphan edge in the inverted index. The unit of atomicity must be the full operation, not individual map writes.
Option A: Global readers-writer lock (recommended starting point)
- All reads share the lock concurrently; writes acquire it exclusively.
- Every operation is linearizable. An intersection query always sees a consistent snapshot.
- Deadlock is structurally impossible — there is only one lock.
- At a 100:1 read/write ratio with sub-millisecond writes this is almost always sufficient. Say so, then offer the scaling path.
- Risk:
delete_tagon a tag with millions of documents holds the write lock for the entire unlink loop, blocking all readers. Mitigate by tombstoning the tag first (it disappears from queries immediately) and cleaning up edges in a background task.
Option B: Striped fine-grained locks
- Divide documents and tags each into N stripes (e.g. 256), keyed by
hash(id) % N. add_tag(d, t)locks the document stripe fordand the tag stripe fort.- Deadlock prevention: enforce a global acquisition order. Always acquire all document-stripe locks before tag-stripe locks; within each class, acquire in ascending stripe index. Never deviate from this order.
delete_tagmust lock every document stripe for affected docs — collect them, sort by stripe index, acquire in order.- Intersection queries lock k tag stripes in ascending order; they see a consistent view across those stripes only.
- Higher write throughput, but significantly harder to reason about and audit.
Option C: Copy-on-write / immutable snapshots
- A single writer mutex serializes mutations. Each write builds new immutable structures and atomically replaces a root pointer. Readers need no locks at all.
- Copying full maps is O(N) — unacceptable at 10M documents. Persistent data structures (e.g. Hash Array Mapped Tries) reduce this to O(log N) copied nodes per write.
- Best fit when reads vastly outnumber writes and slightly stale reads are acceptable (search-like workloads).
Consistency guarantees to state explicitly
- Individual operations are linearizable under Options A and B.
query_allreturns a point-in-time snapshot under A and C; under B it is consistent only across the queried tag stripes.- All return values must be copies of internal sets, never live references. Returning a live set exposes callers to concurrent modification errors and data races.
6. Reference Implementation (Option A)
import threading, unicodedata
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Document:
id: str
title: str
@dataclass
class Tag:
key: str
display: str
class RWLock:
def __init__(self):
self._readers = 0
self._mutex = threading.Lock()
self._write_lock = threading.Lock()
def read_acquire(self):
with self._mutex:
self._readers += 1
if self._readers == 1:
self._write_lock.acquire()
def read_release(self):
with self._mutex:
self._readers -= 1
if self._readers == 0:
self._write_lock.release()
def write_acquire(self): self._write_lock.acquire()
def write_release(self): self._write_lock.release()
class DocumentTagStore:
def __init__(self):
self._lock = RWLock()
self._docs: dict[str, Document] = {}
self._tags: dict[str, Tag] = {}
self._doc_tags: dict[str, set[str]] = {}
self._tag_docs: dict[str, set[str]] = {}
@staticmethod
def _normalize(name: str) -> str:
return unicodedata.normalize("NFKC", name).strip().casefold()
def add_tag(self, doc_id: str, name: str) -> bool:
key = self._normalize(name)
self._lock.write_acquire()
try:
if doc_id not in self._docs:
raise KeyError(f"Document {doc_id!r} not found")
if key not in self._tags:
raise KeyError(f"Tag {name!r} not found")
if key in self._doc_tags[doc_id]:
return False
self._doc_tags[doc_id].add(key) # both sides updated
self._tag_docs[key].add(doc_id) # under the same lock
return True
finally:
self._lock.write_release()
def query_all(self, names: list[str], limit: Optional[int] = None) -> list[str]:
if not names:
raise ValueError("Tag list must not be empty")
keys = list({self._normalize(n) for n in names})
self._lock.read_acquire()
try:
sets = []
for k in keys:
if k not in self._tag_docs:
return []
sets.append(self._tag_docs[k])
sets.sort(key=len)
result = [d for d in sets[0] if all(d in s for s in sets[1:])]
return result[:limit] if limit else result
finally:
self._lock.read_release()
7. Testing Concurrency Correctness
- Invariant checker: after every test, assert
doc_tagsandtag_docsare fully consistent. Run this under a single lock after the storm settles. - Stress test: launch many threads performing random
add_tag/remove_tag/delete_documentoperations simultaneously. Check for exceptions, hangs, and invariant violations. - Deterministic interleaving: use Python's
threading.Barrieror mocking to force specific interleaving sequences that would expose a race condition in a naive implementation. - Static analysis: tools like
ThreadSanitizer(for C/C++ or Go equivalents) orHelgrindcan detect races that stress tests miss.
Common Mistakes to Avoid
- Returning a live internal set instead of a copy — any caller iterating it can race with a writer.
- Acquiring locks in an inconsistent order across methods — the only reliable fix is a documented and enforced global lock order.
- Treating
ConcurrentHashMapas sufficient for multi-step operations. - Letting
delete_tagsilently leave orphan edges indoc_tags— always clean up both sides. - Allowing
query_all([])to return all documents — reject empty lists explicitly.