Skip to main content

NoSQL Data Modeling

Learning objectives
  • Distinguish key-value, document, wide-column and graph models by the queries they make cheap
  • Decide embed versus reference in a document database
  • Design Cassandra tables query-first, choosing partition keys, clustering columns and time buckets
  • Build a DynamoDB single-table design with overloaded keys and global secondary indexes
  • Argue where NoSQL fits a bank or e-commerce platform (sessions, carts, catalogs, feeds) and where it does not (the ledger of record)

TL;DR​

  • Relational modeling starts from entities; NoSQL modeling starts from access patterns. List every query first, then design keys so each one is a single-partition lookup.
  • Key-value: get/put by key. Document: a self-contained aggregate (order with its lines) per document. Wide-column: rows grouped into partitions by a partition key and sorted by clustering keys. Graph: relationships are first-class and traversals are cheap.
  • In Cassandra, the partition key decides which nodes store the data, clustering columns decide sort order inside the partition, and you typically duplicate data into one table per query. Bound partition size with time buckets.
  • In DynamoDB, a table is partition key + sort key; single-table design stores several entity types in one table with prefixed keys (CUSTOMER#42, ORDER#2025-11-28#9001) so one Query returns a whole item collection. GSIs add alternate access paths, eventually consistent.
  • NoSQL fits high-volume, key-addressed, aggregate-shaped data: sessions, carts, catalogs, activity feeds, device and risk signals.
  • It is a poor fit for the ledger of record: multi-entity atomicity, constraints, ad-hoc audit queries and reconciliation are what relational databases do well.

Why it matters​

Large banks and e-commerce platforms are polyglot: Postgres or Oracle for accounts and orders, Redis for sessions and rate limits, a document store for the catalog, Cassandra or DynamoDB for activity history, a graph database for fraud rings, a search engine for discovery. Interviewers probe whether you can justify each store by its access patterns and consistency needs, and whether you know the modeling discipline each requires. A Cassandra table modeled like a relational one fails at scale; a DynamoDB design built without listing access patterns needs a migration the first time product asks for a new screen.

Core concepts​

The families​

FamilyData modelCheap operationsExamples
Key-valueOpaque value by keyGet/put/delete by key, TTLRedis, Memcached, DynamoDB (as KV), etcd
DocumentJSON-like documents, nestedFetch/update a whole aggregate, secondary indexes on fieldsMongoDB, Couchbase, Firestore
Wide-columnPartitions of sorted rowsWrite anything; read one partition by key and clustering rangeCassandra, ScyllaDB, HBase, Bigtable
GraphNodes, edges, propertiesMulti-hop traversalsNeo4j, Amazon Neptune, JanusGraph

Most of these give up something relational systems provide: joins, multi-entity transactions (or make them expensive), ad-hoc queries, schema enforcement. In exchange you get horizontal scaling by partition, predictable latency for designed queries, and flexible schemas.

Key-value: modeling is key design​

The only query is "by key", so all modeling lives in the key: namespaced, predictable and bounded. Examples: session:9f2c… (session blob with TTL), cart:42 (customer cart), ratelimit:api:merchant:7:2025-11-28T10:01 (counter per window). Choose values that are read and written as a unit, and keep them small. Key-value stores are covered in depth in Redis Deep Dive.

Document databases: embed or reference​

A document should match an aggregate in the DDD sense: a cluster of data that is read and changed together, with one consistency boundary (see Domain-Driven Design).

{
"_id": "ord_9001",
"customerId": "cus_42",
"status": "PAID",
"currency": "VND",
"totalMinor": 390000,
"shipping": { "line1": "12 Ly Thuong Kiet", "city": "Hanoi" },
"lines": [
{ "sku": "SKU-1", "name": "Coffee beans 1kg", "qty": 2, "unitPriceMinor": 150000 },
{ "sku": "SKU-9", "name": "Pour-over kettle", "qty": 1, "unitPriceMinor": 90000 }
],
"createdAt": "2025-11-28T09:12:44Z"
}
Embed whenReference when
The child is owned by the parent and has no independent life (order lines, shipping snapshot)The child is shared by many parents (a product referenced by many orders)
The child set is bounded and smallThe set grows without bound (reviews on a popular product, events on an account)
You read them together almost alwaysThe child is read or updated independently and frequently
Atomic updates across parent and children matterDocument size would approach limits (MongoDB documents are capped at 16 MB)

MongoDB specifics worth knowing: single-document writes are atomic; multi-document ACID transactions exist (replica sets since 4.0, sharded clusters since 4.2) but cost latency and should be the exception; $jsonSchema validators enforce structure; indexes include compound, multikey (on arrays), partial and TTL; in a sharded cluster, the shard key determines distribution and which queries are targeted versus scatter-gather, with the same trade-offs as in Partitioning & Sharding in Practice.

Wide-column: Cassandra query-first modeling​

Cassandra's primary key has two parts: PRIMARY KEY ((partition key columns), clustering columns).

  • The partition key is hashed (Murmur3) to a token, which decides which replicas store the partition. All rows of a partition live together on the same replica set.
  • Clustering columns sort rows within the partition, enabling range queries and ordered reads inside one partition.
  • Queries must specify the full partition key (otherwise they scan the cluster), and can filter clustering columns only left-to-right, like a composite index prefix.

Method: write down every query, then make a table per query whose partition key is the query's equality filter and whose clustering columns are its sort and range.

Activity feed for a shopping app, with three queries:

  1. Q1: latest activity of a customer, newest first, paged.
  2. Q2: all activity of a given type (for example REFUND_REQUESTED) for a merchant on a day.
  3. Q3: one event by id (for deep links from notifications).
-- Q1: partition per customer per day bounds partition size
CREATE TABLE activity_by_customer_day (
customer_id bigint,
day date,
event_time timeuuid,
event_type text,
merchant_id bigint,
payload text,
PRIMARY KEY ((customer_id, day), event_time)
) WITH CLUSTERING ORDER BY (event_time DESC)
AND default_time_to_live = 7776000 -- 90 days
AND compaction = {'class': 'TimeWindowCompactionStrategy',
'compaction_window_unit': 'DAYS', 'compaction_window_size': 1};

-- Q2: same data, different partitioning
CREATE TABLE activity_by_merchant_type_day (
merchant_id bigint,
event_type text,
day date,
event_time timeuuid,
customer_id bigint,
payload text,
PRIMARY KEY ((merchant_id, event_type, day), event_time)
) WITH CLUSTERING ORDER BY (event_time DESC);

-- Q3: lookup by id
CREATE TABLE activity_by_id (
event_id timeuuid PRIMARY KEY,
customer_id bigint,
event_type text,
payload text
);

The same event is written three times. That is normal: writes are cheap in an LSM engine (see Storage Engines), and denormalization is the price of single-partition reads. Use a logged batch when the three writes must eventually all apply (it guarantees all-or-eventually-all, not isolation) or make the writer idempotent and retry.

Rules of thumb (rough, version-dependent):

  • Bound partitions. Common guidance keeps partitions well under ≈ 100 MB and ≈ 100,000 rows. A partition per customer forever is unbounded for an active user; add a time bucket (day, month) sized to your write rate.
  • Avoid hot partitions. A partition per merchant per day for your largest merchant during a sale may take most of the cluster's writes for that table on three nodes. Add a bucket number ((merchant_id, day, bucket)) and fan out reads.
  • Consistency is per query. With replication factor 3, QUORUM writes and reads overlap (R + W > N) and give read-your-writes; LOCAL_QUORUM does the same within one data center. ONE is faster and may be stale.
  • Lightweight transactions (INSERT … IF NOT EXISTS, UPDATE … IF balance = ?) use Paxos per partition and need several round trips; fine for occasional uniqueness, not for every payment.
  • Deletes are tombstones; TTL and time-window compaction are the way to expire data cheaply.
  • Secondary indexes exist (Storage-Attached Indexes in Cassandra 5.0 improve them considerably) but queries still fan out across nodes unless they include the partition key.

DynamoDB: single-table design​

A DynamoDB table has a partition key (PK) and an optional sort key (SK). Items with the same PK form an item collection, stored together and sorted by SK. Query reads one item collection with SK conditions (=, begins_with, between, <, >); Scan reads the whole table and is almost never what you want online.

Single-table design puts several entity types in one table, overloading PK and SK with typed prefixes so related entities share a partition and one Query returns them together.

Access patterns for an order service:

  1. Get customer profile.
  2. List a customer's orders, newest first.
  3. Get an order with all its lines.
  4. List orders by status for the operations dashboard (for example all PAYMENT_PENDING older than 15 minutes).
EntityPKSKGSI1PKGSI1SKAttributes
CustomerCUSTOMER#42PROFILEname, email, tier
Order (customer view)CUSTOMER#42ORDER#2025-11-28T09:12:44Z#9001STATUS#PAID2025-11-28T09:12:44ZorderId, total, status
Order headerORDER#9001HEADERcustomerId, status, totalMinor, currency
Order lineORDER#9001LINE#001sku, qty, unitPriceMinor
  • Pattern 1: GetItem(PK=CUSTOMER#42, SK=PROFILE).
  • Pattern 2: Query(PK=CUSTOMER#42, SK begins_with "ORDER#"), ScanIndexForward=false.
  • Pattern 3: Query(PK=ORDER#9001) returns the header and all lines in one request.
  • Pattern 4: Query on GSI1 with GSI1PK=STATUS#PAYMENT_PENDING and GSI1SK < now-15m. A status GSI partition can be hot (millions of DELIVERED orders under one key); shard it (STATUS#DELIVERED#07) or use sparse indexes that only include items in active states, by removing GSI1PK when an order reaches a terminal state.

Index types and limits worth stating precisely:

  • GSI: any attributes as PK/SK, created any time, has its own throughput, updated asynchronously (eventually consistent reads only). A throttled GSI can back-pressure writes to the base table.
  • LSI: same PK, alternative SK, must be created with the table, supports strongly consistent reads, and limits each item collection to 10 GB.
  • Item size is limited to 400 KB. Transactions (TransactWriteItems) cover up to 100 items, with roughly double the capacity cost of normal writes.
  • Conditional writes (ConditionExpression) give compare-and-set for idempotency and optimistic locking; TTL expires items; Streams provide change data capture.

The downside of single-table design: it is optimized for known access patterns and painful for new ones; analytics require exporting to S3 or a warehouse; and the schema is understandable only with documentation of the key conventions. Many teams use a few tables (one per bounded context) with the same principles rather than one table per company.

Write sharding a hot key: a leaderboard​

A monthly game leaderboard needs the top 10 and "roughly where am I?". The obvious GSI, partition key chess#2025-11 and sort key score, serves the top 10 with one Query, but puts every score update of the month on one partition. With a rough ceiling of ≈1,000 write units per second per partition (see In practice), that caps the whole game, and a throttled GSI pushes back on base-table writes.

Write sharding adds a suffix to the key:

DesignGSI partition keyGSI sort keyWritesTop 10
Naivechess#2025-11scoreAll on one partitionOne Query
Shardedchess#2025-11#p3, where 3 = hash(user_id) mod NscoreSpread over N partitionsN parallel queries, merged
  • Top N: query the N keys in parallel (ScanIndexForward=false, Limit=10) and merge the short lists in the service. Each user lives in one shard, so the merge is exact; the GSI lags the base table slightly, which a leaderboard tolerates.
  • Rank: an exact rank would mean counting higher scores across all N partitions on every request. Show a percentile instead: users are hashed, so shards share a score distribution, and a periodic job can compute and cache cut-offs from one shard (for example "top 10% = 870+ points"). "Top 10%" also reads better than "#1,200,001".
  • Choosing N: peak writes divided by a safe per-partition rate, plus headroom; 5,000 updates/s suggests N ≈ 10 (rough). A larger N widens every read, and changing N rewrites the key attribute, so switch at the next month's board.

The same suffix trick fixes the hot status GSI in pattern 4 and the hot merchant partition in Cassandra. Full design: Real-time Gaming Leaderboard.

Graph databases​

When the question is about relationships several hops deep, graph databases make traversals cheap where SQL would need recursive self-joins.

Fraud ring detection: accounts, devices, phone numbers, cards, addresses and IP addresses are nodes; "used", "registered with", "shipped to" are edges. A ring shows up as many accounts connected through a few shared devices or cards.

// Cypher (Neo4j / openCypher): accounts within 3 hops of a known fraudster
MATCH (f:Account {flagged: true})-[:USED|PAID_WITH|SHIPPED_TO*1..3]-(a:Account)
WHERE a <> f
RETURN a.id, count(*) AS paths
ORDER BY paths DESC
LIMIT 50;

Typical uses in banks and e-commerce: fraud rings and mule-account networks, KYC/AML entity resolution and beneficial ownership chains, recommendations ("customers who bought X also bought"), and permission graphs. Graph stores are usually fed from the system of record via CDC, not used as it. See Fraud & Risk Systems.

Where NoSQL fits, and where it does not​

Use caseGood NoSQL fit?Why
Sessions, auth tokensYes (key-value)Key access, TTL, loss tolerable or re-creatable
Shopping cartYes (key-value or document)Per-customer aggregate, high write rate, availability over strict consistency; Amazon's Dynamo paper used the cart as its motivating example
Product catalogOften (document + search engine)Variable attributes per category, read-heavy, denormalized views
Activity feeds, notifications inbox, order history viewsYes (wide-column or DynamoDB)Append-heavy, per-user time-ordered reads, TTL
Device fingerprints, risk features, rate countersYes (key-value)Low-latency lookups by key during authorization
OrdersPossible (DynamoDB designs exist)Works for transactional access; reporting and ad-hoc queries need a pipeline
Ledger, balances, payments of recordUsually noNeeds atomic multi-account journals, constraints, auditable ad-hoc queries, reconciliation and decades of tooling; NoSQL transactions are limited in scope and cost
Regulatory reportingNoAd-hoc SQL over joined, historical data; use a warehouse fed by CDC

Trade-offs​

OptionStrengthsWeaknessesChoose when
RelationalJoins, constraints, transactions, ad-hoc queriesVertical scaling limits for writes; sharding is manual workSystem of record, complex invariants
Key-valueSimplest, fastest, scales linearlyOnly key access, no queries on valuesSessions, caches, counters, carts
DocumentAggregate per document, flexible schema, rich indexesCross-document consistency, unbounded embedded arraysCatalogs, profiles, content, orders as aggregates
Wide-columnMassive write throughput, multi-DC, tunable consistencyQuery-first rigidity, denormalization, tombstones, no joinsFeeds, time-series, event history at scale
DynamoDB single-tableFully managed, predictable latency at any scaleAccess patterns fixed up front, analytics need export, cost model to learnServerless or AWS-native high-scale services
GraphMulti-hop traversalsWeaker at bulk aggregations, scaling writesFraud rings, recommendations, entity resolution

In practice​

  • Start from the access-pattern table: query, frequency, latency target, consistency need, result size. Review it with product before choosing keys; new patterns later mean new tables or indexes and backfills.
  • Keep the relational system of record and project into NoSQL stores via CDC or outbox events (see Transactional Outbox & CDC). Projections can be rebuilt by replaying.
  • Idempotent writes: design writes so retries are harmless (deterministic keys, conditional writes), because at-least-once delivery is the norm.
  • Capacity: in DynamoDB, a single partition supports on the order of 1,000 write units and 3,000 read units per second; adaptive capacity helps but cannot fix one hot key. In Cassandra, watch partition size and per-node load.

Optimistic locking for a cart in DynamoDB with the AWS SDK for Go v2:

package carts

import (
"context"
"errors"
"strconv"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

var ErrConflict = errors.New("cart was modified concurrently")

// SaveCart writes the cart only if the stored version is the one the caller read.
func SaveCart(ctx context.Context, db *dynamodb.Client, customerID, itemsJSON string, readVersion int) error {
_, err := db.PutItem(ctx, &dynamodb.PutItemInput{
TableName: aws.String("shop"),
Item: map[string]types.AttributeValue{
"PK": &types.AttributeValueMemberS{Value: "CUSTOMER#" + customerID},
"SK": &types.AttributeValueMemberS{Value: "CART"},
"items": &types.AttributeValueMemberS{Value: itemsJSON},
"ver": &types.AttributeValueMemberN{Value: strconv.Itoa(readVersion + 1)},
},
ConditionExpression: aws.String("attribute_not_exists(PK) OR #ver = :read"),
ExpressionAttributeNames: map[string]string{
"#ver": "ver",
},
ExpressionAttributeValues: map[string]types.AttributeValue{
":read": &types.AttributeValueMemberN{Value: strconv.Itoa(readVersion)},
},
})
var ccf *types.ConditionalCheckFailedException
if errors.As(err, &ccf) {
return ErrConflict
}
return err
}

Common pitfalls​

  • Modeling Cassandra tables like relational ones and querying with ALLOW FILTERING. Symptom: queries that scan the cluster and time out under load.
  • Unbounded partitions or embedded arrays. A partition per merchant forever, or every review embedded in the product document. Symptom: slow reads, large GC pauses, document size errors.
  • Hot keys and partitions. One celebrity merchant, one status value in a GSI. Symptom: throttling on a single partition while the table is mostly idle.
  • Using Cassandra as a queue. Insert, consume, delete. Symptom: tombstone warnings and failing reads.
  • Assuming GSIs are consistent. Symptom: an order just created is missing from the "pending orders" view for a moment; code that reads-after-write through a GSI breaks.
  • Scans in request paths. Symptom: DynamoDB costs and latency scale with table size.
  • Choosing NoSQL for the ledger "for scale" before quantifying the write rate. Symptom: re-implementing transactions, constraints and reconciliation in application code, with bugs.
  • No plan for analytics. Symptom: product asks "how many carts were abandoned last month" and nobody can answer without a full export.

Interview angle​

  • Prompts: "Why not just use MongoDB for everything?", "Design the data model for an activity feed in Cassandra", "Model orders in DynamoDB", "Where would you use a graph database in a bank?"
  • A strong answer lists access patterns first, derives keys from them, sizes partitions, addresses hot keys, chooses consistency levels, and states what is given up (joins, ad-hoc queries, multi-entity transactions).
  • Show polyglot judgment: relational for money and orders of record; NoSQL for sessions, carts, catalogs, feeds; CDC between them.
  • Follow-ups: "A new screen needs orders by merchant, what do you do?" (new GSI or table plus backfill), "How do you keep the three Cassandra tables consistent?" (idempotent writes, logged batch, repair), "What consistency level and why?".
  • Red flags: "NoSQL scales, SQL doesn't" without numbers, no partition-size reasoning, using NoSQL to avoid schema design.

Self-check​

1. What do the partition key and clustering columns each control in Cassandra?

The partition key is hashed to a token that determines which replica nodes store the partition, and every query should specify it fully for a single-partition read. Clustering columns define the sort order of rows within a partition, which enables efficient range queries and ordered pagination inside that partition, filtered left to right.

2. Why does Cassandra modeling often duplicate the same data into several tables?

Because each table can efficiently answer only queries that specify its partition key and walk its clustering order. To serve several query shapes with single-partition reads, you write the same event into a table per query. Writes are cheap in the LSM engine, so you trade storage and write work for predictable reads, and handle consistency between copies with idempotent writes or logged batches.

3. When would you embed order lines in the order document and when would you reference products?

Embed lines because they are owned by the order, bounded in number, always read with it, and must change atomically with it; include a snapshot of name and price at purchase time. Reference products because they are shared by many orders, change independently, and their current details are not part of the order's history.

4. Explain a DynamoDB item collection and how single-table design uses it.

All items sharing a partition key form an item collection, stored together and sorted by sort key. Single-table design assigns related entities the same PK (for example ORDER#9001) with type-prefixed sort keys (HEADER, LINE#001), so one Query on the PK returns the order and its lines together, replacing a join with a single request.

5. What are the consistency and capacity implications of a GSI?

GSIs are updated asynchronously from the base table, so reads from a GSI are eventually consistent and may miss very recent writes. They have their own throughput; if a GSI is under-provisioned or has a hot partition key, its throttling can slow writes to the base table. Hot GSI keys (like a status value) need sharding or sparse-index design; the leaderboard example above walks through the sharding route end to end.

6. Scenario: a team wants to move the bank's account ledger to Cassandra to handle a year-end peak. How do you respond?

Clarify the peak write rate and the ledger's guarantees. Postings must atomically debit and credit accounts that live in different partitions, balances must not go below limits, and auditors need ad-hoc historical queries. Cassandra offers only per-partition lightweight transactions and no joins. Recommend keeping the ledger relational (partitioned, possibly sharded by account, or distributed SQL), and using Cassandra for high-volume derived views such as transaction history feeds fed by CDC.

7. How would you size the partition key for an activity table where heavy users generate 5,000 events per day?

A partition per customer forever would grow without bound. Bucket by time: (customer_id, day) gives about 5,000 rows per partition for the heaviest users, comfortably bounded; lighter users get small partitions, which is fine. Reads for "latest activity" query today's bucket first and walk backwards day by day until the page is filled.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Model and run an activity feed in Cassandra.

docker run --name cass -d -p 9042:9042 cassandra:5.0
# wait about a minute for startup, then:
docker exec -it cass cqlsh
CREATE KEYSPACE shop WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
USE shop;
  1. Create the three activity tables from this page. Insert events for two customers over three days with now() for event_time, writing each event to all three tables.
  2. Run Q1 for one customer and day with LIMIT 20, Q2 for a merchant and type, Q3 by id. Then try a query that filters on event_type in activity_by_customer_day and read the error; explain why.
  3. Use TRACING ON and compare the trace of a single-partition read with one that needs ALLOW FILTERING.
  4. On paper, design a DynamoDB single-table layout for merchant settlements: patterns "settlements of a merchant by date", "one settlement with its line items", "all settlements in status FAILED today". Show PK, SK and any GSI, and identify the hot key risk.
  5. Write one paragraph arguing which parts of a payment platform you would not put in either store.

Done when every query runs as a single-partition read, you can explain the filtering error, and your DynamoDB design serves all three patterns with Query (no Scan).

Further reading​

  • Martin Kleppmann, Designing Data-Intensive Applications, ch. 2 and ch. 5.
  • Giuseppe DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store" (SOSP 2007).
  • Avinash Lakshman and Prashant Malik, "Cassandra: A Decentralized Structured Storage System" (2010).
  • Alex DeBrie, The DynamoDB Book.
  • Apache Cassandra documentation, "Data Modeling" section (cassandra.apache.org).
  • AWS documentation, "Best practices for designing and architecting with DynamoDB".
  • MongoDB documentation, "Data Modeling".
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).