Databases and storage

Key-value, document and wide-column stores

The data model, strengths, limits and partitioning of the three main NoSQL families, and how to design tables from access patterns.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

Amazon’s retail site ran on relational databases in the early 2000s and struggled to scale them through peak shopping periods. When engineers looked at how services actually used those databases, most access turned out to be simple. Werner Vogels, Amazon’s CTO, wrote in 2012 that about 70% of operations were of the key-value kind, using only a primary key to return a single row. Those services were paying for joins, a query planner and a single-primary architecture, and using almost none of it.

Consider the shopping cart. It is read and written by one key, the customer id. It must accept a write even when a server or a data centre is down, because a cart that rejects items loses sales. A relational primary gave that service features it did not need and an availability limit it could not accept.

The response, described in the Dynamo paper in 2007, was to build stores around a simpler contract. Give up joins and arbitrary queries. In return, spread data across many machines by key, and keep answering when some of them fail. Different teams drew that contract in different places, which gave three families. SQL vs NoSQL covers when to leave relational at all. This lesson covers which family to pick.

Key-value stores

Data model. A key maps to a value, and the store does not look inside the value. The operations are get, put and delete.

Example systems. Redis keeps data in memory and adds data structures such as lists, sets and sorted sets (see Redis vs Memcached). DynamoDB is a durable, managed store that started from this model. Memcached is a pure cache.

Good at. Lookups by exact key at very high throughput and with predictable latency: sessions, carts, feature flags, rate-limit counters, cached objects.

Bad at. Everything else. You cannot ask “which sessions belong to users in Lagos?” without reading every key.

Partitioning. Hash the key and map the hash to a node, with consistent hashing or a slot table. Since every operation names one key, routing is trivial and capacity grows by adding nodes.

Choose it when every access is by a key the caller already holds. Do not choose it when you need to search by value, scan ranges or update several keys atomically.

Document stores

Data model. A record is a JSON-like document with nested objects and arrays. Documents in a collection need not share a shape. The store understands the structure, so it can index and query fields inside it.

Example systems. MongoDB, Couchbase and Firestore.

Good at. Aggregates that are read and written as a whole: a product with its variants and attributes, a user profile with settings, an article with its metadata. One read fetches everything with no joins, and fields can differ between records.

Bad at. Many-to-many relationships and anything that needs joins across collections. The main design decision is embed or reference. Embed data that the parent owns, that is bounded, and that is read with it. Reference data that is shared or grows without limit. An ever-growing embedded array is the classic mistake: MongoDB caps a document at 16 MB, and each update gets costly long before that.

Partitioning. MongoDB shards a collection by a shard key that you choose, hashed or by range. A query that includes the shard key goes to one shard. A query that does not is sent to all of them.

Choose it when your entities are self-contained and vary in shape. Do not choose it when the data is highly connected or when rules span many documents. Multi-document transactions exist in MongoDB, and they cost more than single-document writes.

Wide-column stores

Data model. This family follows Google’s Bigtable. In Cassandra’s version, a table has a partition key and optional clustering columns. All rows with the same partition key form one partition, stored together on the same nodes. Inside the partition, rows are kept sorted by the clustering columns. Think of a partition as a sorted list that belongs to one key.

Example systems. Cassandra and ScyllaDB hash the partition key. HBase and Bigtable keep all rows sorted by row key and split that range into pieces.

Good at. Very high write rates, because the engines are LSM trees, and reads of the form “the latest N rows for key X”: messages in a conversation, events for a device, a user’s activity history.

Bad at. Queries that do not start from a partition key, joins, aggregations across partitions, and read-modify-write transactions. Cassandra’s lightweight transactions exist, and they need several round trips between replicas.

Partitioning. By the partition key. A range-partitioned store such as HBase gives cheap scans across keys, and suffers hot spots when keys arrive in increasing order, such as timestamps.

Choose it when writes are heavy, the queries are few and known, and each reads one partition. Do not choose it for ad hoc queries, or as a queue, since heavy deletes hurt LSM engines.

Modelling by access pattern

In a relational design you model the entities and trust the planner with the queries. Here you do the reverse.

  1. List the queries, with their frequency. For chat: fetch the latest 50 messages in a channel, page backwards through older ones, post a message.
  2. Choose the partition key so that each query names exactly one partition. Here that is the channel id.
  3. Choose the sort key (clustering column) to match the order and ranges the query needs. Here it is a time-ordered message id, newest first.
  4. Check partition size and heat. A busy channel grows for ever, so add a time bucket to the partition key. Discord’s engineers described this design for their Cassandra message store: the partition key is the channel id plus a bucket of about ten days.
  5. Add a table or index for each further query. Messages by author need their own table keyed by user id.
Reading by partition key compared with asking every node5 components: Chat service, Coordinator, Node A, Node B, Node C. Connections: Chat service to Coordinator; Coordinator to Node A; Coordinator to Node B; Coordinator to Node C.Chat serviceCoordinatorhashes the partition keyNode ANode Bholds channel 42Node C

Step 1 of 8

A messages table uses the channel id as its partition key and the message time as its clustering key. The partition key decides which node stores a row. The clustering key decides the order of rows inside a partition.

Read the steps as text
  1. A messages table uses the channel id as its partition key and the message time as its clustering key. The partition key decides which node stores a row. The clustering key decides the order of rows inside a partition.
  2. A new message is written to channel 42. The coordinator hashes 42, which maps to node B, and node B adds the row to that channel's partition in time order. Every message in channel 42 lives together on the same node.
  3. Now the query the table was designed for, the latest 50 messages in channel 42. The coordinator hashes 42 again and asks only node B. The rows are already stored together and sorted, so the node reads one contiguous slice.
  4. A time range inside one channel works the same way. Messages in channel 42 from the last hour are a slice of one partition, selected by the clustering key. The cost depends on the rows returned, not on the size of the table.
  5. Now a query the table was not designed for, every message written by user 7. The user id is not the partition key, so the coordinator cannot tell which nodes hold matches. It has to ask every node, and every node has to scan.
  6. That scatter-gather query is as slow as the slowest node and gets worse as the cluster grows. The fix is a second table keyed by user id, written alongside the first. In these stores you keep one table per query, which is denormalization by design.
  7. One more trap. A very busy channel is still a single partition on a single node and its replicas, however large the cluster. Adding a time bucket to the partition key, such as channel id plus day, keeps each partition bounded.
  8. Choose the partition key from the question you ask most often, then check how large and how busy one partition can get. Every other modelling decision in a key-value or wide-column store follows from that.
Reading by partition key compared with asking every node

A good partition key has many distinct values, spreads traffic evenly, keeps each partition bounded, and is known to every hot query. A poor one has few values (a status or a country) or follows time (today’s date), so all current writes land in one place. DynamoDB uses the same ideas under the names partition key and sort key, with global secondary indexes for additional queries. Those indexes are updated asynchronously, so reads from them are eventually consistent. See sharding for the general problem.

Comparison

Key-value Document Wide-column
Unit of data Opaque value Nested document Sorted rows in a partition
Best query Get by key Get or filter one aggregate Slice of one partition
Secondary queries None Indexes on fields A new table per query
Typical systems Redis, DynamoDB MongoDB, Firestore Cassandra, HBase, Bigtable

In the interview

Use this when you have decided that a table needs a NoSQL store, and say which family and why. Then show the keys. Interviewers pay most attention to that step.

A strong answer takes about a minute: “Messages are write-heavy and always read by channel in time order, so a wide-column store fits. Partition key is channel id plus a ten-day bucket, clustering key is the message id descending. The latest 50 messages is one partition read. I bucket by time so a busy channel cannot grow one partition without limit. Search by author is a second table. User profiles are different, small self-contained records read by id, so they go in a document or key-value store.”

Key takeaways

  • A key-value store does one thing, read and write by exact key, and does it at very high throughput with predictable latency.
  • A document store keeps a whole aggregate in one nested record and can index its fields. It is weak at many-to-many relationships.
  • A wide-column store groups rows into partitions and sorts them inside each partition. It suits huge write volumes and time-ordered reads per key.
  • Model by access pattern: list the queries, then choose a partition key and sort key so each query reads one partition.
  • A good partition key has many distinct values, spreads load evenly and keeps each partition bounded in size.
  • Wide-column does not mean column-oriented. Cassandra serves lookups by key. ClickHouse and Parquet serve analytical scans.

Check yourself

1. A Cassandra table has PRIMARY KEY ((user_id), created_at). Which query does it serve efficiently?
2. An orders table in DynamoDB uses status as its partition key, with the values pending, shipped and delivered. What is the main problem?
3. A blog stores each post as a document with its comments embedded in an array. When does this model fail?
4. What is the difference between a wide-column store such as Cassandra and a column-oriented database such as ClickHouse?
5. A chat system stores messages in Cassandra partitioned by channel. A new feature needs all messages sent by one user. What is the idiomatic approach?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What is a key-value store good and bad at?

Good at get, put and delete by exact key with very high throughput and low latency. Bad at anything else, such as queries by value, joins and aggregation.

When should a document embed data, and when should it reference it?

Embed data that is owned by the parent, bounded in size and read with it. Reference data that is shared, unbounded or updated on its own.

In Cassandra, what do the partition key and clustering key do?

The partition key is hashed to choose the node, and all rows that share it are stored together. The clustering key sorts rows inside the partition, so range reads are a contiguous slice.

What makes a good partition key?

Many distinct values, load spread evenly across them, each partition bounded in size, and a value that your main queries always know.

What is a hot partition and how do you fix it?

One partition key that takes a disproportionate share of traffic or data. Add a component to the key such as a time bucket or a shard suffix, or cache the hot item.

What does modelling by access pattern mean?

Start from the list of queries, not from the entities. Design one table or index per query so each read touches a single partition, and accept duplicated data.

Review the deck