Read and write capacity units in DynamoDB - Time & Space Complexity
When working with DynamoDB, it's important to understand how read and write capacity units affect performance.
We want to know how the number of capacity units used grows as we read or write more data.
Analyze the time complexity of the following DynamoDB operations.
// Writing multiple items
const items = [...]; // list of items
for (const item of items) {
await dynamodb.putItem({ TableName: 'MyTable', Item: item });
}
// Reading multiple items
const keys = [...]; // list of keys
const result = await dynamodb.batchGetItem({
RequestItems: { 'MyTable': { Keys: keys } }
});
This code writes many items one by one and reads many items in a batch from DynamoDB.
Look for repeated actions that cost time.
- Primary operation: Writing each item individually in a loop.
- How many times: Once per item in the list.
- Secondary operation: Reading multiple items in one batch request.
- How many times: One batch call for all keys.
As you add more items, the number of capacity units used grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 write units for writes, 1 batch read |
| 100 | About 100 write units for writes, 1 batch read |
| 1000 | About 1000 write units for writes, 10 batch reads |
Writing scales linearly with the number of items because each item costs capacity units. Reading in batch is one operation but capacity units depend on total data size.
Time Complexity: O(n)
This means the capacity units and time grow directly with the number of items you read or write.
[X] Wrong: "Batch reading many items costs the same as reading one item."
[OK] Correct: Even though batch reads are one request, the capacity units used depend on the total size of all items read, so cost grows with data size.
Understanding how capacity units scale helps you design efficient DynamoDB usage and shows you can think about performance in real systems.
"What if we switched from writing items one by one to using batch write operations? How would the time complexity change?"