Batch Writing to DynamoDB with AWS Emulator (BatchWriteItem)
With DynamoDB's BatchWriteItem, you can put (add or overwrite) and delete up to 25 items in a single request. Use it when you need to write many items at once, such as loading test data or migrating from another database. This article shows the results of writing in batches with the AWS CLI and Python (Boto3) against AWS Emulator on a local machine, without an AWS account, and checking the limits and how failures are returned. The commands and output are copied as they ran in the test environment.
The test environment was Ubuntu 24.04 (x86_64), AWS Emulator 1.0.556 (released November 21, 2026, Debian package), AWS CLI 2.42.1, Python 3.11, and Boto3 1.44.9. No AWS account or credentials were used. I did not test how real Amazon DynamoDB behaves: the rate at which writes are throttled, the timing, the result of batch_writer resending without waiting, the capacity consumed, or the cost. Where the article mentions these, it relies on the official documentation. I also did not test the item size limit (400KB), the request size limit (16MB), ThrottlingException, or SDKs other than Python.
- 1. Start the emulator and create a table
- 2. Write 3 items at once with the AWS CLI
- 3. Mix deletes and overwrites in one request
- 4. Write to 2 tables in one call
- 5. Over 25 items and none are written
- 6. Items that could not be written come back in UnprocessedItems
- 7. With Boto3's batch_writer, splitting and resending are handled for you
- 8. When batch_writer writes the same key twice
Start the emulator and create a table
I installed AWS Emulator by following the Linux installation steps. I verified the Debian package signature with gpg before installing, then started it with aws-emulator -t off (-t off turns off telemetry). I pointed the AWS CLI and Boto3 at the emulator with the environment variables described in the official documentation. The documentation warns that if you run commands in a shell where AWS_ENDPOINT_URL is not set, any credentials you have will be used to send requests to real AWS.
I created an on-demand Cats table with only a string partition key id. Right after creation, the table is CREATING. Writing during this time was rejected with ResourceNotFoundException.
$ aws dynamodb create-table --table-name Cats --attribute-definitions AttributeName=id,AttributeType=S --key-schema AttributeName=id,KeyType=HASH --billing-mode PAY_PER_REQUEST --query TableDescription.TableStatus
"CREATING"
$ aws dynamodb batch-write-item --request-items file://items.json
aws: [ERROR]: An error occurred (ResourceNotFoundException) when calling the BatchWriteItem operation: Requested resource not found
The BatchWriteItem API reference says ResourceNotFoundException is returned not only when the table does not exist but also when it is not ACTIVE. In a script that creates a table, wait until it becomes ACTIVE with aws dynamodb wait table-exists before writing.
$ aws dynamodb wait table-exists --table-name Cats
$ aws dynamodb describe-table --table-name Cats --query Table.TableStatus
"ACTIVE"
Write 3 items at once with the AWS CLI
For batch-write-item, you pass a JSON object whose keys are table names and whose values are lists of write operations. Wrap each item in PutRequest, and write its attributes in Item using the same typed format as PutItem (for example, {"S": ...}).
$ cat items.json
{
"Cats": [
{"PutRequest": {"Item": {"id": {"S": "tama"}, "name": {"S": "タマ"}, "age": {"N": "3"}}}},
{"PutRequest": {"Item": {"id": {"S": "kuro"}, "name": {"S": "クロ"}, "age": {"N": "5"}}}},
{"PutRequest": {"Item": {"id": {"S": "shiro"}, "name": {"S": "シロ"}, "age": {"N": "1"}}}}
]
}
$ aws dynamodb batch-write-item --request-items file://items.json
{
"UnprocessedItems": {}
}
If UnprocessedItems in the response is empty, every item was written. A scan returned the 3 items.
$ aws dynamodb scan --table-name Cats --query "Items[].[id.S,name.S,age.N]" --output text | sort
kuro クロ 5
shiro シロ 1
tama タマ 3
Mix deletes and overwrites in one request
A single request can contain both PutRequest and DeleteRequest. For DeleteRequest, put only the primary key in Key. Here I deleted shiro, rewrote the existing tama, and added mike. Adding --return-consumed-capacity TOTAL also returns the write capacity consumed.
$ cat mixed.json
{
"Cats": [
{"DeleteRequest": {"Key": {"id": {"S": "shiro"}}}},
{"PutRequest": {"Item": {"id": {"S": "tama"}, "name": {"S": "タマ"}, "age": {"N": "4"}}}},
{"PutRequest": {"Item": {"id": {"S": "mike"}, "name": {"S": "ミケ"}, "age": {"N": "2"}}}}
]
}
$ aws dynamodb batch-write-item --request-items file://mixed.json --return-consumed-capacity TOTAL
{
"UnprocessedItems": {},
"ConsumedCapacity": [
{
"TableName": "Cats",
"CapacityUnits": 3.0
}
]
}
$ aws dynamodb scan --table-name Cats --query "Items[].[id.S,name.S,age.N]" --output text | sort
kuro クロ 5
mike ミケ 2
tama タマ 4
The age of tama changed from 3 to 4. However, this replaced the whole item. It did not update only some attributes. The API reference says BatchWriteItem cannot update items, and an existing item is overwritten. There is no UpdateRequest operation, and the AWS CLI rejected it before sending the request.
$ aws dynamodb batch-write-item --request-items '{"Cats":[{"UpdateRequest":{"Key":{"id":{"S":"tama"}}}}]}'
aws: [ERROR]: An error occurred (ParamValidation): Parameter validation failed:
Unknown parameter in RequestItems.Cats[0]: "UpdateRequest", must be one of: PutRequest, DeleteRequest
To change only some attributes, the API reference recommends UpdateItem. You also cannot attach a condition (ConditionExpression) to an individual item in a batch.
Write to 2 tables in one call
If you list two table names in the --request-items JSON, you can write to both tables in one call. I created an Owners table with the partition key ownerId and wrote one item to each table.
$ cat twotables.json
{
"Cats": [
{"PutRequest": {"Item": {"id": {"S": "hachi"}, "name": {"S": "ハチ"}, "ownerId": {"S": "o-1"}}}}
],
"Owners": [
{"PutRequest": {"Item": {"ownerId": {"S": "o-1"}, "name": {"S": "example-owner"}}}}
]
}
$ aws dynamodb batch-write-item --request-items file://twotables.json
{
"UnprocessedItems": {}
}
$ aws dynamodb get-item --table-name Owners --key "{\"ownerId\":{\"S\":\"o-1\"}}" --query Item.name.S
"example-owner"
Over 25 items and none are written
A single request can carry at most 25 items. I generated JSON files with 25 and 26 items in Python (the items are named cat-000 onward, and the 26-item file starts at cat-100) and sent each one.
$ aws dynamodb batch-write-item --request-items file://put25.json
{
"UnprocessedItems": {}
}
$ aws dynamodb batch-write-item --request-items file://put26.json 2>&1 | sed -E "s/Value .* at /Value (省略) at /"
aws: [ERROR]: An error occurred (ValidationException) when calling the BatchWriteItem operation: 1 validation error detected: Value (省略) at 'requestItems' failed to satisfy constraint: Member must have length less than or equal to 25
$ aws dynamodb get-item --table-name Cats --key "{\"id\":{\"S\":\"cat-100\"}}"
The error for 26 items includes all 26 submitted items, which makes it very long, so I used sed to replace the item list with a short placeholder in the output. Reading cat-100, the first of the 26 items, returned nothing.
Sometimes a single problem causes the whole request to be rejected. The API reference lists the main conditions for rejecting the entire request:
- One of the specified tables does not exist.
- A primary key attribute does not match the table's key definition.
- The same item is operated on more than once in one request (this includes putting and deleting the same item).
- More than 25 items are in the request.
- An item is larger than 400KB, or the whole request is larger than 16MB.
- A key exceeds its length limit (2048 bytes for a partition key and 1024 bytes for a sort key).
On the emulator, I tested the first four conditions (for the item count, see the previous section). A PutRequest and another PutRequest with the same key were rejected with ValidationException, and so was a PutRequest and a DeleteRequest with the same key.
$ cat dup.json; echo
{"Cats": [{"PutRequest": {"Item": {"id": {"S": "dup"}, "age": {"N": "1"}}}}, {"PutRequest": {"Item": {"id": {"S": "dup"}, "age": {"N": "2"}}}}]}
$ aws dynamodb batch-write-item --request-items file://dup.json
aws: [ERROR]: An error occurred (ValidationException) when calling the BatchWriteItem operation: Provided list of item keys contains duplicates
$ cat putdel.json; echo
{"Cats": [{"PutRequest": {"Item": {"id": {"S": "del-dup"}}}}, {"DeleteRequest": {"Key": {"id": {"S": "del-dup"}}}}]}
$ aws dynamodb batch-write-item --request-items file://putdel.json
aws: [ERROR]: An error occurred (ValidationException) when calling the BatchWriteItem operation: Provided list of item keys contains duplicates
The whole request was also rejected when only one of the two items had its id key typed as a number (N), and when a request included a nonexistent table, NoSuchTable. In both cases, reading the valid item (ok-1 and t1) returned nothing.
$ cat badtype.json; echo
{"Cats": [{"PutRequest": {"Item": {"id": {"S": "ok-1"}}}}, {"PutRequest": {"Item": {"id": {"N": "1"}}}}]}
$ aws dynamodb batch-write-item --request-items file://badtype.json
aws: [ERROR]: An error occurred (ValidationException) when calling the BatchWriteItem operation: The provided key element does not match the schema
$ aws dynamodb get-item --table-name Cats --key "{\"id\":{\"S\":\"ok-1\"}}"
$ cat notable.json; echo
{"Cats": [{"PutRequest": {"Item": {"id": {"S": "t1"}}}}], "NoSuchTable": [{"PutRequest": {"Item": {"id": {"S": "t2"}}}}]}
$ aws dynamodb batch-write-item --request-items file://notable.json
aws: [ERROR]: An error occurred (ResourceNotFoundException) when calling the BatchWriteItem operation: Requested resource not found
$ aws dynamodb get-item --table-name Cats --key "{\"id\":{\"S\":\"t1\"}}"
Items that could not be written come back in UnprocessedItems
Apart from requests rejected as a whole, some items may be returned unwritten. According to the API reference, each individual put and delete in BatchWriteItem is atomic, but the batch as a whole is not. When some items cannot be written, for example because they exceed the table's write capacity, those items are returned in UnprocessedItems. If no items are written, the call fails with an error such as ProvisionedThroughputExceededException. UnprocessedItems has the same shape as RequestItems, so you can pass it directly to the next request.
Even when UnprocessedItems is not empty, the AWS CLI exits with code 0, and Boto3 raises no exception. If you treat the call as successful without checking the contents, you will miss the items that were not written. If you need all writes to succeed or all to be rolled back, use transactions (TransactWriteItems) instead of BatchWriteItem.
I reproduced this on the emulator. I created a provisioned table Slow3 with a write capacity of 1, then sent 25 items of about 20KB each in big.json with the AWS CLI. Ten items came back in UnprocessedItems. The exit code was still 0.
$ aws dynamodb batch-write-item --request-items file://big.json --query "length(UnprocessedItems.Slow3)"; echo "終了コード: $?"
10
終了コード: 0
You have to resend the returned items yourself. The script below sends the same 25 items to a table Slow with the same settings. It resends only the remaining items until UnprocessedItems is empty.
import sys
import time
import boto3
client = boto3.client("dynamodb")
table = sys.argv[1]
def batch_write_all(request_items, max_attempts=10):
for attempt in range(1, max_attempts + 1):
resp = client.batch_write_item(RequestItems=request_items)
left = resp["UnprocessedItems"]
n = sum(len(v) for v in left.values())
print(f"{attempt}回目: 残り {n} 件")
if not left:
return
request_items = left # resend only the items that were not written
time.sleep(min(0.05 * 2 ** attempt, 2)) # gradually increase the wait
raise RuntimeError("書き込めなかった項目が残っています")
data = "x" * 20_000 # about 20KB per item
items = [{"PutRequest": {"Item": {"id": {"S": f"big-{i:02d}"}, "data": {"S": data}}}}
for i in range(25)]
batch_write_all({table: items})
The wait doubles on each resend because the API reference strongly recommends exponential backoff (gradually increasing the wait) when resending. It explains that resending immediately tends to be rejected for exceeding capacity again.
When I ran it, 10 items came back on the first try, and after that only 1 item could be written per call. The script was limited to 10 attempts, so it stopped with an exception while one item was still left (the traceback is shortened).
$ time python3 unprocessed.py Slow
1回目: 残り 10 件
2回目: 残り 9 件
3回目: 残り 8 件
4回目: 残り 7 件
5回目: 残り 6 件
6回目: 残り 5 件
7回目: 残り 4 件
8回目: 残り 3 件
9回目: 残り 2 件
10回目: 残り 1 件
Traceback (most recent call last):
(省略)
RuntimeError: 書き込めなかった項目が残っています
real 0m13.388s
user 0m0.246s
sys 0m0.016s
$ aws dynamodb scan --table-name Slow --select COUNT --query Count
24
The table ended with 24 items. Items that were already written are not rolled back when the script stops. If items are still unwritten after the maximum number of retries, record them (for example, in a log) so you can write them again later.
The number of items written per call and the number of calls until completion above are results from the emulator.
With Boto3's batch_writer, splitting and resending are handled for you
In Python, Boto3's batch_writer handles splitting the items into groups of 25 and resending UnprocessedItems. You only call put_item (or delete_item for deletes) inside the with block. To count how many requests were sent, I recorded the item count just before each BatchWriteItem call.
import boto3
table = boto3.resource("dynamodb").Table("Cats")
# Count the number of items in each request sent
sizes = []
def count(params, **kwargs):
sizes.append(sum(len(v) for v in params["RequestItems"].values()))
table.meta.client.meta.events.register("provide-client-params.dynamodb.BatchWriteItem", count)
with table.batch_writer() as batch:
for i in range(60):
batch.put_item(Item={"id": f"kitten-{i:03d}", "age": 0})
print("BatchWriteItem の回数:", len(sizes))
print("1回ごとの件数:", sizes)
The 60 items were sent in 3 calls of 25, 25, and 10, and all 60 were written.
$ python3 batch_writer_demo.py
BatchWriteItem の回数: 3
1回ごとの件数: [25, 25, 10]
$ aws dynamodb scan --table-name Cats --filter-expression "begins_with(id, :p)" --expression-attribute-values "{\":p\":{\"S\":\"kitten-\"}}" --select COUNT --query Count
60
I wrote 25 items of about 20KB each with batch_writer to the table Slow2, which has a write capacity of 1. All 25 were written in 11 BatchWriteItem calls.
$ python3 bw_throttle.py Slow2
0.0秒で終了
BatchWriteItem の回数: 11
1回ごとの件数: [25, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
$ aws dynamodb scan --table-name Slow2 --select COUNT --query Count
25

However, sending all 11 requests took less than 0.1 seconds (shown as 0.0 seconds), so it did not wait between retries. Reading the source of the batch_writer in Boto3 1.44.9, I found that returned items are added to the next batch to send, with no wait (there is a comment saying Any unprocessed_items are immediately added to the next batch we send.).
$ grep -n -A12 "def _flush(self)" .venv/lib/python3.11/site-packages/boto3/dynamodb/table.py
141: def _flush(self):
142- items_to_send = self._items_buffer[: self._flush_amount]
143- self._items_buffer = self._items_buffer[self._flush_amount :]
144- response = self._client.batch_write_item(
145- RequestItems={self._table_name: items_to_send}
146- )
147- unprocessed_items = response['UnprocessedItems']
148- if not unprocessed_items:
149- unprocessed_items = {}
150- item_list = unprocessed_items.get(self._table_name, [])
151- # Any unprocessed_items are immediately added to the
152- # next batch we send.
153- self._items_buffer.extend(item_list)
On the emulator, even though it resent without waiting, one item was written on each call, so it finished quickly.
When batch_writer writes the same key twice
batch_writer also sends BatchWriteItem internally, so a duplicate key within one call is rejected. If you pass primary key attribute names to overwrite_by_pkeys, then when the buffered items contain the same key, only the item added last is kept (based on the explanation in the Boto3 guide).
import boto3
table = boto3.resource("dynamodb").Table("Cats")
try:
with table.batch_writer() as batch:
batch.put_item(Item={"id": "pochi", "age": 1})
batch.put_item(Item={"id": "pochi", "age": 2})
except Exception as e:
print(type(e).__name__, e)
with table.batch_writer(overwrite_by_pkeys=["id"]) as batch:
batch.put_item(Item={"id": "pochi", "age": 1})
batch.put_item(Item={"id": "pochi", "age": 2})
print(table.get_item(Key={"id": "pochi"})["Item"])
$ python3 dup_demo.py
ClientError An error occurred (ValidationException) when calling the BatchWriteItem operation: Provided list of item keys contains duplicates
{'age': Decimal('2'), 'id': 'pochi'}
Without overwrite_by_pkeys, you get a ValidationException. With it, the item with age 2, which was added last, remains. For a table with a sort key, pass both attribute names, like overwrite_by_pkeys=["partition_key", "sort_key"].





