Partition Keys, Sort Keys, and Secondary Indexes

~12 min read

The single most important design decision in DynamoDB — how items are physically organized and looked up.

The Partition Key is hashed by DynamoDB to determine which physical partition stores an item, and every efficient query must specify it (or use an index) — there's no way to efficiently scan for an item by a non-key attribute without one. Choosing a partition key with high cardinality and evenly distributed access is critical: a poorly chosen key (e.g. one with only a handful of possible values, or where 90% of traffic hits one specific value) creates a 'hot partition,' where that one partition's throughput ceiling throttles requests even though the table's overall provisioned or on-demand capacity is far from exhausted.

Adding a Sort Key creates a composite primary key, allowing multiple items to share the same partition key while being stored together, sorted, and efficiently range-queried within that partition — this is the mechanism behind patterns like 'get all of user X's orders, sorted by date' in a single efficient query.

When you need to query by an attribute that isn't part of your primary key, a Global Secondary Index (GSI) creates what's effectively a second table-like view with its own partition/sort key drawn from your item's attributes, asynchronously and eventually-consistently kept in sync with the base table. A Local Secondary Index (LSI) is more restrictive — same partition key as the base table, an alternate sort key, must be defined at table creation time, but offers the option of strongly consistent reads, which GSIs cannot.

💬 Deep Dive with AI

Key points

  • Partition Key determines physical storage; queries need it (or an index) to be efficient
  • Low-cardinality or skewed-access partition keys cause 'hot partitions' and throttling
  • Sort Key enables efficient range queries within a shared partition key
  • GSI: new key structure, eventually consistent, addable anytime; LSI: alternate sort key only, defined at creation, supports strong consistency