One-to-many relationship patterns in DynamoDB - Time & Space Complexity
When working with one-to-many relationships in DynamoDB, it is important to understand how the time to get data grows as the number of related items increases.
We want to know how the cost changes when we fetch many related records for one main item.
Analyze the time complexity of the following DynamoDB query pattern.
// Query to get all orders for a single customer
const params = {
TableName: "Orders",
KeyConditionExpression: "customerId = :cid",
ExpressionAttributeValues: {
":cid": { S: "123" }
}
};
const result = await dynamodb.query(params).promise();
This code fetches all orders linked to one customer using a query on the partition key.
Look for repeated actions that affect performance.
- Primary operation: Reading each order item for the customer.
- How many times: Once per order item returned by the query.
As the number of orders for a customer grows, the query reads more items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 item reads |
| 100 | About 100 item reads |
| 1000 | About 1000 item reads |
Pattern observation: The number of operations grows directly with the number of related items.
Time Complexity: O(n)
This means the time to get all related items grows linearly with how many items there are.
[X] Wrong: "Querying related items always takes constant time regardless of how many items exist."
[OK] Correct: Each related item must be read, so more items mean more work and longer time.
Understanding how queries scale with related data helps you design better data models and answer questions confidently in interviews.
"What if we added pagination to limit the number of related items returned at once? How would the time complexity change?"