Course contents

04. Database Fundamentals Lesson 2 of 10

NoSQL Databases

Key-value, document, wide-column and graph stores; why key lookups scale out, why queries off the partition key scatter, and how hot keys break partitioning.

16 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • NoSQL covers key-value, document, wide-column and graph models, each built around particular access patterns.
  • Partitioned stores route each request by its key, so key lookups cost one partition and scale with more partitions.
  • Queries without the partition key ask every partition; that cost grows as you add partitions.
  • Design keys from your queries; duplicate data (extra tables, global indexes) for queries that need another key.
  • A single hot key overloads one partition; split it or cache it.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

"NoSQL" is an umbrella for databases that do not use the relational table-and-join model as their primary interface. Four families cover most of them:

  • Key-value: a key maps to a value the database mostly treats as opaque. Operations are get, put, delete, sometimes atomic counters or TTLs. Examples: Redis, Amazon DynamoDB (also document-capable), etcd, Riak.
  • Document: the value is a JSON-like document; fields can be queried and indexed, and related data is often embedded in one document. Examples: MongoDB, Couchbase, Google Firestore.
  • Wide-column (column-family): rows are grouped under a partition key and kept sorted by a clustering key inside it, so "all events of device 7 in the last hour" is one sequential read. Examples: Apache Cassandra, ScyllaDB, Google Bigtable, Apache HBase.
  • Graph: nodes and edges with properties; queries traverse relationships (Cypher, Gremlin). Examples: Neo4j, Amazon Neptune.

Key-value, document and wide-column stores are usually partitioned by key across many machines and replicated; that is what most of this lesson is about.

Why it exists

In the 2000s, web-scale companies hit limits of single-primary relational databases: write volume and data size beyond one machine, and availability requirements across data centres. Amazon's Dynamo paper (2007) and Google's Bigtable paper (2006) described stores that give up general joins and cross-entity transactions in exchange for horizontal scale, predictable latency per key, and high availability. Document databases separately made it easy to store nested, evolving data the way applications already hold it.

How it works

Partitioning. Each item has a partition key. The store hashes it (or uses key ranges) to pick the partition, and each partition lives on a node with replicas. A request that carries the key is routed straight to that partition: its cost does not depend on how many partitions exist, so adding nodes adds capacity. Consistent hashing or a partition map keeps reassignments small when nodes join or leave.

Sort keys. Within a partition, items can be sorted by a second key (DynamoDB sort key, Cassandra clustering columns). "Orders of customer 42, newest first" is then one partition, one contiguous range.

Queries off the key. A query that does not name the partition key cannot be routed. Either the store rejects it, or a coordinator sends it to every partition and merges the results (scatter-gather). Its cost grows with the number of partitions, and its latency follows the slowest partition. Secondary indexes help, but come in two kinds: local indexes live with each partition (queries still scatter unless they include the partition key), global indexes are partitioned by the indexed attribute (single-partition reads, but updated asynchronously on every write — DynamoDB global secondary indexes are eventually consistent).

Modelling from access patterns. Instead of normalising entities and joining at read time, you list the queries first and shape keys so each one hits one partition. Data needed by several queries is duplicated (another table keyed differently, a global index, or a document that embeds what one screen shows). Writes do more work; reads stay cheap and predictable.

Consistency. Replication is often leaderless or multi-leader with tunable consistency (Cassandra's per-query consistency level, DynamoDB's eventually or strongly consistent reads). Many stores now offer transactions, usually limited in scope or cost (DynamoDB transactions up to 100 items, MongoDB multi-document transactions since 4.0).

When to use it

  • Access patterns are known and mostly by key: sessions, carts, user profiles, feature flags, device and IoT data, chat messages, activity feeds, leaderboards.
  • Write volume or data size exceeds one relational primary, and the data partitions naturally (per user, per device, per tenant).
  • Data is naturally an aggregate read and written together (a product with its variants, a form submission): document stores.
  • Questions are about relationships many hops deep: graph stores.
  • You need multi-region active-active writes with tunable consistency.

When not to

  • Queries are varied, ad hoc or not yet known; reporting across entities.
  • Correctness depends on transactions across many entities and invariants (ledgers, inventory with constraints).
  • The data fits comfortably on one relational node: you would give up joins and constraints for scale you do not need.
  • The only reason is "flexible schema": the schema still exists, in your code.

Trade-offs

Choice You gain You pay
Partition by key Horizontal scale, predictable per-key latency Queries without the key scatter or need extra tables
Duplicating data per access pattern One-partition reads Write amplification, keeping copies in sync
Global secondary index Queries by another attribute without scatter Extra write cost, eventually consistent reads
Embedding in documents One read per screen Large documents, duplicated sub-data
Tunable / eventual consistency Availability and low latency across replicas Stale reads, conflict handling

Alternatives

  • Relational database with indexes, read replicas and caching: covers far more scale than most products need.
  • Distributed SQL (CockroachDB, YugabyteDB, Spanner): horizontal scale with SQL and transactions, at higher write latency.
  • Sharded relational (application-level or Vitess, Citus): keeps SQL inside a shard; cross-shard queries scatter just like here.
  • Search engines (Elasticsearch, OpenSearch) for full-text and flexible filtering, fed from the primary store.

Failure modes

  • Scatter-gather creep: one convenient query without the partition key ends up on a hot path and loads every partition.
  • Hot keys and hot partitions: a celebrity user, a big tenant, or a date-based key that sends all of today's writes to one partition. Partitioning spreads keys, not load.
  • Unbounded partitions: one partition key collecting rows forever (all events of a busy device) grows past what one node handles well; bucket by time.
  • Stale reads from eventually consistent replicas or global indexes, surprising code that wrote a moment ago.
  • Write amplification: every duplicate and index multiplies write cost and capacity bills.
  • Schema drift: documents of many shapes that every reader must handle.

In production

Write down the access patterns before choosing keys, with expected rates. Pick high-cardinality partition keys with evenly spread traffic; add a time bucket for unbounded series. Monitor per-partition metrics (throttling, hot-key reports such as DynamoDB CloudWatch Contributor Insights or Cassandra's nodetool toppartitions), not only totals. Treat scatter-gather queries as a design smell on hot paths. Decide per query which consistency you need. Keep a relational or analytical copy (via change data capture) for reporting instead of forcing ad-hoc queries onto the operational store.

Common misconceptions

  • "NoSQL means no schema." It means the database does not enforce one; your code does.
  • "NoSQL is always faster." It is fast for the access patterns it was modelled for, and slow or impossible for others.
  • "NoSQL can't do transactions." Many can, within limits; check scope and cost.
  • "More partitions fix any load problem." Not scatter-gather queries, and not a single hot key.
  • "NoSQL is one thing." A graph database and a key-value store have almost nothing in common.

Interview angle

Justify the choice from the access patterns and scale, not fashion: "Messages are written 50k/s and read per conversation, newest first, so a wide-column store with partition key = conversation id and clustering by time fits." Then show you know the costs: how you serve a second access pattern (another table or a global index), what happens with a very active conversation (hot partition — bucket it), which reads may be stale, and where you would keep data that needs transactions or ad-hoc queries.

Model assumptions

The partitioned store is simulated: each partition is a database node with 8 connections, a 32 ms mean read and a 48 ms mean write (lognormal, cv 0.4); a query waiting more than 400 ms for a connection fails. The router uses a consistent-hash ring (64 virtual nodes per partition) over the request key; request keys follow a Zipf distribution over 100,000 customers (exponent 0.6, or 1.3 for the hot-key step). Adding partitions does not model data movement. Scatter-gather goes through a coordinator that asks all partitions at the same time and answers when the slowest has answered, so its latency follows the slowest partition rather than the sum; every partition does one read per scatter query. The challenge doubles the customer page to 150 queries per second. Splitting the hot keys is modelled as a flatter key distribution. The four families in the first step are a scripted illustration. Numbers are illustrative, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. Four families of NoSQL

    "NoSQL" is not one design. Four families cover most systems:

    Key-value: a key maps to an opaque value; you GET and PUT by key (Redis, DynamoDB, etcd). Document: the value is a JSON-like document whose fields can be queried and indexed (MongoDB, Firestore, Couchbase). Wide-column: rows grouped under a partition key and sorted by a clustering key inside it (Cassandra, ScyllaDB, Bigtable, HBase). Graph: nodes and edges, built for multi-hop traversals (Neo4j, Neptune).

    The first three share one idea that the rest of this lesson simulates: data is partitioned by key across machines, and the key decides which machine serves a request. The family nodes on the right are an illustration.

    Scene: Illustration: four NoSQL families — key-value, document, wide-column and graph — each answering a typical request. Behind the app, a partition router spreads simulated key lookups over three partitions.

    Key idea: NoSQL stores trade general-purpose querying for a data model and partitioning scheme built around specific access patterns.

  2. 2. A lookup by key touches one partition

    Every request carries a partition key (here a customer id). The router hashes it and sends the request to the one partition that owns that key. No other partition is involved.

    150 lookups per second split roughly evenly: each partition sees about 50 per second, a fifth of what it can do, and latency is little more than one read.

    Scene: The app sends 150 key lookups per second to the partition router, which sends each to exactly one of three partitions. Each partition gets about a third and is lightly loaded.

    Key idea: If every request names its partition key, each request costs one partition’s work, however many partitions there are.

  3. 3. More traffic? Add partitions

    Traffic grows to 750 lookups per second. Three partitions can do about 750 together, with no headroom, so we add Partition 4 and 5. The hash ring hands each new partition a share of the keys (in a real store that data is copied over first).

    Each partition now serves about 150 per second on average, 60% of its capacity (a hash ring is never perfectly even, so some partitions carry a little more). Throughput grew by adding machines, not by buying a bigger one. This is what key-value, document and wide-column stores are designed for.

    Scene: Traffic rises to 750 lookups per second and two partitions are added. Five partitions each serve about a fifth of the traffic at roughly 60% utilisation; nothing fails.

    Key idea: Key-partitioned stores scale reads and writes horizontally: double the partitions, roughly double the capacity.

  4. 4. A query not by key asks everyone

    The table is partitioned by order id, but a new page shows "all orders of customer 42". The partition key does not say where those orders are, so a coordinator has to ask every partition and merge the answers: scatter-gather. It asks all five at the same time, so a scatter query is as slow as the slowest of the five partitions at that moment.

    75 such queries per second become 75 extra reads on each of the five partitions, 375 reads in total. The partitions climb to near saturation, so one of the five is nearly always busy and the scatter queries are much slower than lookups, and the key lookups that share the partitions start to wait and fail too. Adding partitions would not help: each new one also receives every scatter query.

    Scene: A customer page sends 75 queries per second to a coordinator, which asks all five partitions for each one. Every partition gets 75 extra reads per second, they approach saturation, and both the scatter queries and some key lookups slow down or fail.

    Key idea: A query that does not include the partition key costs work on every partition and gets worse, not better, as you add partitions.

  5. 5. Partition by the access pattern

    NoSQL modelling starts from the queries, not the entities. The main queries are "orders of a customer" and "one order", so we partition by customer id and sort each customer’s orders by date inside the partition (in DynamoDB terms: partition key CUSTOMER#42, sort key ORDER#2026-11-24#81233; in Cassandra a clustering column).

    Now "all orders of customer 42" is one read on one partition, routed like any lookup. The coordinator is gone, the partitions are back below saturation (about 70% busy on average), and the errors stop. The price: any query that is not by customer needs its own table or index, maintained on every write.

    Scene: The table is partitioned by customer, so the customer page sends each query through the router to a single partition. The coordinator is gone, partitions are back below saturation and nothing fails.

    Key idea: Choose the partition key so each frequent query hits one partition; duplicate data for the queries that need a different key.

  6. 6. One key gets a quarter of the traffic

    A large marketplace seller signs up and its integration polls its own orders constantly. One customer id now receives about a quarter of all requests.

    A key lives on exactly one partition, so that partition gets its normal share plus the hot key. It saturates and its requests time out, while the other partitions are only half busy. Adding partitions does not help either: the hot key still lives on one of them.

    Scene: One customer key now gets about a quarter of all lookups and another about a tenth. The partitions that own them are saturated and their requests fail, while the other partitions are half busy or less.

    Key idea: Partitioning spreads keys, not load: a single hot key overloads its partition no matter how many you have.

  7. 7. Split the hot key

    For the hot keys we add a suffix to the key (CUSTOMER#1#0 … CUSTOMER#1#9) so its rows and requests spread over ten keys and therefore several partitions; reads for such a key fetch the ten sub-keys and merge. A cache in front of the hottest keys is the other common fix.

    Load evens out across the partitions and the errors stop. The cost is complexity for those keys: writes pick a suffix, reads gather ten.

    Scene: The hot key is split into ten sub-keys. Load is spread evenly over the five partitions and nothing fails.

    Key idea: Hot keys need key-level fixes: split them (write sharding) or cache them.

  8. 8. When NoSQL fits

    Pick a key-partitioned NoSQL store when you know your access patterns, they are mostly by key, and you need scale or availability beyond one machine: sessions, carts, user profiles, device data, messaging, feeds. Pick a document store when data is naturally a nested aggregate read and written as a whole; a graph store when the questions are traversals.

    Stay relational when queries are varied or unknown, when you need joins and multi-row transactions across entities, or when one machine is enough. Many systems use both: relational for the core records, NoSQL for one high-volume access pattern.

    Scene: Five partitions behind a partition router serve key lookups from the app and the customer page, evenly loaded.

    Key idea: NoSQL rewards knowing your queries up front; relational rewards not knowing them.