CodePark/ questions / RDS, Aurora & DynamoDB
START PRACTICINGPRACTICE
Backend question · Cloud & AWS › RDS, Aurora & DynamoDB

How do you design DynamoDB keys for an orders feature, and what is a hot partition? The app must fetch a customer's orders newest first and fetch a single order by ID.

In DynamoDB, you design keys from the access patterns, not from the entities. An access pattern is a question the app asks the database, such as "get this customer's orders". Every item has two keys:

  • A partition key decides where the item is stored.
  • An optional sort key orders the items inside that partition.

For "orders for a customer, newest first", use PK = CUSTOMER#<id> and SK = ORDER#<isoDate>#<orderId>. Then call Query with ScanIndexForward: false, which returns the items in reverse order, so the newest come first.

For "order by ID", add a GSI (global secondary index: a second copy of the data with different keys) keyed on the order ID. Or store a second item for the order. Single-table design puts several entity types in one table, with prefixed keys like CUSTOMER# and ORDER#. This lets you fetch related items in one query.

A hot partition happens when most traffic goes to one partition key value. Examples are a global STATUS#pending key, or one huge tenant. Each partition has its own throughput limits. So DynamoDB throttles (slows or rejects) requests on that partition, even when the table as a whole has spare capacity.

Fixes:

  • Choose high-cardinality keys (keys with many different values) that spread the load.
  • If one key is still hot, shard it: add a suffix like #1, #2 to split it across several partitions.
  • Design DynamoDB keys from the access patterns, not from the entities.
  • The partition key decides where data is stored. The sort key orders items and allows range queries.
  • Use the customer as the partition key and a date-prefixed sort key, then Query in reverse order for newest first.
  • Add a GSI or a duplicate item for other access patterns. Single-table design keeps several entity types in one table.
  • A hot partition is one key that gets most of the traffic and causes throttling. Use high-cardinality keys or shard the hot key.