Data modeling
Overview
Once you know what a system does, the next question is what data it keeps. A data model names the things the system stores, what each one contains and how they relate. It is the bridge between requirements and storage choices, and in interviews it usually comes right after the API.
Entities, attributes and keys
- An entity is a kind of thing you store: users, photos, orders.
- Attributes are its fields: a photo has a URL, a caption and a creation time.
- A primary key (PK) uniquely identifies each row or record.
- A foreign key (FK) is a field that points at another entity’s primary key.
Relationships
- One-to-one (1:1): a user has one profile settings record. Often merged into one table unless the parts are accessed separately.
- One-to-many (1:N): a user has many photos. Put the foreign key (
user_id) on the “many” side. - Many-to-many (N:M): users like many photos and photos are liked by many users. Use a join table (
likes) with two foreign keys.
A self-relationship links an entity to itself: follows connects a user to another user.
Composite primary keys turn business rules into guarantees. Making (user_id, photo_id) the key of likes means a user physically can’t like the same photo twice.
Choosing IDs
Small systems use auto-incrementing integers. At scale that causes problems: one database must hand out every number, IDs reveal how big you are, and merging data from shards creates collisions. Common alternatives:
| ID type | Size | Sortable by time? | Notes |
|---|---|---|---|
| Auto-increment | 8 bytes | Yes | Needs one central counter |
| UUID v4 | 16 bytes | No | Generate anywhere; random inserts fragment B-tree indexes |
| UUID v7 / ULID | 16 bytes | Yes | Time-ordered prefix, generate anywhere |
| Snowflake-style | 8 bytes | Yes | Timestamp + machine ID + sequence; needs machine IDs |
The unique ID generator case study in week 7 designs a Snowflake-style service.
Time, money and other details
Small modelling choices cause big bugs later:
- Timestamps: store in UTC, with time zones applied when displaying.
- Money: use integer minor units (paise, cents) or a decimal type, never floating point, and store the currency.
- Soft deletes: a
deleted_atcolumn keeps history but every query must filter it. - Status fields: an explicit
statuswith allowed values (pending, paid, shipped) makes state machines visible. - Created/updated times on every table help debugging, syncing and analytics.
From model to storage
The same logical model can be stored in different ways:
- In a relational database, entities become tables and relationships become foreign keys and joins.
- In a document database, you might embed a user’s settings inside the user document and keep photos separate.
- In a wide-column or key-value store, you design one table per query, often duplicating data (see the access-patterns lesson).
That’s why you model first and pick the database second.
Check the model against the queries
List the main queries and walk them through the model:
- “Show a user’s photos, newest first” →
photosfiltered byuser_id, sorted bycreated_at; needs an index on(user_id, created_at). - “Count likes on a photo” → counting
likesrows byphoto_idis fine for small numbers, but a popular photo may have millions; store a pre-computedlike_counttoo. - “Show photos from people I follow” → a join between
followsandphotos, expensive at scale; the news feed case study solves this differently.
If a key query is awkward, change the model now rather than after the data has grown.
In an interview
Write three to five entities with their key fields and keys, draw the relationships, and say which store you’d use and why. Keep it brief, but include the fields your later design depends on, such as timestamps for sorting and IDs for sharding.
Recap
A data model lists entities, attributes, keys and relationships. One-to-many uses a foreign key, many-to-many a join table, and composite keys enforce uniqueness rules. Choose IDs that can be generated without a central bottleneck, store time in UTC and money as integers, and always test the model against the queries it must serve.
Model an event-booking app
Model the data for a simple event-booking app: organisers create events at venues; each event has a date and a number of seats; users book one or more seats for an event; users can leave one review per event they attended. List the entities with their main fields, mark primary and foreign keys, and describe each relationship (1:1, 1:N or N:M).
Entities:
-
Relationships:
-Entities:
- users (id PK, name, email UNIQUE, created_at)
- venues (id PK, name, city, capacity)
- events (id PK, organiser_id FK -> users, venue_id FK -> venues, title, starts_at, total_seats)
- bookings (id PK, event_id FK -> events, user_id FK -> users, seats, status, created_at)
- reviews (event_id FK, user_id FK, rating, text, created_at; PK (event_id, user_id))
Relationships:
- user (organiser) 1:N events
- venue 1:N events
- event 1:N bookings; user 1:N bookings
(so users and events are N:M through bookings)
- users N:M events through reviews, limited to one review per pair by the composite PK
Notes: store seats left on the event or compute it from bookings (a trade-off covered
in the ticket-booking case study); index bookings by user_id for "my bookings".Summary
- A data model lists entities, their attributes, a primary key for each, and the relationships between them.
- One-to-many uses a foreign key on the 'many' side; many-to-many uses a join table with two foreign keys.
- Composite primary keys enforce rules such as 'one like per user per photo'.
- At scale, IDs should be unique without a central counter: UUIDs or time-ordered IDs such as Snowflake or ULID.
- Model the data first, then check it against every query the system must answer.