Node.js(AWS SDK v3)에서의 DynamoDB BatchWriteItem

BatchWriteItem은 단일 요청에서 최대 25개 항목을 put하거나 delete합니다(총 16 MB, 항목당 400 KB). AWS SDK v3에서는 RequestItemsPutRequestDeleteRequest 항목을 섞는 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는 시도 사이에 지수 백오프를 강력히 권장합니다.
  • 업데이트 없음, 조건 없음BatchWriteItemUpdateItem, 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을 다운로드하세요.

References

Last verified 2026-07-13 against the official AWS documentation linked above.

Console 없이 DynamoDB 작업하기

DynoTable은 DynamoDB를 위한 빠른 데스크톱 클라이언트입니다 — 테이블을 탐색하고, SQL 스타일 쿼리를 실행하고, 항목을 로컬에서 편집하세요.