Data modelling for NoSQL
In DynamoDB and Cassandra you design keys around the questions your app asks. List them first, then shape the data so each one is a single cheap read.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
Discord's 2017 post tells how it moved chat messages from MongoDB to Cassandra. Every query read one channel, so channel_id became the partition key. Messages inside it were sorted by message_id, a time-ordered ID. 1
The first import showed a problem at once. Cassandra logged warnings about partitions over 100 MB. Under one key, a busy channel's messages would grow without end. Discord wrote that big partitions add heavy garbage collection pressure, and cannot be spread across the cluster. 1
So they changed the key. They added a time bucket to the partition key: ((channel_id, bucket), message_id). They looked at the largest channels and chose about 10 days per bucket. They expected that to keep partitions comfortably under 100 MB. 1
The model still had a sharp edge. In one public server, someone deleted millions of messages with the API. One message was left in the channel. To return it, Cassandra scanned millions of delete markers, called tombstones. 1 The garbage collector ran 10-second stop-the-world pauses again and again. 1
The fix was in table settings and the read path. Discord cut the tombstone lifetime from 10 days to 2. That was safe only because they ran repairs every night. The query code now remembers empty buckets and skips them. 1
Nothing here was a bug in Cassandra. The key decided how big each partition could grow, and how much work one read could cause.
The idea in simple words
In a relational database, you normalise first and write queries later. The data models lesson covers that. DynamoDB and Cassandra flip the order.
AWS says it plainly: you should not design a DynamoDB schema "until you know the questions it will need to answer". 2 Cassandra's docs say the same: "data modeling is query-driven". 9
The reason is the trade. These stores answer a few kinds of query very fast at any size. Other queries can be "expensive and slow". 2 You choose which queries are fast when you choose the keys.
The key idea. Write the list of access patterns before you draw a table. Then pick a partition key and sort key so each pattern is one request to one partition. Copy data where a pattern needs it.
How it works
Two keys
The primary key has two parts.
- The partition key is hashed to decide which partition, and so which node, stores the item. 9 1 The sharding lesson explains how the hash ring works.
- The sort key orders items inside one partition. Cassandra calls it the clustering key. 9
In DynamoDB, all items with the same partition key form an item collection. They are stored together. 3 One Query reads them in sort-key order.
A sort key can also hold a path. AWS shows [country]#[region]#[state]#[county]#[city]#[neighborhood]. With begins_with you can read any level of that tree in one range query. 5
Step through one small table. Use Next and Back, or the ← and → keys.
- Member m1 has three items under one partition key. Together they are an item collection. The sort key keeps them in order: CLUB# items, then PROFILE.
- Access pattern: "show this member's clubs". One Query with the partition key and a sort key prefix returns both clubs. The club name was copied in, so no second read is needed.
- Add a second member. Now ask the reverse question: "who is in club c1?". CLUB#c1 sits in the sort key of many partitions. The table cannot find them without reading everything.
- A global secondary index (GSI) with the keys swapped fixes this. Only membership items carry its keys, so profiles stay out. All of c1's members land in one index partition.
- The cost: DynamoDB updates the index asynchronously, usually within a fraction of a second. A query on it can miss a member who joined a moment ago.
Denormalise per query
Neither store has joins. Cassandra's docs say all fields a query needs must sit in one table. Each query gets its own table, so the same data is copied into several tables. 9 That copying is denormalisation.
In DynamoDB you copy into item collections and indexes instead. In the diagram, the club's name is copied onto each membership item. The "my clubs" screen then needs one read, not one per club. The cost is that a club rename must update every copy.
One-to-many and many-to-many
One-to-many is the easy case. Put the parent and its children under the parent's partition key. Give the children a sort key prefix like ORDER# and read them with begins_with. 5
Many-to-many needs two directions. AWS calls the usual answer an adjacency list. Each entity is a partition. Each link is an item in that partition, with the target's ID as the sort key. 6 AWS's example is invoices and bills. One Query reads all bills on an invoice. For the reverse, "which invoices contain this bill?", you add a global secondary index (GSI) on the sort key. 6 People call this flipped index an inverted index. 2
A GSI is not free. It is updated asynchronously, usually "within a fraction of a second". A query on it can return stale results. 7 Each GSI also adds write cost, and a GSI short of write capacity throttles writes to the table. 7
Keep partitions bounded
A partition key with a few huge values is a trap. In DynamoDB, each partition can serve at most 3,000 read units and 1,000 write units per second. 4 Cassandra suggests under 100,000 values and under 100 MB per partition. 9 Its hard limit is 2 billion cells, but it gets slow well before that. 10
The fix is the one Discord used. Add a column to the partition key, such as a month or a date. 10 Here is the simplified schema from Discord's post. It keeps the newest messages first. The real table has about 10 more columns. 1
CREATE TABLE messages (
channel_id bigint,
bucket int,
message_id bigint,
author_id bigint,
content text,
PRIMARY KEY ((channel_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);The bucket must be computable from the ID or a timestamp. 1 Reads then walk buckets from now backwards until they have enough rows. The cost lands on quiet channels: they may need several queries to fill one page. 1 Pick the bucket size from your biggest key, not your average one.
Single-table design, and its critics
AWS's general advice is to keep "as few tables as possible". 2 Single-table design goes further. It stores many entity types in one table, so one Query can return a user and their orders together. 3 AWS also lists the costs. It has a steep learning curve. All entities share one backup, one encryption setting and one stream. 3 AWS says multiple tables are "good and sufficient" when you never query entities together. 3
Alex DeBrie, who recommends it for most apps, gives the main reason: fetching several item types "using a single request". 11 He lists the downsides too. New access patterns are hard to add, and analytics need extra work. He would skip it for GraphQL, and for new apps that value flexibility. 11
Pete Naylor, who worked at Amazon, pushes back harder. He says: "Do NOT start with exactly one table as a design constraint…" 12 He agrees the best answer might be one table, but says it often will be more. 12 Items in one table but different partitions are no cheaper to read than items in two tables. 12 The real win is the item collection. So treat the number of tables as an outcome of the modelling. 12
What you give up
- Ad-hoc queries. A question that the keys do not answer needs a Scan of the whole table, or a new index. 7
- Joins. Cassandra has none, so you copy data instead. 9
- Big transactions. A DynamoDB transaction holds up to 100 distinct items and 4 MB, in one account and Region. 8 Each item costs two writes: one to prepare and one to commit. 8
Trade-offs
| Choice | Fast reads | Easy to change later | Watch out for |
|---|---|---|---|
| One table per entity (normalised) | No Several requests per screen. | Yes | Code that joins in memory. 3 |
| Single-table design | Yes , when items share a partition key. 12 | No New patterns are hard to add. 11 | Shared backups, streams and encryption. 3 |
| Denormalised copies | Yes One read per screen. | No Each copy needs an update path. | Copies that disagree. |
| GSI for the reverse lookup | Yes One Query. | Yes You can add one later. | Stale reads and extra write cost. 7 |
| Time-bucketed partition key | Yes , for recent data. | Partly. Bucket size is hard to change. | Quiet keys need several queries. 1 |
Simple rule: if you cannot list the access patterns yet, you are not ready for these stores. Start with a relational database and come back.
At work: how a senior uses this
Here is a worked example: a small sports club app. First, the access patterns. Then the keys. Each row is one request.
| Access pattern | Request | PK | SK |
|---|---|---|---|
| Show a member's profile | GetItem | MEMBER#m1 | PROFILE |
| List a member's clubs | Query, begins_with | MEMBER#m1 | CLUB# |
| List a club's members | Query on GSI1 | CLUB#c1 (GSI1PK) | MEMBER# (GSI1SK) |
| Show one court's slots for a day | Query | COURT#c7#2026-11-20 | SLOT# |
| List a member's upcoming bookings | Query, between | MEMBER#m1 | BOOKING#2026-11-20 to BOOKING#9999 |
The bookings query needs an upper bound. A plain >= would also return the CLUB# and PROFILE items, because they sort after BOOKING#.
The court partition is bucketed by day, so it holds at most one item per slot. Booking writes two items in one transaction. The condition stops a double booking.
await ddb.send(new TransactWriteCommand({ TransactItems: [
{ Put: { TableName: "Club",
Item: { PK: "COURT#c7#2026-11-20", SK: "SLOT#18:00", member: "m1" },
ConditionExpression: "attribute_not_exists(PK)" } },
{ Put: { TableName: "Club",
Item: { PK: "MEMBER#m1", SK: "BOOKING#2026-11-20T18:00", court: "c7" } } },
] }));Habits that go with it:
- Write each access pattern with its key, its sort order and its peak rate. AWS says to know data size, shape and velocity first. 2
- For each partition key, ask: "What is the biggest this partition can get?" If there is no answer, add a bucket.
- For every copied field, name the code that updates it.
- Ask: "Which question will product ask next year?" If you can't answer it with a new GSI, say so now.
- Load test with your biggest real tenant or channel, not average data.
With AI
What to ask the agent
"Here are our 8 access patterns with rates. Propose a DynamoDB key design. For each pattern, show the exact GetItem or Query call, the PK and SK values, and how many items it reads."
"For this Cassandra schema, estimate the largest partition using our biggest customer's data. Show the formula and the numbers."
"List every field this design copies. For each one, show the code path that must change when the source changes."
What to check yourself
- Every access pattern maps to one request. None needs a Scan or a filter on a non-key field.
- No partition key value can grow without a limit.
- The agent did not add a GSI where the base table could already answer.
- Code that reads a GSI can handle a missing or stale item.
- Transactions stay under 100 items, and the agent counted the double write cost. 8
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 12 sources and related lessons
- Stanislav Vishnevskiy, “How Discord Stores Billions of Messages”, Discord blog (2017) (opens in a new tab)
The messages schema, the partitions over 100 MB, the 10-day buckets, and the tombstone problem in one channel. - Amazon DynamoDB Developer Guide: NoSQL design for DynamoDB (opens in a new tab)
Why you list the questions before the schema, and the principles of locality, sort order and spreading load. - Amazon DynamoDB Developer Guide: Data Modeling foundations in DynamoDB (opens in a new tab)
AWS's own list of pros, cons and fit for single table and multiple table design. - Amazon DynamoDB Developer Guide: Best practices for designing and using partition keys effectively in DynamoDB (opens in a new tab)
The per-partition limit of 3,000 read units and 1,000 write units per second. - Amazon DynamoDB Developer Guide: Best practices for using sort keys to organize data in DynamoDB (opens in a new tab)
Range queries with begins_with and between, and composite sort keys for hierarchies. - Amazon DynamoDB Developer Guide: Best practices for managing many-to-many relationships in DynamoDB tables (opens in a new tab)
The adjacency list pattern with invoices and bills, and a GSI on the sort key for the reverse lookup. - Amazon DynamoDB Developer Guide: Using Global Secondary Indexes in DynamoDB (opens in a new tab)
Why a query on a non-key attribute needs a Scan or an index, and how the index is kept in sync. - Amazon DynamoDB Developer Guide: Amazon DynamoDB Transactions: How it works (opens in a new tab)
The limits of TransactWriteItems and what a transaction costs in capacity. - Apache Cassandra Documentation: Data Modeling, Introduction (opens in a new tab)
Query-driven modelling, one table per query, partition and clustering keys, and partition size guidelines. - Apache Cassandra Documentation: Evaluating and refining data models (opens in a new tab)
How to estimate a partition's size, and how to split a big one by adding a column to the partition key. - Alex DeBrie, “The What, Why, and When of Single-Table Design with DynamoDB” (2020) (opens in a new tab)
The case for single-table design, its downsides, and when he would not use it. - Pete Naylor, “Single table design for DynamoDB: The reality”, Momento blog (2023) (opens in a new tab)
Someone who worked with DynamoDB at Amazon argues that item collections matter, and the number of tables should be an outcome.
Case studies: Uber: Schemaless: an append-only datastore built on MySQL
Related: Data models and query languages · Sharding and consistent hashing · Choosing a database · Secondary, composite and special indexes · Quorums and leaderless replication · DynamoDB in depth · Cassandra in depth
- Before this: Data models, Sharding and Secondary and composite indexes.
- Quorums and leaderless replication explains how Cassandra reads and writes replicas of each partition.
- Next: DynamoDB in depth and Cassandra in depth go deeper on each store.