← Questions

Thread-safe document and tag classes

0
AmazonOO designLast asked Aug 2025

An object-oriented design interview question asked in Amazon's coding round, last asked Aug 2025. It tests object-oriented design and concurrency.

Design the classes for a system that stores documents and the tags on them, and make every operation safe when many threads call it at once. Write the core classes and methods in code, and explain the locking choices.

Requirements

  • Functional: create and delete documents; add a tag to a document and remove it; list a document's tags; list the documents carrying a tag; rename or delete a tag everywhere.
  • Non-functional: many concurrent readers and writers; the document-to-tags and tag-to-documents views never disagree as seen by a reader; reads are much more common than writes; avoid one global lock if you can.

Clarifying questions

  • How many documents and tags, and how many tags per document?
  • Are tags free text (case-sensitive?) or from a fixed list?
  • Which consistency matters: must a reader never see a tag on a document while the reverse index lacks it?
  • Is this one process in memory, or must it persist?
  • Which operations are the hot path?

What a strong answer covers

  • Classes: Document (id, content, its tag set), Tag (name, normalized key), and a TagService or repository that owns two indexes, document id to tag set and tag to document id set.
  • Methods with clear return values: add_tag(doc_id, tag) -> bool, remove_tag(doc_id, tag) -> bool, tags_of(doc_id) -> set[str], documents_with(tag) -> set[str], delete_document(doc_id).
  • Keeping the two indexes in step: one lock per document plus one per tag (lock striping), always taken in a fixed order to prevent deadlock; or a read-write lock for read-heavy use.
  • Returning copies or immutable snapshots, never the internal mutable sets.
  • What ConcurrentHashMap-style structures do and do not give you (each map is safe, the pair of maps is not).
  • How to test it: concurrent add and remove of the same tag, delete racing with add, and a stress test that checks both indexes agree.

Follow-ups

  • Find documents that have all of a set of tags, or any of them.
  • Tag counts and the most popular tags, kept current under concurrent writes.
  • Make the store durable and shared across several servers.

Where it's asked

  • Amazon · Coding · Last asked Aug 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI

What it tests

object-oriented design · concurrency

Your canvas
Draw your answer hereBoxes, arrows and notes, saved for you to come back to.Sign in to start drawing