Picking a database means picking a data model: tables, documents, key-value pairs, wide rows or graphs. Each one makes some queries cheap and others painful. In most designs a relational database is the right default, and the other models are tools you add for a specific access pattern. This note walks through each model, then shows how to choose.
Quick comparison#
Five data models cover almost every design. Here they are side by side before you look at each one.
| Model | Examples | Strength | Typical uses |
|---|---|---|---|
| Relational | PostgreSQL, MySQL | Joins, constraints, multi-row ACID transactions | Default for core entities: users, orders, payments |
| Document | MongoDB, Firestore | Flexible, nested, self-contained records | Catalogs with varied attributes, content, profiles |
| Key-value | Redis, Memcached, DynamoDB | Very fast lookup by key | Caches, sessions, rate limits, feature flags |
| Wide-column | Cassandra, HBase | Huge write throughput, time-ordered data | Logs, metrics, IoT, chat history |
| Graph | Neo4j, Amazon Neptune | Multi-hop relationship traversal | Fraud rings, recommendations, network analysis |
Relational databases (SQL)#
Data lives in tables with a fixed schema defined up front. Each row is a record and each column has a strict type. A primary key identifies a row; a foreign key references a row in another table. Normalization splits data into separate tables so facts aren't repeated.
Relational databases provide ACID transactions:
- Atomicity: all of a transaction happens or none of it does.
- Consistency: constraints hold before and after every transaction.
- Isolation: concurrent transactions don't see each other's partial changes.
- Durability: once committed, data survives crashes.
Scaling a relational database#
A single relational server eventually runs out of room. These are the usual ways to grow past it, each with its own catch.
| Technique | Idea | Catch |
|---|---|---|
| Vertical scaling | Bigger CPU/RAM on one server | Hardware ceiling, cost, still a single point of failure |
| Read replicas | One leader for writes, followers for reads | Replication lag (Scaling Reads) |
| Sharding | Split rows across servers by a shard key | No cross-shard joins; rebalancing is hard (Sharding) |
| Indexing | B-tree lookups instead of full scans | Faster reads, slower writes (Indexing) |
When to choose SQL#
Reach for a relational database when the problem has one or more of these traits:
- Money or mission-critical state. Payments, banking, and inventory (don't oversell). Balances must be correct immediately, which needs atomicity and isolation.
- Highly relational data. "Reviews of courses taken by students in the same cohort as X" is one SQL query.
- A predictable schema. You know what a
UserorProductlooks like. - Complex filtering. Search by price, date, location and color at once.
- Integrity rules. A
Ticketcan't exist without itsEvent(foreign keys). - Multi-row transactions. One action must update several tables or none.
Choosing SQL doesn't mean it can't take heavy traffic. You usually add capacity in layers:
- Indexing and connection pooling.
- Read replicas.
- A cache like Redis for hot queries.
- Application-level sharding on a stable key like
user_id.
At high scale, expensive joins get replaced by denormalized columns or cached precomputed results.
Document databases#
Records are JSON-like documents (JSON or BSON). The database doesn't require a fixed schema, so two documents in the same collection can have different fields. Modeling shifts from normalizing (splitting into tables) to embedding (nesting related data in one document). Think of a scrapbook where everything about a person is glued onto one page, versus a filing cabinet with a drawer per kind of record.
The main modeling choice is whether related data goes inside the parent document or gets pointed to:
| Embedding | Referencing | |
|---|---|---|
| How | Put child data (e.g. lessons) inside the parent (course) | Store only lesson_ids in the parent |
| Pro | One read gets everything, with no joins | Documents stay small |
| Con | Documents get large and slow to update | Needs a second lookup |
When it fits: a document store pays off when records are naturally self-contained or vary in shape.
- Deeply nested data that would need many joins in SQL.
- Polymorphic data. In a product catalog, laptops have CPU speeds while shirts have sizes and fabrics.
- Rapidly changing models, where you'd rather not run
ALTER TABLEmigrations every week. - Heterogeneous profiles. Some users have long work histories and links, others almost nothing. One document per user avoids a wide table full of
NULLs.
Risks: data gets duplicated to keep reads fast (a username change may touch many documents), and many document stores only guarantee atomicity within a single document.
Why it's less common in interviews: the requirements are fixed for the 45 minutes, so the biggest advantage, schema flexibility, rarely comes into play. If the data is well defined and relational, the usual reasoning is to stay with PostgreSQL for joins and ACID.
Key-value stores#
A key-value store is a giant dictionary: you GET and SET a value by its unique key. Think of a wall of P.O. boxes.
You must know your box number (the key), and you can't ask "give me all mail from people named John". Lookups are extremely fast and scale horizontally, but there are no ad-hoc queries or joins. Here's how that compares with a relational database:
| Relational | Key-value | |
|---|---|---|
| Access | Complex queries (SELECT/JOIN) | Direct lookup by key |
| Storage | Disk | RAM (Redis) or SSD (DynamoDB) |
| Latency | Milliseconds | Sub-millisecond for in-memory stores |
| Best for | Business logic, money | Caching, sessions, rate limiting |
In practice you rarely choose key-value instead of SQL. A common hybrid: PostgreSQL is the source of truth and Redis is the speed layer, using cache-aside:
- Check Redis, and return on a hit.
- On a miss, read PostgreSQL.
- Store the result in Redis with a TTL, then return it.
See Caching.
When the key-value store is your only store for some data, there are no joins to fall back on. So you denormalize and store one entry per access path:
| Key | Value |
|---|---|
user:123 |
{"name": "Alex", "email": "alex@example.com"} |
email:alex@example.com |
{"id": 123} |
The risk is consistency: change the name and every copy must be updated. DynamoDB-style stores also suit flat, high-volume lookups by a single id, such as session management or feature flags.
Wide-column databases#
Rows live in partitions, and each row can have many, varying columns. These stores are built for massive write volume across many commodity servers. Picture a ledger per user: every new event is appended to the end of that user's ledger, so thousands of users can write at once without waiting on each other.
Two keys matter:
- Partition key decides which node stores the data (e.g.
sensor_id,chat_id). Everything for one key lives together. - Clustering key orders rows inside a partition (e.g.
timestamp), which makes range scans like "the last 24 hours" fast.
That layout is what sets wide-column stores apart from relational ones:
| Relational | Wide-column | |
|---|---|---|
| Write speed | Moderate (B-tree updates, locking) | Very high (LSM tree: memory first, then sequential flush) |
| Scaling | Vertical, or manual sharding | Add nodes, close to linear |
| Design approach | Model the entities | Model the queries |
| Joins | Native | None |
Pros: peer-to-peer clusters with no single point of failure (Cassandra), fast writes, and a natural fit for time series.
Cons: you must know your queries up front, and a new query often means a new, duplicated table. Background compaction can cause CPU and disk spikes.
Typical uses: millions of IoT readings per second (partition by sensor_id, cluster by timestamp) and chat history at very large scale (partition by chat_id, so a conversation is stored together).
Graph databases#
Data is nodes (users, products) and edges (follows, bought, friends-with). Graph databases are optimized for multi-hop traversals that would need repeated self-joins in SQL. Finding friends of friends means following edges rather than looking things up. Here's how that differs from tables and joins:
| Relational | Graph | |
|---|---|---|
| Model | Tables and foreign keys | Nodes, edges, properties |
| Queries | Joins | Traversals |
| Deep relationships | Slower with every hop | Stays fast across many hops |
| Scaling | Well understood (sharding) | Hard to partition |
That last row is the catch. Graph databases are hard to scale horizontally, and many large social networks don't use one as primary storage. Facebook, for example, built TAO, a graph-aware caching layer on top of MySQL. For "design a social network", the usual answer is a relational database plus a cache of adjacency lists.
Mention a graph database only when deep traversal is the core problem:
- Fraud detection, e.g. rings of accounts sharing phone numbers, devices and payment methods.
- Recommendations ("customers who bought this also bought...").
- Network impact analysis, e.g. how a failure at node A affects node Z in a power grid.
Impedance mismatch#
Whichever model you pick, your code still has to talk to it. Application code works with objects: an Order holds a customer, a list of line items and a shipping address. A relational database stores flat rows in separate tables. The gap between these two shapes is called the impedance mismatch.
To save one Order object, you split it across orders, order_items and addresses. To load it, you join those tables and rebuild the object. Object-relational mappers (ORMs), such as SQLAlchemy or Django's ORM, do this translation for you. The Order below is one object in code but two tables on disk:
from dataclasses import dataclass, field
@dataclass
class LineItem:
sku: str
quantity: int
@dataclass
class Order:
order_id: int
customer_id: int
items: list[LineItem] = field(default_factory=list)
# In SQL this one object spans two tables: orders and order_items.
# In a document store it can be saved as one JSON document.
ORMs remove a lot of boilerplate, but they have costs:
- Hidden queries. Loading a list of orders and then touching each order's items can fire one query per order (the "N+1 queries" problem).
- Leaky abstraction. For complex or slow queries, you still need to understand the SQL the ORM writes.
Document stores reduce the mismatch for data that is read and written as one unit, because the stored document has the same shape as the object. The mismatch comes back when you need to query across documents or join them. That's one reason the right model depends on your access patterns, not on fashion.
Polyglot persistence#
You don't have to pick a single model for a whole system. Large systems rarely use one database for everything. Polyglot persistence means using several storage technologies in one system, each for the data it handles best. The idea mirrors polyglot programming, where a team uses different languages for different parts of a system.
For example, an online shop might use:
| Data | Store | Why |
|---|---|---|
| Orders, payments, inventory | PostgreSQL | ACID transactions and constraints |
| Sessions, carts, rate limits | Redis | Fast key lookups with TTLs |
| Product search | Elasticsearch | Full-text search and ranking |
| Click and event logs | Cassandra | High write volume, time-ordered |
| Product images | Object storage (Amazon S3) | Cheap storage for large files |
| "Customers also bought" | A graph database | Multi-hop relationship queries |
Benefits: each workload gets a store built for it, and you can scale each store on its own.
Costs:
- More to run. Every store needs backups, monitoring, upgrades and people who understand it.
- Data in sync. The same product may live in PostgreSQL and in the search index. You need a reliable way to copy changes, such as change data capture or events through a queue.
- No transactions across stores. A write to PostgreSQL and a write to Elasticsearch cannot commit together. One can succeed while the other fails, so design for retries and repair.
Keep one store as the source of truth for each piece of data. The other stores hold derived copies that you can rebuild. Add a new store only when a real access pattern needs it; each one adds operational weight.
How to choose#
With all five models in view, here's a path that works for most designs. Start simple and add a store only when a need shows up.
- Start with PostgreSQL for core entities. It handles relationships and consistency.
- If reads are too slow, add Redis in front.
- If one table's write volume outgrows a single leader (logs, events, metrics), move that table to Cassandra or a similar store.
- If the schema is unpredictable or polymorphic, consider a document store.
- Avoid graph databases unless multi-hop traversal is the heart of the problem.
Key takeaways#
- Relational is the default: joins, constraints and ACID transactions for core data.
- Document stores trade joins and cross-document transactions for flexible, nested records.
- Key-value stores are for fast lookups by key, usually as a cache in front of a source of truth.
- Wide-column stores handle huge write volumes when you design tables around known queries.
- Graph databases solve deep traversal problems but are hard to scale. Use them sparingly.
- The impedance mismatch is the gap between objects in code and rows in tables. ORMs bridge it; document stores shrink it for aggregate-shaped data.
- Polyglot persistence uses a different store per workload. Keep one source of truth and plan how derived copies stay in sync.