Introduction
Batch limits and retries help you send or receive many items efficiently without overloading the system or losing data.
BatchWriteItemRequest {
RequestItems: {
TableName: [
{ PutRequest: { Item: {...} } },
{ DeleteRequest: { Key: {...} } }
]
},
ReturnConsumedCapacity: 'TOTAL' | 'NONE',
ReturnItemCollectionMetrics: 'SIZE' | 'NONE'
}
BatchGetItemRequest {
RequestItems: {
TableName: {
Keys: [ { KeyAttribute: value }, ... ],
ProjectionExpression: 'attribute1, attribute2'
}
},
ReturnConsumedCapacity: 'TOTAL' | 'NONE'
}BatchWriteItemRequest with 3 items: { RequestItems: { 'Books': [ { PutRequest: { Item: { 'ISBN': '123', 'Title': 'Book A' } } }, { PutRequest: { Item: { 'ISBN': '456', 'Title': 'Book B' } } }, { DeleteRequest: { Key: { 'ISBN': '789' } } } ] } }
BatchGetItemRequest with 2 keys: { RequestItems: { 'Books': { Keys: [ { 'ISBN': '123' }, { 'ISBN': '456' } ], ProjectionExpression: 'Title, Author' } } }
Empty BatchWriteItemRequest:
{
RequestItems: {
'Books': []
}
}BatchWriteItemRequest with 26 items (exceeds limit): // This will cause an error and needs splitting into two batches.
import boto3 from botocore.exceptions import ClientError # Create DynamoDB client client = boto3.client('dynamodb') def batch_write_with_retries(table_name, items): max_batch_size = 25 unprocessed_items = [] # Split items into batches of 25 for i in range(0, len(items), max_batch_size): batch = items[i:i+max_batch_size] request_items = {table_name: [{'PutRequest': {'Item': item}} for item in batch]} while True: response = client.batch_write_item(RequestItems=request_items) unprocessed = response.get('UnprocessedItems', {}) if not unprocessed or not unprocessed.get(table_name): break # All items processed # Retry unprocessed items request_items = unprocessed print(f"All items written to {table_name} with retries if needed.") # Example items to write items_to_write = [ {'ISBN': {'S': '001'}, 'Title': {'S': 'Book One'}}, {'ISBN': {'S': '002'}, 'Title': {'S': 'Book Two'}}, {'ISBN': {'S': '003'}, 'Title': {'S': 'Book Three'}} ] print("Before batch write") batch_write_with_retries('Books', items_to_write) print("After batch write")
BatchWriteItem request in DynamoDB?BatchWriteItem request.response = client.batch_write_item(RequestItems={
'MyTable': [
{'PutRequest': {'Item': {'ID': {'S': '1'}}}},
{'PutRequest': {'Item': {'ID': {'S': '2'}}}}
]
})
print(response.get('UnprocessedItems'))
If the response prints {}, what does it mean?UnprocessedItems key contains items that DynamoDB did not process and need retrying.{} means no unprocessed items, so all were processed successfully.Pass the test and this pattern moves unknown