"Which database would you use, and why?" is asked in almost every design round. A weak answer names a product. A strong answer starts with the data and the queries, picks a database family, and says what it costs. This lesson covers the NoSQL families, how modeling changes, and a simple way to choose.
1. What NoSQL Means
NoSQL is a loose name for databases that are not relational tables with joins. It does not mean "no SQL" (some support SQL-like queries) and it does not mean "faster". Each family drops some relational features to be better at one job:
- Scale out. Data is split across machines from the start, so writes and storage grow by adding nodes.
- Flexible shape. Items in one collection can have different fields, so the schema can change without a migration.
- A fast, narrow access path. The data is laid out for the queries you plan, so those queries are cheap and predictable.
These gains come with costs. Joins are limited or missing. Queries you did not plan are slow or impossible. Transactions across items are limited, and many systems default to eventual consistency (the consistency lessons cover this). So the question is never "SQL or NoSQL". It is "what does this data and these queries need?"
2. The Main Families
| Family | Model | Good at | Weak at | Examples |
|---|---|---|---|---|
| Key-value | Key to value, opaque to the database | Lookups by key at very low latency and very high rate | Any query except by key | Redis, DynamoDB, Memcached |
| Document | JSON-like documents with nested fields | Objects read and written as a whole, changing shapes, secondary indexes | Many-to-many relationships, multi-document transactions at scale | MongoDB, Couchbase, DynamoDB |
| Wide-column | Partition key, then rows sorted by a clustering key | Huge write rates, time-ordered data, simple known queries | Ad hoc queries, joins, updates in place | Cassandra, ScyllaDB, HBase |
| Graph | Nodes and edges | Queries that follow many links: friends of friends, fraud rings | Bulk scans, scaling across many machines | Neo4j, Amazon Neptune |
Three more kinds are specialist stores, and each has its own lesson: search engines (Elasticsearch, for text queries), time-series databases (for metrics with timestamps) and vector databases (for similarity search in AI systems). Be ready to name them, but do not use them as your main store.
There is also NewSQL (Google Spanner, CockroachDB). It keeps SQL and transactions but spreads data across machines. The cost is higher write latency, because nodes must agree on every commit.
2.1 How Each Family Is Used
- Key-value: sessions, shopping carts, feature flags, counters. Redis keeps everything in memory (about 24 GB usable on the r5.xlarge from earlier lessons). DynamoDB keeps data on disk across partitions and limits an item to 400 KB.
- Document: product catalogs, user profiles, content. A document is one object with nested parts, so it is read with a single lookup. MongoDB limits a document to 16 MB.
- Wide-column: messages, events, sensor data, activity feeds. Cassandra writes are very fast because they append to a log and are merged later (the LSM trees lesson explains how).
- Graph: social connections, recommendations, access paths, fraud detection. A relational database can answer "friends of friends of friends" only with a chain of joins that gets slower at each hop.
3. Modeling Changes: Query First
In a relational database you design the tables around the data, and then write any query on top. In NoSQL you design around the queries. List the exact questions the application asks, then shape the data so each one is answered by one lookup.
3.1 Embed or Reference
In a document store, put data that is read together in one document. A restaurant menu is always shown as a whole, so embed it:
{
"restaurantId": "r_42",
"name": "Spice Route",
"hours": { "open": "11:00", "close": "23:00" },
"menu": [
{ "item": "Paneer Tikka", "priceCents": 24000 },
{ "item": "Dal Makhani", "priceCents": 22000 }
]
}
One read gets everything, with no join. Embedding fits when the nested data is owned by the parent, is bounded in size, and is read with it. Use a reference (store an ID and fetch the other document) when the child is shared, grows without limit, or changes on its own. A restaurant's reviews can grow forever, so they get their own collection.
3.2 Partition Key and Sort Key
DynamoDB and Cassandra split data by a partition key. All rows with the same key live together on one node, sorted by a sort key (clustering key in Cassandra). A query is fast only if it names the partition key. For "show a customer's latest 10 orders":
Partition key: customer_id
Sort key: order_time (descending)
Query: customer_id = 'c_7', limit 10 -> one partition, one range read
This choice decides everything. Two rules:
- Spread the load. A key with few values, or one value that is very popular, makes a hot partition. DynamoDB allows about 1,000 writes and 3,000 reads per second for one partition, so one hot key is throttled long before the table's total limit. Use a high-cardinality key such as the customer ID, not the date or the country.
- Keep each partition bounded. A partition that grows forever (all events for one device, with no time bucket) becomes huge. Add a bucket, such as the month, to the key.
3.3 Secondary Indexes, Consistency and Transactions
Querying by anything other than the key needs a secondary index. A local index covers one partition and is cheap. A global index covers the whole table, but it lives on other nodes and is updated after the write, so it can be briefly behind. Other limits to know:
- Consistency: DynamoDB reads are eventually consistent by default, and a strongly consistent read costs twice as much. Cassandra lets you choose how many replicas must answer each request. If reads plus writes exceed the replica count (R + W > N), a read sees the latest write (see the replication lesson).
- Transactions: DynamoDB and MongoDB support multi-item transactions, but they are slower and limited in size. Design so that most operations touch one item or one partition.
3.4 Duplicate Data on Purpose
A second query needs a second layout. "Orders by restaurant" needs the restaurant as the partition key. NoSQL designs often store the same order twice, or build a secondary index, one copy per access path. This is denormalization taken to its limit. Writes become more work, and the copies must be kept in step. Reads stay a single lookup. The number of access paths you can afford is part of the choice.
4. How to Choose
Ask these questions in order:
flowchart TD
A["Need transactions and joins across entities?"] -- Yes --> B["Relational"]
A -- No --> C["Fits on one node with room to grow, or ad hoc queries needed?"]
C -- Yes --> B
C -- No --> D["What is the access pattern?"]
D --> E["By key, tiny values: key-value"]
D --> F["Whole objects, varied shape: document"]
D --> G["Huge writes, time-ordered: wide-column"]
D --> H["Many hops between items: graph"]
Then check the numbers. Write them down as the requirement, as in the estimation lesson:
| If the requirement is | Lean toward | Because |
|---|---|---|
| Exact data | Relational | Money, inventory and anything that must be exact need constraints and multi-row transactions |
| Unknown queries | Relational | Queries are unknown or keep changing, and SQL answers questions you did not plan for |
| Over 10,000 writes/s | Wide-column, DynamoDB, or a sharded relational database | More than about 10,000 writes per second on one dataset is beyond what one primary handles (5,000 to 20,000) |
| Under 1 ms lookups | In-memory key-value | Simple lookups under 1 ms: memory is about 5,000 times faster than a network call to a disk-based store |
| Flexible objects | Document | Whole objects with flexible fields: one read, no join, no migration for new fields |
| Petabytes of events | Wide-column or object storage | Append-only events: cheap sequential writes, low cost per GB |
| Relationships | Graph | Each hop is an index lookup, not a join |
Two checks that save you from bad picks: first, many problems that look like they need NoSQL do not. PostgreSQL with replicas and a cache handles a very large read load, and it stores JSON in a JSONB column. Second, a NoSQL database needs the query list up front. If the product is still finding its feature set, the flexible queries of a relational database are worth more than scale you do not need yet.
4.1 Worked Example: Order Tracking Events
The delivery app records an event for every order step and courier ping: 1.1 billion events a day, 200 bytes each, kept for 30 days. Peak is about 4 times the average. Assume one Cassandra node sustains 10,000 writes per second and holds 2 TB of data comfortably (assumptions, to be replaced by a load test).
- Write rate: 1.1 billion ÷ 86,400 = 12,500 events per second on average, so about 50,000 at peak. That is above one relational primary (5,000 to 20,000). Sharding is possible, but the data is append-only and read by order ID, which suits wide-column.
- Storage: 1.1 billion × 200 B = 216 GB a day. For 30 days that is 6.5 TB, and with 3 replicas about 19 TB.
- Nodes: for storage, 19 ÷ 2 = 10 nodes. For writes at peak, 50,000 × 3 copies ÷ 10,000 = 15 nodes, and at 70% utilization about 21. Writes decide, so plan about 21 nodes.
- Partition key:
order_idwith the event time as the sort key. One order has a few dozen events, so each partition stays small.
5. Using More Than One Database
Real systems combine stores, each doing the job it is best at. This is called polyglot persistence. Take a food delivery app:
- Customers, orders, payments: PostgreSQL. The data is relational and must be exact.
- Restaurant menus: a document store. Menus are read whole, and each restaurant has a different shape.
- Live courier locations: Redis. 100 MB of latest positions and 200,000 updates per second (the sharding example in the Numbers lesson).
- Search for dishes and restaurants: Elasticsearch, fed from the main database.
- Order and tracking events: a wide-column store or Kafka and object storage, for history and analytics.
The cost of this is the main thing to say. Every store is one more system to run, back up, secure and keep in step. Data copied to the search index and the cache can disagree with the source. A common pattern is to pick one source of truth (here, PostgreSQL), and feed the others from it with events. Do not add a store unless a number or a query needs it.
6. Common Pitfalls
- Choosing by fashion. "We use Mongo because it scales" without a number.
- Saying NoSQL is faster. It is faster for the access path it was built for, and slower or impossible for others.
- Modeling like relational tables. A NoSQL design that needs many lookups per request has lost the benefit.
- A hot or unbounded partition key. Pick a high-cardinality key and bucket growing data.
- Forgetting the second query. The design works for the first access path and fails for the next one.
- No source of truth. Three stores hold the same data and nobody knows which one is right.
- Too many databases. Each one adds cost and failure modes.
7. Interview Questions This Lesson Prepares You For
- When would you choose NoSQL over a relational database? When one access pattern dominates and the numbers need it: writes beyond one primary, very low latency by key, flexible object shapes, or huge append-only data. Otherwise a relational database is the safer default.
- Walk me through how you would choose a database for this system. List the queries, the read and write rates, the consistency needs and the data size. Then match each to a family and name the cost.
- What is a hot partition and how do you avoid it? One key that gets far more traffic than others, so one node is overloaded. Use a high-cardinality partition key, add a random or bucket suffix for popular keys, and cache hot reads.
- Embed or reference in a document database? Embed data that is owned by the parent, bounded and read together. Reference data that is shared, unbounded or updated on its own.
- You need 50,000 writes per second of small, append-only events. What do you pick and how many nodes? A wide-column store keyed by the entity ID. Compute nodes for both write rate and storage (with replicas), take the larger, and say the per-node numbers are assumptions to load test.
- Why not use one database for everything? No single store is best at transactions, search, caching and event history. But every extra store adds operations work and sync problems, so add one only when a requirement needs it.