GSI key selection strategy in DynamoDB - Time & Space Complexity
When using Global Secondary Indexes (GSIs) in DynamoDB, the way we pick keys affects how fast queries run.
We want to know how the choice of keys changes the work DynamoDB does as data grows.
Analyze the time complexity of querying a GSI with a chosen partition key and sort key.
const params = {
TableName: "Orders",
IndexName: "CustomerDateIndex",
KeyConditionExpression: "CustomerId = :cid AND OrderDate >= :start",
ExpressionAttributeValues: {
":cid": "12345",
":start": "2023-01-01"
}
};
const result = await dynamodb.query(params).promise();
This code queries a GSI named CustomerDateIndex using CustomerId as partition key and OrderDate as sort key.
Look for repeated work done during the query.
- Primary operation: Scanning items with the same partition key in the GSI.
- How many times: Once per matching partition key group; then filtering by sort key range.
As more items share the same partition key, the query checks more items in that group.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 items with same key | 10 checks |
| 100 items with same key | 100 checks |
| 1000 items with same key | 1000 checks |
Pattern observation: The work grows linearly with the number of items sharing the partition key.
Time Complexity: O(n)
This means the query time grows directly with how many items share the same partition key in the GSI.
[X] Wrong: "Choosing any partition key for the GSI will always give fast queries regardless of data distribution."
[OK] Correct: If many items share the same partition key, the query must check all those items, making it slower as data grows.
Understanding how GSI key choices affect query speed shows you can design databases that stay fast even as data grows.
What if we changed the GSI partition key to a more unique attribute? How would the time complexity change?
Practice
Solution
Step 1: Understand partition key role in GSI
The partition key determines how data is spread across storage partitions in DynamoDB.Step 2: Importance of even data distribution
Choosing a partition key that evenly distributes data avoids hot partitions and improves query speed.Final Answer:
To evenly distribute data across partitions for faster queries -> Option AQuick Check:
Partition key = data distribution [OK]
- Thinking partition key orders data inside partitions
- Confusing partition key with sort key
- Assuming partition key encrypts data
Category and a sort key named Timestamp in a DynamoDB table creation JSON?Solution
Step 1: Identify partition and sort key roles
Partition key uses KeyType "HASH" and sort key uses KeyType "RANGE" in DynamoDB.Step 2: Match keys to correct KeyType
Category is partition key so it must have KeyType "HASH"; Timestamp is sort key so it must have KeyType "RANGE".Final Answer:
Correct JSON with Category as HASH and Timestamp as RANGE -> Option BQuick Check:
Partition key = HASH, Sort key = RANGE [OK]
- Swapping HASH and RANGE key types
- Using RANGE for partition key
- Incorrect JSON structure for KeySchema
UserId and the sort key is OrderDate, what will be the result of this query?Query on GSI with UserId = 'user123' and OrderDate between '2023-01-01' and '2023-01-31'
Solution
Step 1: Understand query conditions on GSI keys
Query uses partition key UserId = 'user123' and a range condition on sort key OrderDate between two dates.Step 2: Result filters by UserId and date range
Only items with UserId 'user123' and OrderDate in January 2023 are returned, sorted by OrderDate.Final Answer:
All orders by user123 in January 2023 sorted by OrderDate -> Option AQuick Check:
Partition key + sort key range = filtered query [OK]
- Thinking query returns all users' data
- Ignoring sort key range condition
- Assuming syntax error without filter expression
Category and sort key Price. Your queries on this GSI are slow and uneven. What is the most likely cause?Solution
Step 1: Analyze partition key distribution
If Category has few distinct values, many items share the same partition key, causing hot partitions and slow queries.Step 2: Understand impact on query performance
Hot partitions limit throughput and cause uneven query speed despite having a sort key.Final Answer:
Category has very few distinct values causing hot partitions -> Option DQuick Check:
Few partition keys = hot partitions = slow queries [OK]
- Assuming missing sort key causes slowness
- Ignoring partition key cardinality
- Thinking projection affects partitioning
CustomerId and sort them by OrderStatus and then by OrderDate. Which key selection strategy is best?Solution
Step 1: Identify query pattern requirements
You want to query by CustomerId and sort first by OrderStatus, then by OrderDate.Step 2: Design composite sort key for multi-level sorting
Concatenate OrderStatus and OrderDate into one sort key string (e.g., 'Shipped#2023-06-01') to sort by status then date.Step 3: Assign keys correctly
Partition key should be CustomerId for grouping orders by customer; sort key is the concatenated string for sorting.Final Answer:
Partition key: CustomerId; Sort key: OrderStatus#OrderDate concatenated string -> Option CQuick Check:
Composite sort key enables multi-level sorting [OK]
- Using OrderStatus as partition key causing uneven distribution
- Not combining sort keys for multi-level order
- Using OrderDate as partition key which breaks grouping
Ready to prove it?
Pass the test and this pattern moves unknown
