DynamoDBの制限を実際に検証してみた

2025.12.03
DynamoDBの制限を実際に検証してみた
この記事をシェアする

本記事は、クラウドビルダーズ株式会社のアドベントカレンダー2025の3日目の記事となります!!

はじめに

CloudBuildersのhijikuroです。
参画しているプロジェクトでDynamoDBの制限に抵触し対処したので、検証も兼ねて記事にしました。
今回は、DynamoDBの下記の制限項目について実際に検証を行い、各制限に抵触するとどのような挙動になるのかを確認してみました。

検証した制限項目

今回検証した制限は以下の5つです。

  • 1レコード400KBの制限
  • 結果整合性の制限
  • Query/Scanで取得できるデータの1MB制限
  • ホットパーティションによるスロットル
  • RCU/WCU不足によるスロットル

検証環境

検証には以下の環境を使用しました。

  • リージョン: ap-northeast-1(東京)
  • テーブル名: LimitTestTable
  • プロビジョニングモード: RCU 5、WCU 5
  • 実行環境: Node.js v22、AWS SDK v3

各制限の検証結果

1レコード400KBの制限

DynamoDBでは、1つのアイテム(レコード)のサイズが最大400KBまでに制限されています。この制限を超えるとどうなるか検証しました。

検証内容:

  • 390KBのアイテムを挿入(成功するはず)
  • 410KBのアイテムを挿入(失敗するはず)
  • 399KBのアイテムを挿入(成功するはず)

検証コード(抜粋):

// 410KBのアイテムを作成して挿入を試みる
const item410KB = {
  id: "test-410kb",
  data: generateString(410 * 1024), // 410KB
  timestamp: new Date().toISOString()
};

const putCommand = new PutCommand({
  TableName: TABLE_NAME,
  Item: item410KB
});

await docClient.send(putCommand);
全コードを表示
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";

const TABLE_NAME = "LimitTestTable";
const REGION = "ap-northeast-1";

// DynamoDBクライアントの初期化
const client = new DynamoDBClient({ region: REGION });
const docClient = DynamoDBDocumentClient.from(client);

console.log("=== DynamoDB 400KB制限検証 ===\n");

// データサイズを計算する関数
function calculateSize(obj) {
  return new Blob([JSON.stringify(obj)]).size;
}

// 指定サイズの文字列を生成する関数
function generateString(sizeInBytes) {
  // 1文字あたり約1バイトと仮定
  return "A".repeat(sizeInBytes);
}

async function test400KBLimit() {
  try {
    // テスト1: 400KB以下のアイテムを挿入(成功するはず)
    console.log("テスト1: 390KBのアイテムを挿入");
    const item390KB = {
      id: "test-390kb",
      data: generateString(390 * 1024), // 390KB
      timestamp: new Date().toISOString()
    };
    
    const size390KB = calculateSize(item390KB);
    console.log(`アイテムサイズ: ${(size390KB / 1024).toFixed(2)} KB`);
    
    const putCommand1 = new PutCommand({
      TableName: TABLE_NAME,
      Item: item390KB
    });
    
    await docClient.send(putCommand1);
    console.log("✓ 390KBのアイテム挿入成功\n");
    
    // テスト2: 400KB超のアイテムを挿入(失敗するはず)
    console.log("テスト2: 410KBのアイテムを挿入");
    const item410KB = {
      id: "test-410kb",
      data: generateString(410 * 1024), // 410KB
      timestamp: new Date().toISOString()
    };
    
    const size410KB = calculateSize(item410KB);
    console.log(`アイテムサイズ: ${(size410KB / 1024).toFixed(2)} KB`);
    
    const putCommand2 = new PutCommand({
      TableName: TABLE_NAME,
      Item: item410KB
    });
    
    try {
      await docClient.send(putCommand2);
      console.log("✗ 410KBのアイテムが挿入されました(予期しない結果)\n");
    } catch (error) {
      if (error.name === "ValidationException") {
        console.log("✓ エラーが発生しました(期待通り)");
        console.log(`エラー名: ${error.name}`);
        console.log(`エラーメッセージ: ${error.message}\n`);
      } else {
        throw error;
      }
    }
    
    // テスト3: ちょうど400KB付近のアイテムを挿入
    console.log("テスト3: 399KBのアイテムを挿入");
    const item399KB = {
      id: "test-399kb",
      data: generateString(399 * 1024), // 399KB
      timestamp: new Date().toISOString()
    };
    
    const size399KB = calculateSize(item399KB);
    console.log(`アイテムサイズ: ${(size399KB / 1024).toFixed(2)} KB`);
    
    const putCommand3 = new PutCommand({
      TableName: TABLE_NAME,
      Item: item399KB
    });
    
    await docClient.send(putCommand3);
    console.log("✓ 399KBのアイテム挿入成功\n");
    
    console.log("=== 検証完了 ===");
    console.log("結論: DynamoDBは1アイテムあたり400KB(厳密には約400KB)の制限があります。");
    console.log("この制限を超えるとValidationExceptionエラーが発生します。");
    
  } catch (error) {
    console.error("予期しないエラーが発生しました:", error);
    throw error;
  }
}

// 検証実行
test400KBLimit()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error("検証失敗:", error);
    process.exit(1);
  });

結果:

400KBを超えるアイテムを挿入しようとすると、ValidationExceptionエラーが発生しました。エラーメッセージは以下の通りです。

ValidationException: Item size has exceeded the maximum allowed size

390KBと399KBのアイテムは正常に挿入できました。この制限は厳格で、属性名やその他のメタデータを含めた合計サイズが400KBを超えると挿入できません。

結果整合性の制限

DynamoDBはデフォルトで結果整合性(Eventually Consistent)の読み取りを行います。これは、書き込み直後の読み取りで最新のデータが返されない可能性があることを意味します。

検証内容:

  • データを書き込み直後に結果整合性読み取りを実行
  • 高速な更新と読み取りを繰り返して不整合を検出
  • 強い整合性読み取り(ConsistentRead=true)との比較

検証コード(抜粋):

// データを更新
await docClient.send(new PutCommand({
  TableName: TABLE_NAME,
  Item: { id: testId, value: newValue, timestamp: new Date().toISOString() }
}));

// 即座に結果整合性読み取り
const eventualRead = await docClient.send(new GetCommand({
  TableName: TABLE_NAME,
  Key: { id: testId },
  ConsistentRead: false // 結果整合性読み取り
}));

// 強い整合性読み取り
const strongRead = await docClient.send(new GetCommand({
  TableName: TABLE_NAME,
  Key: { id: testId },
  ConsistentRead: true // 強い整合性読み取り
}));
全コードを表示
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, GetCommand } from "@aws-sdk/lib-dynamodb";

const TABLE_NAME = "LimitTestTable";
const REGION = "ap-northeast-1";

const client = new DynamoDBClient({ region: REGION });
const docClient = DynamoDBDocumentClient.from(client);

console.log("=== DynamoDB 結果整合性検証 ===\n");

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function testEventualConsistency() {
  try {
    const testId = "consistency-test-1";
    
    // テスト1: 書き込み直後に結果整合性読み取り
    await docClient.send(new PutCommand({
      TableName: TABLE_NAME,
      Item: {
        id: testId,
        value: "初期値",
        version: 1,
        timestamp: new Date().toISOString()
      }
    }));
    
    // テスト2: 高速な更新と読み取りを繰り返す
    let inconsistencyDetected = 0;
    const iterations = 10;
    
    for (let i = 1; i <= iterations; i++) {
      const newValue = `更新値-${i}`;
      
      await docClient.send(new PutCommand({
        TableName: TABLE_NAME,
        Item: {
          id: testId,
          value: newValue,
          version: i + 1,
          timestamp: new Date().toISOString()
        }
      }));
      
      const eventualRead = await docClient.send(new GetCommand({
        TableName: TABLE_NAME,
        Key: { id: testId },
        ConsistentRead: false
      }));
      
      if (eventualRead.Item?.value !== newValue) {
        inconsistencyDetected++;
      }
    }
    
    // テスト3: 強い整合性読み取りとの比較
    const finalValue = "最終値";
    await docClient.send(new PutCommand({
      TableName: TABLE_NAME,
      Item: {
        id: testId,
        value: finalValue,
        version: 100,
        timestamp: new Date().toISOString()
      }
    }));
    
    const eventualRead = await docClient.send(new GetCommand({
      TableName: TABLE_NAME,
      Key: { id: testId },
      ConsistentRead: false
    }));
    
    const strongRead = await docClient.send(new GetCommand({
      TableName: TABLE_NAME,
      Key: { id: testId },
      ConsistentRead: true
    }));
    
    console.log(`結果整合性読み取り: ${eventualRead.Item?.value}`);
    console.log(`強い整合性読み取り: ${strongRead.Item?.value}`);
    
  } catch (error) {
    console.error("予期しないエラーが発生しました:", error);
    throw error;
  }
}

testEventualConsistency()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error("検証失敗:", error);
    process.exit(1);
  });

結果:

書き込み直後の結果整合性読み取りでは、まれに古い値が返されることがありました。特に高速に更新と読み取りを繰り返した場合、不整合が発生する可能性が高まります。一方、ConsistentRead: trueを指定した強い整合性読み取りでは、常に最新の値が返されました。

東京リージョンでの検証では、ほとんどの場合で結果整合性読み取りでも最新の値が返されましたが、数パーセントの確率で古い値が返される場合がありました。

Query/Scanの1MB制限

DynamoDBのQuery/Scan操作では、1回の呼び出しで最大1MBのデータまで取得できます。それを超えるデータがある場合は、ページネーションを使用する必要があります。

検証内容:

  • 約50KBのアイテムを30個作成(合計約1.5MB)
  • Queryで全データを取得し、ページネーションの発生を確認

検証コード(抜粋):

let hasMore = true;
let pageCount = 0;
let lastEvaluatedKey = undefined;

while (hasMore) {
  pageCount++;
  
  const command = new QueryCommand({
    TableName: TABLE_NAME,
    IndexName: "gsi-index",
    KeyConditionExpression: "gsi_pk = :pk",
    ExpressionAttributeValues: {
      ":pk": "1mb-test-partition"
    },
    ExclusiveStartKey: lastEvaluatedKey
  });
  
  const result = await docClient.send(command);
  
  if (result.LastEvaluatedKey) {
    lastEvaluatedKey = result.LastEvaluatedKey;
  } else {
    hasMore = false;
  }
}
全コードを表示
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, QueryCommand } from "@aws-sdk/lib-dynamodb";

const TABLE_NAME = "LimitTestTable";
const REGION = "ap-northeast-1";

const client = new DynamoDBClient({ region: REGION });
const docClient = DynamoDBDocumentClient.from(client);

console.log("=== DynamoDB Query/Scan 1MB制限検証 ===\n");

function generateString(sizeInKB) {
  return "A".repeat(sizeInKB * 1024);
}

function calculateSize(obj) {
  return new Blob([JSON.stringify(obj)]).size;
}

async function test1MBLimit() {
  try {
    // 約50KBのアイテムを30個作成
    const promises = [];
    for (let i = 1; i <= 30; i++) {
      promises.push(
        docClient.send(new PutCommand({
          TableName: TABLE_NAME,
          Item: {
            id: `1mb-test-${String(i).padStart(3, '0')}`,
            gsi_pk: "1mb-test-partition",
            data: generateString(49),
            index: i,
            timestamp: new Date().toISOString()
          }
        }))
      );
    }
    await Promise.all(promises);
    
    // Queryで1MB制限を確認
    let hasMore = true;
    let pageCount = 0;
    let totalItems = 0;
    let totalSize = 0;
    let lastEvaluatedKey = undefined;
    
    while (hasMore) {
      pageCount++;
      
      const command = new QueryCommand({
        TableName: TABLE_NAME,
        IndexName: "gsi-index",
        KeyConditionExpression: "gsi_pk = :pk",
        ExpressionAttributeValues: {
          ":pk": "1mb-test-partition"
        },
        ExclusiveStartKey: lastEvaluatedKey
      });
      
      const result = await docClient.send(command);
      const items = result.Items || [];
      
      const pageSize = calculateSize(items);
      totalSize += pageSize;
      totalItems += items.length;
      
      console.log(`ページ ${pageCount}: ${items.length}件, ${(pageSize / 1024).toFixed(2)} KB`);
      
      if (result.LastEvaluatedKey) {
        lastEvaluatedKey = result.LastEvaluatedKey;
      } else {
        hasMore = false;
      }
    }
    
    console.log(`総ページ数: ${pageCount}, 総アイテム数: ${totalItems}`);
    console.log(`総データサイズ: ${(totalSize / 1024 / 1024).toFixed(2)} MB`);
    
  } catch (error) {
    console.error("予期しないエラー:", error);
    throw error;
  }
}

test1MBLimit()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error("検証失敗:", error);
    process.exit(1);
  });

結果:

合計1.5MBのデータをQueryで取得した場合、2ページに分割されました。1ページ目は約1MBのデータを返し、LastEvaluatedKeyが含まれていました。このキーを使用して2ページ目のデータを取得することで、残りのデータを取得できました。

この制限は、大量のデータを扱う際に必ずページネーション処理を実装する必要があることを意味します。

ホットパーティションによるスロットル

DynamoDBは各パーティションに対してスループットを分散します。単一のパーティションキーに大量のアクセスが集中すると、ホットパーティションとなりスロットルが発生する可能性があります。

検証内容:

  • 同一パーティションキーに対して100回の書き込み
  • 同一パーティションキーに対して100回の読み取り
  • 20個の並行リクエストを送信

検証コード(抜粋):

const hotPartitionKey = "hot-partition-test";

// 同一パーティションキーに連続して書き込み
for (let i = 1; i <= 100; i++) {
  await docClient.send(new PutCommand({
    TableName: TABLE_NAME,
    Item: {
      id: hotPartitionKey,
      counter: i,
      data: `データ ${i}`,
      timestamp: new Date().toISOString()
    }
  }));
  await sleep(5);
}
全コードを表示
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, GetCommand } from "@aws-sdk/lib-dynamodb";

const TABLE_NAME = "LimitTestTable";
const REGION = "ap-northeast-1";

const client = new DynamoDBClient({ region: REGION });
const docClient = DynamoDBDocumentClient.from(client);

console.log("=== DynamoDB ホットパーティション検証 ===\n");

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function testHotPartition() {
  try {
    const hotPartitionKey = "hot-partition-test";
    let successCount = 0;
    let throttleCount = 0;
    
    // テスト1: 大量の書き込み
    const writeIterations = 100;
    
    for (let i = 1; i <= writeIterations; i++) {
      try {
        await docClient.send(new PutCommand({
          TableName: TABLE_NAME,
          Item: {
            id: hotPartitionKey,
            counter: i,
            data: `データ ${i}`,
            timestamp: new Date().toISOString()
          }
        }));
        successCount++;
      } catch (error) {
        if (error.name === "ProvisionedThroughputExceededException") {
          throttleCount++;
        } else {
          throw error;
        }
      }
      await sleep(5);
    }
    
    console.log(`書き込み - 成功: ${successCount}回, スロットル: ${throttleCount}回`);
    
    // テスト2: 大量の読み取り
    let readSuccessCount = 0;
    let readThrottleCount = 0;
    const readIterations = 100;
    
    for (let i = 1; i <= readIterations; i++) {
      try {
        await docClient.send(new GetCommand({
          TableName: TABLE_NAME,
          Key: { id: hotPartitionKey }
        }));
        readSuccessCount++;
      } catch (error) {
        if (error.name === "ProvisionedThroughputExceededException") {
          readThrottleCount++;
        } else {
          throw error;
        }
      }
      await sleep(5);
    }
    
    console.log(`読み取り - 成功: ${readSuccessCount}回, スロットル: ${readThrottleCount}回`);
    
    const totalSuccess = successCount + readSuccessCount;
    const totalThrottle = throttleCount + readThrottleCount;
    
    console.log(`\n総計 - 成功: ${totalSuccess}回, スロットル: ${totalThrottle}回`);
    
  } catch (error) {
    console.error("予期しないエラー:", error);
    throw error;
  }
}

testHotPartition()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error("検証失敗:", error);
    process.exit(1);
  });

結果:

単一のパーティションキーに短時間で大量のアクセスを集中させると、テーブル全体のWCU/RCUに余裕があってもProvisionedThroughputExceededExceptionが発生する場合がありました。これは、DynamoDBが各パーティションに対してスループットを分散しているためです。

ホットパーティションを避けるためには、パーティションキーの設計を工夫し、アクセスを複数のパーティションに分散させる必要があります。

RCU/WCU不足によるスロットル

プロビジョニングモードのテーブルでは、設定されたRCU/WCUを超えるリクエストを送信するとスロットルが発生します。

検証内容:

  • WCU 5のテーブルに対して、約10KB(10 WCU相当)のアイテムを50回書き込み
  • RCU 5のテーブルに対して、50回の強い整合性読み取りを実行
  • Scan操作による大量RCU消費

検証コード(抜粋):

// 約10KBのアイテムを書き込み(10 WCU相当)
for (let i = 1; i <= 50; i++) {
  await docClient.send(new PutCommand({
    TableName: TABLE_NAME,
    Item: {
      id: `rcu-wcu-test-write-${i}`,
      data: generateString(9), // 約9KB
      index: i,
      timestamp: new Date().toISOString()
    }
  }));
  await sleep(10);
}
全コードを表示
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, GetCommand, ScanCommand } from "@aws-sdk/lib-dynamodb";

const TABLE_NAME = "LimitTestTable";
const REGION = "ap-northeast-1";

const client = new DynamoDBClient({ region: REGION });
const docClient = DynamoDBDocumentClient.from(client);

console.log("=== DynamoDB RCU/WCU不足によるスロットル検証 ===\n");

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function generateString(sizeInKB) {
  return "A".repeat(sizeInKB * 1024);
}

async function testRCUWCUThrottle() {
  try {
    // テスト1: WCU不足によるスロットル
    let writeSuccessCount = 0;
    let writeThrottleCount = 0;
    const writeIterations = 50;
    
    for (let i = 1; i <= writeIterations; i++) {
      try {
        await docClient.send(new PutCommand({
          TableName: TABLE_NAME,
          Item: {
            id: `rcu-wcu-test-write-${i}`,
            data: generateString(9), // 約9KB
            index: i,
            timestamp: new Date().toISOString()
          }
        }));
        writeSuccessCount++;
      } catch (error) {
        if (error.name === "ProvisionedThroughputExceededException") {
          writeThrottleCount++;
        } else {
          throw error;
        }
      }
      await sleep(10);
    }
    
    console.log(`書き込み - 成功: ${writeSuccessCount}回, スロットル: ${writeThrottleCount}回`);
    
    // テスト2: RCU不足によるスロットル
    await sleep(2000);
    let readSuccessCount = 0;
    let readThrottleCount = 0;
    const readIterations = 50;
    
    for (let i = 1; i <= readIterations; i++) {
      try {
        await docClient.send(new GetCommand({
          TableName: TABLE_NAME,
          Key: { id: `rcu-wcu-test-write-${Math.floor(Math.random() * writeSuccessCount) + 1}` },
          ConsistentRead: true
        }));
        readSuccessCount++;
      } catch (error) {
        if (error.name === "ProvisionedThroughputExceededException") {
          readThrottleCount++;
        } else if (error.name === "ResourceNotFoundException") {
          readSuccessCount++;
        } else {
          throw error;
        }
      }
      await sleep(10);
    }
    
    console.log(`読み取り - 成功: ${readSuccessCount}回, スロットル: ${readThrottleCount}回`);
    
    const totalSuccess = writeSuccessCount + readSuccessCount;
    const totalThrottle = writeThrottleCount + readThrottleCount;
    
    console.log(`\n総計 - 成功: ${totalSuccess}回, スロットル: ${totalThrottle}回`);
    
  } catch (error) {
    console.error("予期しないエラー:", error);
    throw error;
  }
}

testRCUWCUThrottle()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error("検証失敗:", error);
    process.exit(1);
  });

結果:

プロビジョニングされた容量を超えるリクエストを短時間で送信すると、ProvisionedThroughputExceededExceptionエラーが発生しました。

1 WCUは1秒あたり1KBの書き込みに相当するため、5 WCUでは1秒あたり5KBまでしか書き込めません。10KBのアイテムを高頻度で書き込むと、すぐに容量を超えてしまいます。

対策としては、以下が考えられます。

  • オンデマンドモードの使用
  • プロビジョニング容量の増加
  • Exponential backoffを使用したリトライロジックの実装
  • リクエストの分散

まとめ

今回、DynamoDBの6つの主要な制限について実際に検証を行いました。各制限に抵触すると、以下のような挙動となります。

制限項目発生するエラー/挙動
1レコード400KB制限ValidationException
結果整合性古い値が返される可能性
Query/Scan 1MB制限LastEvaluatedKeyによるページネーション
ホットパーティションProvisionedThroughputExceededException
RCU/WCU不足ProvisionedThroughputExceededException

DynamoDBを使用する際は、これらの制限を理解した上で、適切なデータモデリングとエラーハンドリングを実装することが重要です。特にスロットルエラーについては、リトライロジックの実装やオンデマンドモードの検討が必要になります。

この記事をシェアする
著者:hijikuro
AWS歴3年目になりました!Amazon Connect勉強中です!