KatInterview

In-Memory Document-Tag Store with Thread-Safe Concurrency

System DesignModel answer
HardModel answerSystem Designconcurrencyindexingapi-design

Last 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?