Data Modeling
How to list the entities, keys and relationships of a design, and when to go further into access patterns, denormalization and partition keys.
On this page
Data modeling is deciding what the system stores: which entities exist, which fields identify and describe each one, and how the entities relate to each other. In a system design interview it is the step between the API and the high-level design, and the other steps depend on it because every request in the design reads or writes these entities.
Every interview expects the same three things from this step: the list of entities, their key fields and the relationships between them. Everything else, such as access patterns, denormalization and partition keys, is worth doing only when the problem needs it or the interviewer asks.
Where the data model sits
What to do every time
The running example is a restaurant reservation system, where diners book a table for a time.
List the entities
An entity is a kind of thing the system has to remember. Take them from the nouns in the requirements: restaurant, dining table, slot (a table at a particular date and time that can be booked), reservation and diner. Give each entity an id that never changes, and leave out nouns that are only fields, such as a restaurant's name.
Write the key fields
For each entity, write the id, the fields the requirements mention and the fields that link it to other entities. You do not need every column. Name the ones that the design will use, such as the party size and the status of a reservation.
Show how the entities relate
Say for each pair whether the relationship is one-to-many or many-to-many, and put a foreign key on the "many" side. A restaurant has many tables, and each table row stores its restaurant_id. A diner has many reservations, and each reservation stores its user_id. A many-to-many relationship, such as dishes and menus, needs a separate table holding one row for each pair.
restaurants (restaurant_id PK, name, city, cuisine, timezone)
tables (restaurant_id, table_id, seats,
PRIMARY KEY (restaurant_id, table_id))
slots (restaurant_id, slot_date, slot_time, table_id,
reservation_id NULL, -- NULL means the slot is free
PRIMARY KEY (restaurant_id, slot_date, slot_time, table_id))
reservations (restaurant_id, reservation_id, table_id, slot_date, slot_time,
user_id, party_size, status, created_at,
PRIMARY KEY (restaurant_id, reservation_id))The slots table has one row for each bookable table at each time. Booking is a conditional update that sets reservation_id only where it is still NULL. If the update changes no row, someone else booked the slot first and the API returns a 409. The check and the write happen in one statement, so two diners cannot both succeed.
Saying this much out loud takes about two minutes and usually satisfies the interviewer. Name the main entities, say what identifies each one, say how they connect, and move on to the high-level design.
What to do only when the problem needs it
The four topics below are not part of every answer. Raise them when the scale, the access pattern or the interviewer's questions make them relevant, and keep each one short.
Access patterns
An access pattern is one way the system reads or writes the data, such as "list the free slots at a restaurant on a date" or "list a diner's upcoming reservations". Write them down when you have to choose between a relational database and a key-value or wide-column store, or when you have to choose keys and indexes, because each of those choices depends on which queries are frequent. For the reservation system, almost every query starts from a restaurant and a date, one starts from a diner, and searching for restaurants by city and cuisine belongs in a search index. The category of database follows from the patterns: lookups by one key suggest a key-value store, and a booking that must update two tables together suggests a relational database (see choosing a database).
Choosing keys
The primary key should be the column or columns that most queries look up. In the slots table above the key starts with restaurant_id and then slot_date, so the free slots for one restaurant and one day are stored next to each other and can be read as one range. A secondary index, described in Indexing, speeds up a query that does not start from the primary key, but every index makes writes slower, so add one only for a query that is frequent.
Denormalizing
A normalized model stores each fact once. The restaurant's name is only in the restaurants table, and a query that needs it joins to that table. A denormalized model copies the fact to where it is read, so the read becomes a single lookup, but every change has to reach every copy.
The reservation system has one place where this is worth doing. The page that lists a diner's reservations shows the restaurant name next to each one. If reservations are partitioned by restaurant, building that page means asking many partitions. A separate table keyed by user_id, with the restaurant name copied into each row, makes the page one range read.
user_reservations (user_id, slot_date, slot_time, reservation_id,
restaurant_name, -- copied on purpose
PRIMARY KEY (user_id, slot_date, slot_time, reservation_id))The cost is that this table can fall behind. If a restaurant is renamed, old rows keep the old name until they are updated, and if the update path is asynchronous, a new booking appears in the list a moment after it is confirmed. Start normalized, and denormalize one query at a time, each with a reason and a way to keep the copy up to date.
1A diner books table 7 at 19:30 at restaurant 42. The API routes by
restaurant_idto one partition.2One local transaction updates the slot (only if it is still free) and inserts the reservation. No other machine is involved.
3The transaction commits and the diner gets a
201. The booking is final, whatever happens to the list afterwards.4A
bookedevent is put on the queue. In production it is written to an outbox table in the booking transaction and published from there, so a crash cannot lose it.5The view updater upserts a row, restaurant name included, into
user_reservations. An event delivered twice is harmless because an upsert repeats the same write.6The diner opens "My reservations". It is one range read by
user_id, already sorted by time.7The updater goes down. Bookings still succeed and only the diner's list falls behind. The app can show the new booking from the 201 reply in the meantime.
Partition keys
When the data is too large or too busy for one machine, a partition key decides which machine holds each row (see sharding and partitioning). A good key keeps everything that one frequent query or one transaction needs on a single partition, and it spreads the load evenly. These two goals often conflict, and the first one matters more for correctness.
restaurant_id is the right key for slots and reservations. The booking check, the free-slot query and a restaurant's list for tonight all start from a restaurant, and the booking transaction touches the slot row and the reservation row, which share that partition. The weakness is that one extremely popular restaurant puts all its traffic on one partition.
A hash of reservation_id spreads the rows perfectly evenly, but only a lookup by reservation id starts from that value. A booking check has to look at the slots of a restaurant, which are now spread over every partition.
user_id makes a diner's list local, which is why the denormalized view above uses it. It cannot be the key for slots, because two diners booking the same table would land on different partitions.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| restaurant_id Usual default | Booking checks, free-slot reads and tonight's list each touch one partition. | One very popular restaurant sends all its traffic to a single partition. | Most queries and every booking transaction start from a restaurant. |
| Hash of reservation_id | The rows spread perfectly evenly. | A booking check has to query every partition. | Almost every read is a lookup of one item by its own id. |
| user_id | A diner's own list is on one partition. | Two diners booking the same table land on different partitions. | Only for a separate per-diner view. |
Problems interviewers probe
Double booking caused by the partition key
Suppose reservations are split across 8 partitions by a hash of the reservation id. Two diners book table 7 at 19:30 at the same moment, and their reservations hash to different partitions. Each partition checks only its own rows, finds no conflict, and commits, so the table is booked twice. The fix is to partition by restaurant_id, so that both attempts reach the same partition and the conditional update lets only one of them succeed. The general rule is that anything which must not conflict has to be decided on a single partition.
A copy that is out of date
Every denormalized copy can be stale. Say how long the delay may be, whether the staleness matters, and what repairs it. For a restaurant name a delay of a few seconds is harmless. For a seat count that decides whether a booking is allowed, it is not, and that value must be read from the table that owns it.
A hot partition
A key that sends too much traffic to one partition cannot be fixed by adding machines. The usual fix is to make the key finer, for example by splitting one stadium's slots by date or by section, or to add a queue in front of the booking page so that a burst is spread over time.
In the interview
Start with the entities, keys and relationships, which take about two minutes. Then ask whether the interviewer wants to go deeper, or go deeper yourself when the problem has a conflict that needs a transaction or a scale that needs partitioning, and say why: "Bookings for one restaurant must not conflict, so I'll partition by restaurant."
Questions to expect:
- "What are the main entities and how do they relate?" Name each one, say what identifies it, and say where the foreign keys are. For the reservation system, a restaurant has many tables, each table has many slots, and a reservation takes one slot for one diner. Mention the one relationship that is many-to-many, if there is one.
- "Which database would you use for this?" Look at the access patterns and the transactions. A booking updates a slot and inserts a reservation together and must not conflict, so a relational database fits. If the data were only looked up by one key at a very high rate, a key-value store would fit.
- "How do you stop two users booking the same slot?" Make the check and the write one atomic step, either a conditional update on the slot row or a unique constraint. Do not read the slot, check it in the application and then write it, because two requests can interleave between the read and the write.
- "How would you partition this data?" Pick the key that keeps each transaction on one partition, here
restaurant_id. Then say what it costs, which is that a very popular restaurant becomes a hot partition, and how you would handle that if it came up. - "Why not just add a secondary index on
user_id?" On one machine that is fine. On a partitioned store a global index is itself a separately partitioned copy of the data, and it is updated either asynchronously, which gives the same lag as a denormalized view, or inside a cross-partition transaction, which makes every booking slower. - "When would you denormalize?" When one frequent read would otherwise need data from several partitions, and a short delay in the copy is acceptable. Say how the copy is updated and what the user sees while it is behind.
How would you partition the reservations?
By restaurant. The booking check, the free-slot query and a restaurant's list for the evening all start from a restaurant, so each of them reads one partition, and a booking is a single local transaction. A diner's own list starts from the user, so I would keep a separate copy keyed by user id.
What about one hugely popular restaurant?
The number of slots is small, so the problem is many people trying to book the same rows when bookings open. The conditional update keeps the result correct, and I would put a queue in front of the booking page so that the burst is spread over time.
A booking system partitions its reservations by a hash of the reservation id. Two diners book the same table at the same time and both succeed. Why?
You copy restaurant_name into the per-diner reservation table. What does this cost?
An interviewer asks you to model a library system. What should you do first?
What to practise next
Read Indexing to see how an index makes each access pattern fast, then try Design Ticket Booking, where the same rule against double booking shapes the data model.