System designCore concepts8 min read

Data Modeling for System Design Interviews

This lesson is for software engineers who reach the "core entities" step of a system design round and want to do more than list nouns. The data model decides which queries are cheap, which are expensive and where your design will hurt at scale. By the end you will be able to go from requirements to a schema, justify each key and index by the query it serves, and handle the denormalization question the interviewer is likely to ask.

Which database to use is covered in Choosing and Scaling a Database, and how to split data across machines in Scaling Data. This lesson is about the shape of the data itself.

Where data modeling fits and how it is scored

Most interviewers expect a short list of core entities right after the requirements, then a fuller schema during the high-level design or the first deep dive. It counts toward high-level design (does the data support every requirement?) and deep dive and scalability (do the hot queries stay fast as data grows?). It also feeds trade-offs, because every denormalization trades write cost for read speed.

You do not need a full schema in the first ten minutes. Name the entities and their relationships early, then add columns, keys and indexes when you design the read and write paths.

From requirements to entities

Read each functional requirement and underline the nouns that the system stores and the verbs that connect them. "Users publish recipes; other users like and comment on them; users see a recipe page with its ingredients and like count." That gives:

  • Entities: user, recipe, ingredient, comment, like.

  • Relationships: a user writes many recipes (one-to-many), a recipe uses many ingredients and an ingredient appears in many recipes (many-to-many), a user likes many recipes and a recipe has many likers (many-to-many), a recipe has many comments in time order (one-to-many, time-ordered).

Then write down the access patterns: the queries the product actually runs, with rough frequency. This is the step most candidates skip, and it is the one that decides the schema.

  • Recipe page: the recipe, its author's name, its ingredients with quantities, the like count, the first page of comments. Very frequent.

  • "Has the current user liked this recipe?" On every recipe page view.

  • An author's recipes, newest first. Frequent.

  • Like and unlike. Frequent writes.

  • Post a comment. Less frequent.

Choosing keys

Primary keys. Use surrogate ids (generated, meaningless) rather than natural keys such as an email or a username, because natural values change and would have to be rewritten everywhere they are referenced. Choose an id format that sorts by creation time when time order matters: a ULID, a UUIDv7 or a snowflake-style 64-bit id generated by the application. Time-sortable ids keep inserts appending to the end of the index, and they let you sort by id instead of keeping a separate tiebreaker.

Join-table keys. For a many-to-many relationship, the natural key is the pair. A like is identified by (user_id, recipe_id): making that the primary key prevents a user from liking the same recipe twice without any extra check.

Partition keys. If the data will be sharded, the key you shard by must appear in the hot queries, or every query fans out to every shard. Comments are read per recipe, so recipe_id is the natural partition key for comments.

Normalize first, then denormalize for the read path

A normalized model stores each fact once. The author's name lives in users, not copied into every recipe. Writes are simple and nothing can disagree with anything else.

The cost appears on the read path. The recipe page needs a like count, and counting the likes table on every view (SELECT count(*) FROM likes WHERE recipe_id = $1) gets slower as a recipe becomes popular, exactly when it is viewed most.

Denormalizing stores a derived copy to make a read cheap: a like_count column on recipes. Now every like must also update the count, so you have traded read work for write work and for a consistency question. Two ways to keep it right:

  • Update the count in the same transaction as the like insert. Always correct, but every like on a viral recipe now contends on one row.

  • Insert the like, then update the count asynchronously (for example from a queue), accepting that the count can lag by a second or two. Better under heavy write load.

The interview rule: start normalized, denormalize only the specific fields that a frequent read needs, and say how each copy is kept up to date. "I denormalized it" without the update path is an incomplete answer.

Time-ordered data, soft deletes and history

Time-ordered data such as comments, messages or events is almost always read as "the latest N for this parent". Model it so that query is one index range scan: an index on (parent_id, created_at DESC, id DESC) returns the newest comments for a recipe directly, and pairs with cursor pagination.

Soft deletes. If deleted rows must be recoverable, auditable or kept for moderation, add a deleted_at timestamp instead of deleting. Every query must then filter it out, which is easy to forget. A partial index (WHERE deleted_at IS NULL) keeps the hot index small. Say how long soft-deleted data is kept, because privacy requests may require removing it for real.

History. When users edit content and you need old versions (for moderation, undo or audit), keep an append-only recipe_versions table and treat the main row as the latest version. This is cheaper and safer than trying to diff in place.

Worked example: the recipe app schema

Prompt: "Design the data model for a recipe sharing app: publish recipes, like and comment, and show a recipe page."

A weak answer lists tables with columns and stops:

users(id, name, email)
recipes(id, user_id, title, ingredients_text, likes)
comments(id, recipe_id, text)

Ingredients are a free-text blob, so "recipes that use tahini" is impossible. likes is a number with no record of who liked, so "has this user liked it" cannot be answered and a double-tap counts twice. Comments have no author, no time and no index for ordering.

A strong answer starts from the access patterns and justifies each choice:

CREATE TABLE users (
  id          BIGINT PRIMARY KEY,          -- time-sortable, app-generated
  username    TEXT NOT NULL UNIQUE,
  name        TEXT NOT NULL
);

CREATE TABLE recipes (
  id          BIGINT PRIMARY KEY,
  author_id   BIGINT NOT NULL REFERENCES users(id),
  title       TEXT NOT NULL,
  body        TEXT NOT NULL,
  like_count  INTEGER NOT NULL DEFAULT 0,  -- denormalized for the recipe page
  created_at  TIMESTAMPTZ NOT NULL,
  deleted_at  TIMESTAMPTZ
);
CREATE INDEX recipes_by_author
  ON recipes (author_id, created_at DESC) WHERE deleted_at IS NULL;

CREATE TABLE ingredients (
  id    BIGINT PRIMARY KEY,
  name  TEXT NOT NULL UNIQUE
);

CREATE TABLE recipe_ingredients (            -- many-to-many with attributes
  recipe_id      BIGINT NOT NULL REFERENCES recipes(id),
  ingredient_id  BIGINT NOT NULL REFERENCES ingredients(id),
  quantity       TEXT NOT NULL,
  position       SMALLINT NOT NULL,
  PRIMARY KEY (recipe_id, ingredient_id)
);
CREATE INDEX recipes_by_ingredient ON recipe_ingredients (ingredient_id);

CREATE TABLE likes (
  user_id     BIGINT NOT NULL REFERENCES users(id),
  recipe_id   BIGINT NOT NULL REFERENCES recipes(id),
  created_at  TIMESTAMPTZ NOT NULL,
  PRIMARY KEY (user_id, recipe_id)          -- one like per user per recipe
);

CREATE TABLE comments (
  id          BIGINT PRIMARY KEY,
  recipe_id   BIGINT NOT NULL REFERENCES recipes(id),
  author_id   BIGINT NOT NULL REFERENCES users(id),
  body        TEXT NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL
);
CREATE INDEX comments_by_recipe ON comments (recipe_id, created_at DESC, id DESC);

Then walk each access pattern against it, which is the part that scores:

  • Recipe page: one primary-key read on recipes, one join to users for the author, one primary-key-prefix scan of recipe_ingredients, and one range scan of comments_by_recipe for the first 20 comments. No count query, because like_count is stored.

  • "Has this user liked it?": a primary-key lookup on likes (user_id, recipe_id): one index probe whose cost does not grow with the recipe's like count.

  • Author's recipes: a range scan of recipes_by_author, which also skips soft-deleted rows.

  • Like: in one transaction, insert into likes with ON CONFLICT DO NOTHING; if a row was inserted, increment like_count. Unlike reverses both. Doing the increment only on a successful insert keeps double taps from inflating the count.

  • Recipes that use an ingredient: recipes_by_ingredient. Without that index this query would scan the whole join table, because the primary key starts with recipe_id.

That last point is worth saying aloud: a composite index only helps queries that filter on its leading column, so a many-to-many table usually needs an index in each direction.

Follow-ups to expect

  • "A recipe goes viral and gets thousands of likes per second. What breaks?" Every like updates the same recipes row, so writes queue behind a row lock. Move the count update off the request path (batch increments from a queue every second), or split the counter into several rows and sum them on read.

  • "How do you show 'liked by people you follow'?" That is a feed-style query across two relationships; precompute it or drop it to a cheaper version ("liked by 3 people you follow" computed in the background). Do not promise a live join at scale.

  • "Where would you shard this?" Recipes and their comments by recipe_id, so a recipe page stays on one shard. Likes by user_id serve "has this user liked it" but not "who liked this recipe"; say which you prioritize, or keep both directions.

  • "Could this be a document database?" Yes for the recipe body and ingredients, which are always read together. Likes and comments grow without bound and are queried independently, so they stay separate either way.

What changes with seniority

Mid-level candidates should produce entities, relationships and a schema that supports every requirement. Senior candidates drive the model from access patterns, choose keys and indexes on purpose, and name the denormalizations with their update paths. Staff candidates also discuss how the model evolves: migrating a column without downtime, backfilling a new index, and how the model splits if teams or services split.

Mistakes that cost points

  • Listing tables without access patterns. The interviewer cannot judge a schema without the queries it must serve. Write the queries first.

  • Free-text blobs for data you will query. If anyone will filter or join on it, give it its own table or column.

  • Counting on every read. Store counts that the hot path shows, and explain how they stay correct.

  • Indexes with no query behind them. Each index costs write time and storage; tie every index to a named access pattern.

  • Forgetting the reverse direction of a many-to-many. One index per direction you query.

Practice it

Pick an app you use daily and spend fifteen minutes on its data model: list the access patterns first, then the tables, then one index per hot query, then one denormalization with its update path. Then practice it live, where the interviewer will ask you to justify your keys:

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Scaling Data: Replication, Partitioning and Consistency

    Pick and defend a partition key, handle hot keys, explain leader-follower, multi-leader and quorum replication, state CAP and PACELC correctly, and match a consistency guarantee to each feature.

    8 min read

  • API Design in a System Design Interview

    Write a small, defensible API in five minutes, with resources, cursor pagination, idempotency keys, errors, versioning and a reasoned choice of REST, RPC, GraphQL or streaming, and answer the follow-ups it triggers.

    8 min read

  • System Design Interviews: The Quick Start

    Know which system design interview you face and how depth expectations change by level, then deliver any design with a six-step, 45-minute framework whose estimates drive real decisions.

    7 min read

  • ML System Design Interviews: The Quick Start

    Run an ML system design interview with an eight-step, 45-minute framework, from framing and labels to metrics, serving, drift and feedback loops, worked through on a harmful-comment classifier.

    9 min read