DynamoDB partition and sort keys
Start with a shopping cart
DynamoDB is a managed NoSQL database that retrieves items by key. An item is a collection of named attributes, like a product record. A table groups items. Unlike a relational table, non-key attributes can differ between items. Start by writing down the questions your application must answer: fetch one cart line, list a customer’s cart, or find inventory for a product. These questions determine the keys, not the other way around.
Design a composite key
A simple primary key has one partition key. A composite primary key combines partition key (PK) and sort key (SK); only the pair must be unique. DynamoDB uses the partition key to distribute data. A partition is an internal storage allocation, not a customer or a fixed machine. Related items with the same PK form an item collection; the SK gives them a useful order. Key attributes are scalar strings, numbers or binary values. Here we use strings and prefixes as our own naming convention.
Read and write one item
The fictional table below has three cart lines and one profile. GetItem with both keys USER#12 and CART#B02 retrieves quantity 2. PutItem with an existing key replaces the item unless a condition prevents it; UpdateItem changes selected attributes and can create an item if absent. DeleteItem removes the identified item. A request to list all cart lines uses Query, covered next.
PK SK quantityUSER#12 CART#A01 1USER#12 CART#B02 2USER#12 PROFILE -USER#34 CART#B02 4Avoid a hot key and protect data
Putting every cart under PK=ALL_CARTS concentrates requests on one logical key. Prefer customer-specific keys for this workload; a single extremely busy customer can still create skew. Measure throttling before considering write sharding; sharding adds read fan-out. A key prefix is not an access-control boundary: enforce the authenticated customer’s identity in the app and scope IAM actions and table/index resources. Practice: propose keys for inventory records and explain why a cart query should not return a different customer’s rows.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
DynamoDB partition and sort keys — knowledge check
Apply DynamoDB concepts to fictional shopping workloads.
What uniquely identifies a cart line in the example?
Which key is a better starting point for listing one customer’s cart?
What can happen when PutItem uses an existing primary key without a condition?
Which statement describes a partition?
What must enforce customer isolation?