tezvyn:

Embed or reference likes in a document database?

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

document modeling driven by access patterns and growth.

OUTLINE

embedding is fast for small bounded lists but unbounded likes hit document size limits; referencing scales for high-cardinality, write-heavy likes.

WHAT THIS TESTS This evaluates whether you can choose between embedding and referencing in a document store based on cardinality, growth, and access patterns, which is the central skill of NoSQL data modeling.

A GOOD ANSWER COVERS Embedding the liker IDs in the post document gives excellent read locality: one fetch returns the post and its likes, and updates can be atomic within a single document. This works only when the array is small and bounded. Likes on a popular post are unbounded and can reach millions, which collides with the per-document size limit and causes the whole document to be rewritten and reindexed on every like, creating write contention on viral posts. Referencing solves growth by storing each like as its own record in a separate collection keyed by post and user, scaling to any cardinality and spreading writes, at the cost of an extra query or aggregation to assemble counts and membership. A common hybrid stores a denormalized like count on the post for fast display and a separate likes collection for membership checks and analytics.

COMMON WRONG ANSWERS Defaulting to embed because it is the document way, without considering that likes are unbounded. Ignoring the document size ceiling and the cost of rewriting a large document on each like. Forgetting the duplicate-like uniqueness constraint, which a separate collection enforces cleanly with a compound unique index.

LIKELY FOLLOW-UPS How do you prevent a user from liking twice? How do you keep the cached count accurate under concurrency? How would the answer change for comments versus likes? How do you paginate likers?

ONE CONCRETE EXAMPLE For a celebrity post with two million likes, embedding fails immediately on the size limit. A likes collection with a unique index on the post and user pair enforces single likes, supports paginated liker lists, and a counter on the post serves the displayed total without scanning.

Read the original → mongodb.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.