Hot partition prevention in DynamoDB - Time & Space Complexity
When using DynamoDB, some partitions can get too many requests, slowing down the whole system.
We want to understand how the work grows when we try to avoid these busy spots, called hot partitions.
Analyze the time complexity of the following code snippet.
// Example: Writing items with a random suffix to avoid hot partitions
const putItem = async (item) => {
const partitionKey = item.id + "-" + Math.floor(Math.random() * 10);
await dynamoDb.put({
TableName: "Orders",
Item: { ...item, partitionKey: partitionKey }
}).promise();
};
for (const order of orders) {
await putItem(order);
}
This code adds a random number to the partition key to spread writes evenly and prevent hot partitions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing each item to DynamoDB with a randomized partition key.
- How many times: Once per item in the orders list, so as many times as the number of orders.
Each new order causes one write operation, but the random suffix helps spread these writes evenly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes spread across partitions |
| 100 | 100 writes spread across partitions |
| 1000 | 1000 writes spread across partitions |
Pattern observation: The number of operations grows directly with the number of items, but the load is balanced to avoid slowdowns.
Time Complexity: O(n)
This means the time to write all items grows linearly with the number of items, but spreading keys prevents slowdowns from busy partitions.
[X] Wrong: "Adding a random suffix makes the operation slower because it adds extra work."
[OK] Correct: The random suffix does not add extra loops or big work; it just changes keys to spread load, keeping the overall time linear.
Understanding how to prevent hot partitions shows you can design systems that stay fast even with lots of data, a key skill for real projects.
"What if we used a fixed partition key without randomization? How would the time complexity and performance be affected?"