PrepStack › Databases › Database Design & Normalization
Database Design & Normalization interview cheat sheet
Keys, ER modelling, 1NF→BCNF, denormalization and real-world schema trade-offs
Design rounds check whether you can turn a fuzzy requirement into tables, keys and constraints that keep data correct, and whether you know when to bend the rules for speed. Expect definitions (keys, normal forms, anomalies), a decomposition exercise, and a whiteboard schema such as an online shop or a URL shortener. Read the 15-minute revision, run the SQLite snippets in your head, then switch to Quiz mode and answer out loud.
15-minute revision
- RDBMS = DBMS that stores data as relations (tables) with keys, constraints, joins, SQL and ACID transactions.
- Super key ⊇ candidate key (minimal super key) → one is chosen as primary key; the rest are alternate keys. A foreign key points at a candidate key of another table.
- Surrogate key = meaningless generated ID; natural key = real-world value (email, ISBN). Common default: surrogate PK +
UNIQUEon the natural key. - Referential actions on delete/update:
CASCADE,SET NULL,SET DEFAULT,RESTRICT,NO ACTION(default). Index the FK column on the child side. - Cardinality: 1:1 → FK with
UNIQUE; 1:N → FK on the many side; M:N → junction table with a composite PK of both FKs. - A weak entity has no key of its own; its PK = owner's PK + a partial key (order_id, line_no).
- Functional dependency X → Y: the same X always gives the same Y. Normal forms are rules about which FDs are allowed.
- Anomalies of a bad table: insert (can't add a fact without an unrelated one), update (same fact in many rows), delete (losing a fact by deleting another).
- 1NF atomic values, no repeating groups. 2NF no partial dependency on part of a composite key. 3NF no transitive dependency (non-key → non-key).
- BCNF: for every non-trivial X → Y, X is a super key. 3NF allows Y to be prime; BCNF does not. BCNF may lose dependency preservation.
- 4NF removes independent multi-valued facts in one table; 5NF removes join dependencies. Rare in interviews beyond the definition.
- Denormalize only for measured read hot spots: counters, snapshots, read models. You then own keeping copies in sync.
- OLTP = many small writes, normalized. OLAP = big scans/aggregates, star schema (fact + dimensions), columnar storage.
- Random UUIDv4 PKs fragment B-tree indexes; UUIDv7 is time-ordered (RFC 9562) and inserts near the right edge like an auto-increment.
- Soft delete =
deleted_at+ partial unique index + filtered views. Audit =created_at/updated_at/created_byor a separate history table. - Zero-downtime migrations use expand → migrate → contract: add new shape, dual-write and backfill, switch reads, then drop the old shape.
Relational foundations
DBMS vs RDBMS & relational terms
An RDBMS stores data as relations (tables) linked by keys and protects it with constraints and transactions.
- A DBMS is any software that stores and manages data: files, hierarchical, network, document or key-value stores all count.
- An RDBMS follows Codd's relational model: data lives in relations (tables), rows are related through keys, and you query with a declarative language (SQL).
- Relational terms: relation = table, tuple = row, attribute = column, domain = set of allowed values, degree = number of columns, cardinality = number of rows.
- A relation is a set: rows have no order and (in theory) no duplicates. That is why every table should have a key.
- Integrity rules: entity integrity (PK is never NULL) and referential integrity (every FK value matches an existing parent key or is NULL).
- The schema is the structure (tables, columns, constraints); an instance is the data at one moment.
Interview questions
- What is the difference between a DBMS and an RDBMS?
- Define tuple, attribute, domain, degree and cardinality.
- What are entity integrity and referential integrity?
Keys: super, candidate, primary, foreign, surrogate
A candidate key is a minimal set of columns that identifies a row; you pick one as primary key and enforce the rest with UNIQUE.
- Super key: any set of columns that uniquely identifies a row.
{emp_id, name}is a super key ifemp_idalone is. - Candidate key: a super key with no extra columns (minimal). A table can have several:
emp_id,email,ssn. - Primary key: the candidate key you choose as the main identifier. Unique and NOT NULL, one per table. The rest are alternate keys and get
UNIQUEconstraints. - Composite key: a key of two or more columns, typical in junction tables (
student_id, course_id). - Foreign key: column(s) in a child table that reference a candidate key (usually the PK) of a parent table.
- Surrogate key is generated and meaningless (
BIGINTidentity, UUID). Natural key comes from the domain (ISBN, country code). Natural keys can change or be reused; surrogates never do.
Interview questions
- Difference between a super key, a candidate key and a primary key?
- Primary key vs unique key?
- Would you use a natural key or a surrogate key?
- Can a foreign key reference a non-primary-key column?
Constraints & referential actions
Constraints let the database reject bad data; referential actions decide what happens to children when a parent changes.
- Column/table constraints:
NOT NULL,UNIQUE,PRIMARY KEY,FOREIGN KEY,CHECK,DEFAULT. PostgreSQL also hasEXCLUDE(for example, no overlapping bookings). - Referential actions on
ON DELETE/ON UPDATE:CASCADE(delete or update children too),SET NULL,SET DEFAULT,RESTRICT(fail at once),NO ACTION(default; fail at end of statement, or at commit if deferred). - Pick by meaning: order lines CASCADE with the order; a ticket's assignee is SET NULL when a user leaves; an invoice's customer is RESTRICTed so history is never lost.
- Deferrable constraints (PostgreSQL
DEFERRABLE INITIALLY DEFERRED) are checked at commit. Useful for circular references or swapping unique values. - Constraints are the last line of defence: app validation can be bypassed by scripts, other services or race conditions; the DB constraint cannot.
- SQLite only enforces foreign keys after
PRAGMA foreign_keys = ON, per connection.
Interview questions
- What is the difference between
RESTRICTandNO ACTION? - When would you use
ON DELETE CASCADEand when would you avoid it? - Why keep constraints in the database if the application already validates?
ER modelling
ER modelling: entities, attributes, weak entities
An ER model names the things (entities), their facts (attributes) and how they relate, before you write any table.
- Entity = a thing you store facts about (Customer, Order). Entity set = all of them; it becomes a table.
- Attribute kinds: simple (price), composite (address = street + city + zip), multi-valued (phone numbers) → separate table, derived (age from birth date) → usually not stored, key attribute (underlined).
- A relationship links entities (Customer *places* Order). It has a cardinality (1:1, 1:N, M:N) and a participation: total (every order must have a customer) or partial.
- A weak entity cannot be identified by its own attributes. It depends on an owner through an identifying relationship, and its key is owner key + partial key (
order_id, line_no). - Relationships can have their own attributes (an enrollment's
grade). For M:N these become columns of the junction table. - Notations: Chen (diamonds for relationships) in textbooks, crow's foot in industry tools. Know how to read both.
Interview questions
- What is a weak entity? Give an example.
- How do you map a multi-valued attribute to tables?
- What is the difference between total and partial participation?
Cardinality: 1:1, 1:N, M:N & junction tables
Put the FK on the many side for 1:N, add UNIQUE to it for 1:1, and use a junction table for M:N.
- 1:N (customer → orders): FK
customer_idinorders. Never put a list of order ids incustomer. - 1:1 (user → profile): FK in the dependent table with
UNIQUE, or share the PK (profile.user_idis both PK and FK). Use it to split rarely-read or sensitive columns, or optional data. - M:N (students ↔ courses): a junction / associative / bridge table
enrollment(student_id, course_id)with a composite PK, which also stops duplicate pairs. - The junction table can carry relationship data:
enrolled_at,grade,role. At that point it is often a real entity (Enrollment, Membership). - Add a second index on the junction in reverse order (
course_id, student_id) so lookups from both sides are fast. - Self-referencing relationships:
employee.manager_id → employee.id(1:N tree) orfollows(follower_id, followee_id)(M:N graph).
Interview questions
- How do you model a many-to-many relationship?
- Where does the foreign key go in a one-to-many relationship?
- When would you split data into a 1:1 table?
Normalization
Functional dependencies & finding keys
X → Y means rows that agree on X always agree on Y; closures of attribute sets tell you the candidate keys.
- Functional dependency X → Y: for any two rows, equal X values force equal Y values.
emp_id → name,zip → city. - Trivial FD: Y is a subset of X (
{a,b} → a). Normal forms only care about non-trivial ones. - Full dependency: Y depends on the whole key. Partial: Y depends on part of a composite key (2NF problem). Transitive: key → A → B where A is not a key (3NF problem).
- Armstrong's axioms: reflexivity (Y ⊆ X ⇒ X → Y), augmentation (X → Y ⇒ XZ → YZ), transitivity (X → Y, Y → Z ⇒ X → Z). Derived: union, decomposition, pseudo-transitivity.
- Attribute closure X⁺ = everything X determines. If X⁺ contains all attributes, X is a super key; if no proper subset does, it is a candidate key.
- Prime attribute = belongs to some candidate key. Matters for 2NF/3NF definitions.
- Trick: attributes that never appear on any right-hand side must be in every candidate key.
Interview questions
- What is a functional dependency?
- How do you find the candidate keys of a relation from its FDs?
- What is the difference between a partial and a transitive dependency?
Insert, update & delete anomalies
When one table stores several independent facts, adding, changing or deleting one fact damages another.
- Update anomaly: the same fact is copied in many rows; changing it in one row and not the others leaves the data contradicting itself.
- Insert anomaly: you cannot record one fact without inventing another, e.g. you cannot add a new course until a student enrols.
- Delete anomaly: removing one fact wipes out another, e.g. the last student drops a course and the course's instructor is forgotten.
- Root cause: columns that depend on different keys share one table, so a single row mixes several facts.
- Fix: decompose the table so each fact is stored once, linked by keys. That is what normalization does.
Interview questions
- What are insert, update and delete anomalies?
- How does normalization remove anomalies?
1NF, 2NF, 3NF with a worked example
1NF: atomic values. 2NF: no partial dependencies. 3NF: no transitive dependencies. In short, every non-key column depends on the key, the whole key, and nothing but the key.
- 1NF: every column holds one atomic value of one type, there are no repeating groups (
phone1, phone2, phone3) and the table has a key. - 2NF: 1NF + no non-prime column depends on part of a composite key. A table with a single-column key in 1NF is automatically in 2NF.
- 3NF: 2NF + no non-prime column depends on another non-prime column (no transitive dependency). Formally: for every X → A, X is a super key or A is prime.
- Worked example:
order_line(order_id, product_id, qty, product_name, order_date, customer_id, customer_city)with key(order_id, product_id). - 2NF fix:
product_namedepends only onproduct_id, andorder_date, customer_idonly onorder_id, so move them intoproductandorders. - 3NF fix:
customer_citydepends oncustomer_id, not on the order, so move it intocustomer. - Each decomposition must be lossless: joining the pieces gives back exactly the original rows. It is lossless when the shared columns are a key of at least one piece.
Interview questions
- Explain 1NF, 2NF and 3NF with an example.
- If a table has a single-column primary key, can it violate 2NF?
- What is a lossless decomposition, and why does it matter?
- Does normalization always make queries slower?
BCNF, 4NF & 5NF
BCNF says every determinant must be a super key; 4NF and 5NF deal with multi-valued and join dependencies.
- BCNF (Boyce–Codd): for every non-trivial FD X → Y, X is a super key. It is stricter than 3NF, which also allows Y to be a prime attribute.
- Classic 3NF-but-not-BCNF case:
teaching(student, course, instructor)with FDs{student, course} → instructorandinstructor → course(each instructor teaches one course).instructoris not a super key. - Decomposing into
instructor_course(instructor PK, course)andstudent_instructor(student, instructor)is lossless, but the FD{student, course} → instructoris no longer enforceable by a single key: BCNF can lose dependency preservation. 3NF can always keep it. - 4NF: BCNF + no non-trivial multi-valued dependency (X →→ Y). Example:
employee_skill_language(emp, skill, language)where skills and languages are independent, so every skill is paired with every language. Split intoemp_skillandemp_language. - 5NF (project-join NF): no non-trivial join dependency except those implied by keys. The table cannot be split into three or more pieces that rejoin losslessly. The textbook case is agent–company–product with a cyclic business rule.
- Higher forms exist (DKNF, 6NF). 6NF shows up in temporal and some data-warehouse designs. In interviews, define them and move on.
Interview questions
- What is the difference between 3NF and BCNF?
- Give an example of a table in 3NF but not in BCNF.
- Can every relation be decomposed into BCNF while preserving dependencies?
- What does 4NF fix?
Denormalization: when and how
Copy or precompute data on purpose to speed up a proven hot read path, and own the job of keeping it consistent.
- Denormalization = deliberately storing redundant or derived data: counters (
comment_count), copied columns (author_nameon a post), precomputed aggregates, or a wide read table. - Do it after measuring: a frequent query that joins many tables or aggregates millions of rows, and indexes or caching are not enough.
- Keep copies in sync with triggers, application code in the same transaction, materialized views (refreshed), or async events (CDC/outbox) if eventual consistency is fine.
- Not all copies are denormalization: an order line's unit price is a historical snapshot, not a duplicate. It must not change when the catalog price does.
- Costs: more write work, risk of drift, harder migrations. Add a reconciliation job for important counters.
- Read-heavy systems (feeds, dashboards, search) and OLAP are where denormalized models are the norm.
Interview questions
- When would you denormalize a schema?
- Is storing the price on an order line denormalization?
- How do you keep denormalized data consistent?
Practical schema decisions
Choosing data types
Use the narrowest type that fits the meaning: exact decimals or integer cents for money, timestamptz for instants, real types instead of strings.
- Money:
NUMERIC(12,2)/DECIMAL, or integer minor units (cents) plus a currency column. NeverFLOAT/DOUBLE, which are binary approximations. - Time: store instants as
timestamptz(PostgreSQL) in UTC; usedatefor calendar dates (birthdays); keep the user's time zone name separately if you need local times. - IDs:
BIGINTidentity rather thanINTfor busy tables (INT tops out near 2.1 billion), orUUID(16 bytes), not UUID stored as a 36-char string. - Strings: in PostgreSQL
textandvarchar(n)perform the same; use aCHECKorvarchar(n)when a real limit exists. MySQLutf8mb4is needed for full Unicode (emoji). - Enums: a lookup table (flexible, can hold labels) or a
CHECK (status IN (...)). Native ENUM types are fast but harder to change. - Booleans as
boolean, JSON asjsonbfor flexible attributes, but keep anything you filter, join or constrain in real columns. - SQLite uses dynamic typing with type affinity;
STRICTtables (3.37+) make it reject wrong types.
Interview questions
- How should you store money in a database?
timestampvstimestamptzin PostgreSQL?- When would you use a JSON column instead of real columns?
Auto-increment vs UUID vs UUIDv7
Sequential integers are small and fast; random UUIDs are globally unique but fragment indexes; UUIDv7 gives you both uniqueness and time order.
- Auto-increment / identity (
BIGINT GENERATED ALWAYS AS IDENTITY): 8 bytes, ordered, great index locality. But ids are guessable, leak volume, and need a central counter, so they are awkward when merging databases or generating ids offline. - UUIDv4: 122 random bits, 16 bytes, generate anywhere without coordination. Random values land on random B-tree pages → page splits, cache misses, bloated indexes, more WAL.
- UUIDv7 (RFC 9562, 2024): 48-bit Unix millisecond timestamp + version + random bits. Roughly sorted by creation time, so inserts go to the right edge like a sequence.
- PostgreSQL 18 ships a built-in
uuidv7()function; older versions use an extension or generate ids in the app. Store as the nativeuuidtype, never as text. - UUIDv7 leaks the creation time. If that matters, keep an internal key and expose a random public id or an opaque slug.
- Other options: Snowflake-style 64-bit ids (timestamp + machine + sequence), ULID (a 128-bit time-ordered id with a Crockford base32 text form).
Interview questions
- UUID or auto-increment primary key?
- Why do random UUIDs hurt insert performance?
- What is inside a UUIDv7?
Soft deletes & audit columns
Soft delete marks a row as deleted instead of removing it; audit columns and history tables record who changed what and when.
- Soft delete:
deleted_at timestamptz NULL(better than a boolean, since it records when). Queries must filterWHERE deleted_at IS NULL, ideally through a view or ORM default scope. - Unique constraints break with soft deletes (a deleted user still holds the email). Fix with a partial unique index
WHERE deleted_at IS NULL. - FKs still point at soft-deleted parents, and
ON DELETE CASCADEnever fires. Decide how children behave. - Alternatives: move deleted rows to an archive table, or rely on a history/audit table and hard delete. GDPR erasure may legally require a real delete or anonymization.
- Audit columns:
created_at,updated_at,created_by,updated_by, maybeversionfor optimistic locking. Set them with defaults and triggers so no code path forgets. - For a full trail use an audit/history table (old and new values, actor, time) written by triggers or CDC, or system-versioned temporal tables where supported (SQL Server, MariaDB).
Interview questions
- What are the pros and cons of soft deletes?
- How do you keep an email unique among active users when using soft deletes?
- How would you audit all changes to a table?
Polymorphic associations
One table pointing at “one of several parent tables” loses foreign keys; use exclusive arcs, a shared supertype, or separate tables instead.
- The Rails-style pattern:
comment(commentable_type TEXT, commentable_id INT)can point at a post or a photo. Easy in an ORM, but no FK is possible, so orphans and typos slip in. - Exclusive arc: one nullable FK per parent (
post_id,photo_id) plusCHECKthat exactly one is set. Real FKs, simple joins; good for a few parent types. - Shared supertype: a
commentable(id)table;post.idandphoto.idare FKs to it; comments referencecommentable. Real FKs and any number of types, at the cost of one more table. - Separate tables:
post_comment,photo_comment. Simplest integrity, but duplicated structure and harder “all comments” queries. - Related inheritance mappings: single table (one table + type column, many NULLs), class table (base + child tables with shared PK), concrete table (one full table per subtype).
Interview questions
- What is a polymorphic association and what is wrong with it?
- How would you let comments attach to posts, photos and videos with real foreign keys?
- Single-table vs class-table inheritance?
Multi-tenancy schema patterns
Tenants can share tables (tenant_id column), get their own schema, or get their own database; isolation goes up as density goes down.
- Shared schema (pool): every table has
tenant_id; one set of tables for all. Cheapest and easy to migrate, but one missing filter leaks data and noisy neighbours share resources. - Schema per tenant (PostgreSQL schemas / MySQL databases): same tables duplicated per tenant. Better isolation and per-tenant restore, but migrations run N times and catalogs grow.
- Database per tenant (silo): strongest isolation, per-tenant tuning, encryption keys and region. Highest cost and operational effort. Often used only for large/enterprise tenants.
- In a shared schema, lead composite keys and indexes with
tenant_id(PRIMARY KEY (tenant_id, id),INDEX (tenant_id, created_at)), and include it in FKs so a row can only reference rows of the same tenant. - Enforce isolation in the database, not just in code: PostgreSQL row-level security policies on
tenant_id = current_setting('app.tenant_id'). - Scale out by sharding on
tenant_id(e.g. Citus distributes tables by a tenant column). Hybrid models move big tenants to their own DB.
Interview questions
- How would you design a multi-tenant SaaS database?
- What are the trade-offs of schema-per-tenant?
- How do you prevent one tenant from seeing another's data?
Analytics, evolution & choosing a store
OLTP vs OLAP, star vs snowflake
OLTP systems run many small normalized transactions; OLAP systems scan and aggregate history in denormalized star schemas.
- OLTP: orders, payments, logins. Short transactions touching few rows, high concurrency, normalized (3NF), row-oriented storage, indexes on keys.
- OLAP: reports, dashboards, BI. Few users running large scans and aggregates over history, read-mostly, loaded by ETL/ELT, often columnar (BigQuery, Snowflake, Redshift, ClickHouse).
- Star schema: a central fact table (measures such as
amount,qty+ FKs) surrounded by denormalized dimension tables (date, product, store, customer). One join per dimension. - Snowflake schema: dimensions are normalized into sub-dimensions (product → category → department). Less redundancy, more joins.
- Grain = what one fact row means (“one line item per order”). Decide it first. Dimensions often use surrogate keys and slowly changing dimension (SCD) handling, e.g. Type 2 adds a new row with valid-from/valid-to.
- Fact types: transaction, periodic snapshot, accumulating snapshot. Measures can be additive (amount), semi-additive (balance) or non-additive (ratios).
Interview questions
- What is the difference between OLTP and OLAP?
- Star schema vs snowflake schema?
- What is a slowly changing dimension?
Schema migrations & zero-downtime changes
Version every schema change, keep each step backward compatible, and use expand → migrate → contract so old and new code run side by side.
- Use a migration tool (Flyway, Liquibase, Alembic, Rails/Django/Prisma migrations): versioned scripts in git, applied in order, recorded in a history table.
- During a rolling deploy, old and new app versions run at the same time, so every schema state must work with both.
- Expand/contract (parallel change): 1) expand: add the new column/table, nullable or with a default; 2) deploy code that writes both; 3) backfill in small batches; 4) switch reads to the new shape; 5) stop writing the old; 6) contract: drop the old column.
- Renaming a column directly breaks the running old version; do it as add-new + dual-write + backfill + drop-old.
- Lock awareness (PostgreSQL):
CREATE INDEX CONCURRENTLY; add FKs/CHECKs asNOT VALIDthenVALIDATE CONSTRAINT; set a shortlock_timeoutso a blockedALTERdoes not queue every other query behind it. - Adding a column with a constant default is metadata-only in PostgreSQL 11+ and MySQL 8 (instant ADD COLUMN), but changing a column's type usually rewrites the table.
- Make migrations idempotent where possible, small, and reversible; never edit a migration that already ran in production.
Interview questions
- How do you rename a column with zero downtime?
- How do you add a NOT NULL column to a huge table safely?
- Why can a simple
ALTER TABLEtake production down even if it is fast? - How do you handle migrations in a microservice or CI/CD setup?
SQL vs NoSQL: choosing a store
Choose relational for relationships, constraints and transactions; choose a NoSQL model when access patterns are simple, known, and need massive scale or a special data shape.
- Relational: fixed schema, joins, constraints, ACID, flexible ad-hoc queries. Scales up easily and out with replicas, partitioning or distributed SQL (CockroachDB, Spanner, Citus).
- Document (MongoDB, Firestore): JSON-like aggregates read and written as a unit; good when data is naturally nested and schemas vary.
- Key-value (Redis, DynamoDB): fastest lookups by key; you design tables around access patterns, not entities.
- Wide-column (Cassandra, ScyllaDB, Bigtable): huge write throughput, partition key + clustering key, query-first modelling, tunable consistency.
- Graph (Neo4j): many-hop relationship queries (friends of friends, fraud rings). Time-series and search engines are other specialised stores.
- NoSQL modelling is usually denormalized and query-driven: you duplicate data so each query hits one partition. Modern Postgres (
jsonb) and MongoDB (multi-document transactions) blur the lines.
Interview questions
- When would you choose NoSQL over SQL?
- How does schema design differ in DynamoDB or Cassandra compared with SQL?
- Can a relational database scale horizontally?
Design exercises
Design: e-commerce schema
Customers, products, orders and order lines with price snapshots, stock checks and a clear order status lifecycle.
- Core entities:
customer,address,product(+product_variantfor size/colour SKUs),category,cart/cart_item,orders,order_item,payment,shipment,inventory. order_itemstores quantity and unit price at purchase time (snapshot), plus product id for reference. Order also snapshots shipping address and currency.- Order status as a constrained column (
pending → paid → shipped → delivered / cancelled / refunded) plus anorder_status_historytable for audit. - Stock: decrement inside the order transaction with a guard (
UPDATE ... SET stock = stock - :q WHERE id = :id AND stock >= :q), or reserve stock with an expiring reservation row. - Categories are a tree (
parent_id) or M:N (product_category) if a product sits in several. Reviews:review(product_id, customer_id, rating CHECK 1–5, UNIQUE(product_id, customer_id)). - Payments: separate table, many attempts per order, store the provider's id and an idempotency key with a
UNIQUEconstraint.
Interview questions
- Design the schema for an online store.
- How do you prevent overselling stock?
- How would you model product variants like size and colour?
Design: URL shortener & social feed
A URL shortener is one hot key-value lookup; a social feed is a follow graph plus either fan-out-on-read or fan-out-on-write timelines.
- URL shortener:
short_url(code PK, long_url, owner_id, created_at, expires_at). Reads dominate (often 100:1), so it is effectively key → value with a cache in front. - Code generation: base62 of a sequence id (short, no collisions, but guessable), random base62 with a unique constraint and retry, or a hash of the URL (dedup, but collisions to handle). 7 base62 chars give about 3.5 trillion codes.
- Store clicks in a separate append-only
clicktable or stream, aggregated asynchronously; neverUPDATE short_url SET clicks = clicks + 1on every hit. - Social feed:
user,follow(follower_id, followee_id, PRIMARY KEY both),post(id, author_id, created_at, body),like(user_id, post_id, PRIMARY KEY both); indexpost(author_id, created_at DESC). - Fan-out on read (pull): build the feed at read time from followees' recent posts. Simple and cheap writes; slow for users following thousands.
- Fan-out on write (push): on each post insert
(follower_id, post_id, created_at)into each follower'stimelinetable/cache. Fast reads; celebrity posts cause write storms. Real systems use a hybrid (push for normal users, pull for celebrities). - Paginate feeds with keyset/cursor pagination (
WHERE (created_at, id) < (:ts, :id)), notOFFSET.
Interview questions
- Design the database for a URL shortener.
- How would you generate short codes without collisions across many servers?
- Fan-out on write vs fan-out on read for a news feed?
- Why use keyset pagination instead of OFFSET for a feed?