How do you design partition keys for even data distribution in DynamoDB?
Learn how to design DynamoDB partition keys for even distribution using high-cardinality composite keys and write sharding, with code and interview questions.
Expected Interview Answer
You design partition keys for even distribution by choosing an attribute with high cardinality that is accessed uniformly, so DynamoDB's hash of the key scatters items and traffic evenly across physical partitions rather than concentrating them on a few.
DynamoDB routes an item to a partition by hashing its partition key, so distribution is driven by both the number of distinct key values (cardinality) and how evenly requests spread across those values. Good keys are things like userId, orderId, or a composite/tenant#entity value; poor keys are booleans, status flags, dates, or any low-cardinality or time-monotonic value that funnels traffic. When a naturally uniform key isn't available, you engineer one — adding a random or calculated shard suffix (write sharding), or combining attributes into a composite key — and you validate the design against real access patterns, since single-table design means the key must serve queries, not just distribution.
- Traffic spreads evenly so full table throughput is usable
- Avoids hot partitions and throttling under load
- Predictable latency at scale
- Supports the table's real query patterns, not just storage
- Reduces cost by removing the need to over-provision for skew
AI Mentor Explanation
A captain sets a fielding placement so the ball can land anywhere and a fielder is nearby, rather than stacking everyone on the leg side where few balls go. Designing a partition key is choosing that placement: pick a key whose values scatter like well-spread fielders, so incoming traffic finds capacity everywhere instead of piling onto one crowded region of the field.
Step-by-Step Explanation
Step 1
List your access patterns first
In DynamoDB you model queries before keys — enumerate how items are read and written so the key serves them.
Step 2
Assess cardinality
Prefer attributes with many distinct values (userId, orderId) over booleans, statuses or dates.
Step 3
Check access uniformity
High cardinality isn't enough — ensure traffic spreads evenly across values, not concentrated on a few.
Step 4
Use composite keys when needed
Combine attributes (tenantId#entityType) to raise cardinality and match query needs in single-table design.
Step 5
Shard inherently skewed keys
Add a random or hashed suffix to fan out an unavoidable hotspot, then scatter-gather on read.
Step 6
Validate against real traffic
Simulate or measure with CloudWatch and throttling metrics; adjust the key if partitions run hot.
What Interviewer Expects
- Distinguishes cardinality from access uniformity
- Models access patterns before choosing keys
- Cites good vs bad key examples (userId vs boolean/date)
- Explains composite keys and single-table design trade-offs
- Knows write sharding and scatter-gather reads for skewed keys
- Mentions validating with metrics rather than assuming
Common Mistakes
- Picking a low-cardinality attribute like status or a boolean flag
- Using a monotonic/time-based key that concentrates today's writes
- Choosing high cardinality but ignoring uneven access to those values
- Designing keys before understanding query patterns
- Sharding for distribution while breaking required query access
- Assuming the sort key affects distribution (only the partition key does)
Best Answer (HR Friendly)
“Designing a partition key means picking the field DynamoDB uses to decide where each record lives. You want a field with lots of different, evenly-used values — like a user id — so records and traffic spread out evenly. If your natural field is lopsided, you split it into buckets so no single slice gets overloaded.”
Code Example
// Bad: pk = status -> only a few values, huge hotspots
// Good: high-cardinality composite key that also serves queries
function buildKey({ tenantId, entityType, entityId, shards = 0 }) {
// Composite partition key raises cardinality and scopes queries
let pk = `${tenantId}#${entityType}`
if (shards > 0) {
// Add a shard suffix for an inherently hot tenant/entity
pk += `#${Math.floor(Math.random() * shards)}`
}
return { pk, sk: entityId }
}
await ddb.send(new PutCommand({
TableName: 'AppData',
Item: {
...buildKey({ tenantId: 'acme', entityType: 'order', entityId: 'o-1029' }),
createdAt: Date.now(),
},
}))Follow-up Questions
- How does a composite partition key differ from a partition key plus sort key?
- Why can a monotonically increasing key (timestamp) hurt distribution?
- How do you pick between write sharding and relying on adaptive capacity?
- How does single-table design influence partition key choice?
- How would you measure whether your partition key is distributing evenly?
MCQ Practice
1. Which attribute is the best partition key for even distribution?
userId has high cardinality and typically even access, so its hash spreads items and traffic across partitions.
2. Beyond cardinality, what else matters for a good partition key?
Even a high-cardinality key causes hotspots if a few values receive most of the traffic; access uniformity matters too.
3. In DynamoDB data modeling, when should you decide partition keys?
DynamoDB single-table design models access patterns first, then designs keys that satisfy those queries and distribute evenly.
Flash Cards
What two properties make a good partition key? — High cardinality (many distinct values) and even access across those values.
Why are booleans and statuses poor partition keys? — Low cardinality funnels most traffic onto a few partitions, creating hot partitions.
What is a composite partition key? — Concatenating attributes (e.g. tenantId#entityType) to raise cardinality and serve query patterns.
Does the sort key affect data distribution? — No — only the partition key's hash determines which physical partition an item lands on.
How do you handle an unavoidably skewed key? — Write sharding: add a random/hashed suffix, then read all shards via scatter-gather.
Continue Learning
Related Interview Questions
How does DynamoDB partitioning and data distribution work under the hood?
hard
What is a hot partition in DynamoDB and how do you avoid it?
medium
What are the real trade-offs of single-table design, and when would you not use it?
hard
What is the difference between DynamoDB and a relational database?
medium