Node.js(AWS SDK v3)에서의 DynamoDB BatchWriteItem
BatchWriteItem은 단일 요청에서 최대 25개 항목을 put하거나 delete합니다(총 16 MB, 항목당 400 KB). AWS SDK v3에서는 RequestItems가 PutRequest와 DeleteRequest 항목을 섞는 BatchWriteItemCommand를 보내며, 배치 전체는 원자적이지 않으므로 UnprocessedItems를 반드시 반복 처리해야 합니다.
Code
import {BatchWriteItemCommand, DynamoDBClient} from '@aws-sdk/client-dynamodb';
const client = new DynamoDBClient({region: 'us-east-1'});
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let requestItems = {
Music: [
{
PutRequest: {
Item: {
Artist: {S: 'Arturo Sandoval'},
SongTitle: {S: 'Cubano Chant'},
AlbumTitle: {S: 'Danzon'},
Year: {N: '1994'}
}
}
},
{
PutRequest: {
Item: {
Artist: {S: 'Arturo Sandoval'},
SongTitle: {S: 'A Mis Abuelos'},
AlbumTitle: {S: 'Danzon'},
Year: {N: '1994'}
}
}
},
{
DeleteRequest: {
Key: {Artist: {S: 'Ella Fitzgerald'}, SongTitle: {S: 'Misty'}}
}
}
]
};
let attempt = 0;
do {
const response = await client.send(new BatchWriteItemCommand({RequestItems: requestItems}));
// Writes that were throttled come back in UnprocessedItems — resubmit them
// with exponential backoff until the map is empty.
requestItems = response.UnprocessedItems;
if (requestItems && Object.keys(requestItems).length > 0) {
attempt += 1;
await sleep(Math.min(100 * 2 ** attempt, 5000));
}
} while (requestItems && Object.keys(requestItems).length > 0);
console.log('Batch written');Explanation
RequestItems— 테이블 이름 → 최대 25개의PutRequest/DeleteRequest항목 배열의 맵입니다(하나의 요청이 여러 테이블에 걸칠 수 있습니다). 각PutRequest.Item은 전체 기본 키가 필요하며, 각DeleteRequest.Key는 키만 필요합니다.- 트랜잭션이 아님 — 각 put/delete는 개별적으로 원자적이지만, 배치 전체는 그렇지 않습니다: 일부 쓰기는 성공하고 다른 쓰기는 스로틀될 수 있습니다. 전부 아니면 전무가 필요한가요? TransactWriteItems를 사용하세요.
UnprocessedItems— 재시도 루프는 선택 사항이 아닙니다. 스로틀된 쓰기가 여기에RequestItems형태로 반환되어 재제출할 준비가 됩니다. AWS는 시도 사이에 지수 백오프를 강력히 권장합니다.- 업데이트 없음, 조건 없음 —
BatchWriteItem은UpdateItem,ConditionExpression,ReturnValues를 표현할 수 없습니다. 기존 키에 대한 put은 항목 전체를 조용히 교체합니다. 중복 키, 동일 항목에 대한 put+delete 혼합, 25개 초과 요청, 400 KB 초과 항목, 또는 총 16 MB 초과는 각각 DynamoDB가 배치 전체를 거부하게 만듭니다. - 배치는 왕복을 절약하지만 용량은 아닙니다: 모든 put/delete는 개별적으로 청구될 WCU와 동일하게 청구됩니다(존재하지 않는 항목에 대한 delete도 여전히 1 WCU를 청구합니다).
Do it visually
DynamoDB JSON 항목을 손으로 조립하고 싶지 않으신가요? DynamoDB Expression Builder는 타입 지정 값 맵을 만들고 실행 가능한 코드를 복사해 주며, 항목 크기 계산기는 보내기 전에 각 항목을 400 KB 상한에 대해 확인합니다.
GUI에서 항목을 대량으로 추가, 편집, 삭제하려면 — 작성할 재시도 루프 없이 — DynoTable을 다운로드하세요.
Related examples
- DynamoDB batch write in Python — boto3의
batch_writer()가 재시도 루프를 대신 처리합니다. - DynamoDB BatchWriteItem with the AWS CLI — 셸에서 실행하는 동일한 배치 쓰기.
- DynamoDB TransactWriteItems in Node.js — 쓰기가 함께 성공하거나 함께 실패해야 할 때.
- Batch operations in DynamoDB — 한도, 부분 실패, 그리고 배치가 이득이 되는 경우.
- "Too many items requested for the BatchWriteItem call" — 하나의 배치에 25개를 초과하는 put/delete 요청.
- "Provided list of item keys contains duplicates" — 하나의 배치에서 동일한 키를 건드리는 두 개의 요청.
References
- BatchWriteItem — Amazon DynamoDB API Reference
- Error handling with DynamoDB — Amazon DynamoDB Developer Guide
- DynamoDB read and write operations (capacity unit consumption) — Amazon DynamoDB Developer Guide
Last verified 2026-07-13 against the official AWS documentation linked above.