iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📦

Parallel Scan with Pagination in DynamoDB using ExclusiveStartKey

に公開

I learned about something called DynamoDB Parallel Scan.

It seems like a useful way to speed up batch processing for DynamoDB tables with a large number of items. In particular, I thought it would be valuable for AWS Lambda batches, which have a 15-minute execution limit.

Since I couldn't find many sample codes involving pagination using ExclusiveStartKey, I'd like to share my results along with sample code (Node.js + TypeScript + AWS SDK V3).

Environment

  • M1 Mac
  • node 16.15.0
  • typescript 4.7.4
  • esbuild 0.14.48
  • esbuild-register 3.3.3
  • @aws-sdk/{client-dynamodb,lib-dynamodb} 3.121.0
  • @faker-js/faker 7.3.0

Create DynamoDB Table

Create the following table from the AWS Management Console.

  • Table name: testItems
  • Capacity: On-demand
  • Primary key
    • Partition key: id (Type S)
    • Sort key: None

Insert Test Data

Create a script like the following to insert test data.

save-test-items.ts
import { DynamoDB } from "@aws-sdk/client-dynamodb"
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"
import * as uuid from "uuid"
import { faker } from "@faker-js/faker"

const main = async () => {
  const ddbDoc = DynamoDBDocument.from(
    new DynamoDB({ region: "ap-northeast-1" })
  )

  // Create 100,000 items of data
  for (let i = 0; i < 4000; i++) {
    await ddbDoc.batchWrite({
      RequestItems: {
        testItems: Array.from({ length: 25 }).map(() => ({
          PutRequest: {
            Item: {
              id: uuid.v4(),
              name: faker.name.findName(),
              age: Number(faker.random.numeric(2)),
              content: faker.lorem.sentences(),
              createdAt: faker.date.recent().toISOString(),
              updatedAt: faker.date.recent().toISOString(),
            },
          },
        })),
      },
    })
  }
}

main()

I initially inserted 25 items for a quick verification and then inserted 100,000 items, so there are a total of 100,025 items in the table.

Scanning

Execution and Measurement

We execute using esbuild-register and use /usr/bin/time -l for measurement.

/usr/bin/time -l node -r esbuild-register ./path/to/{FILE_NAME}.ts

Normal Full Table Scan

First, let's try a full table scan sequentially.

scan-test-items.ts
import { DynamoDB } from "@aws-sdk/client-dynamodb"
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"

const main = async () => {
  // Initialize DynamoDB Document Client
  const ddbDoc = DynamoDBDocument.from(
    new DynamoDB({ region: "ap-northeast-1" })
  )

  let exclusiveStartKey: any | null | undefined = null
  let count = 0
  while (exclusiveStartKey !== undefined) {
    const result = await ddbDoc.scan({
      TableName: "testItems",
      ExclusiveStartKey: exclusiveStartKey ?? undefined,
    })
    exclusiveStartKey = result.LastEvaluatedKey
    count += result.Items?.length ?? 0
    console.log({ count })
  }
}

main()

The execution output is as follows.

{ count: 3364 }
{ count: 6697 }
{ count: 10065 }
{ count: 13419 }
{ count: 16767 }
{ count: 20133 }
{ count: 23480 }
{ count: 26829 }
{ count: 30176 }
{ count: 33515 }
{ count: 36882 }
{ count: 40224 }
{ count: 43568 }
{ count: 46914 }
{ count: 50281 }
{ count: 53612 }
{ count: 56949 }
{ count: 60302 }
{ count: 63645 }
{ count: 66990 }
{ count: 70348 }
{ count: 73706 }
{ count: 77036 }
{ count: 80387 }
{ count: 83721 }
{ count: 87075 }
{ count: 90412 }
{ count: 93754 }
{ count: 97097 }
{ count: 100025 }

Items are retrieved in batches of approximately 3,300.

Scanning All Items with 2-way Parallelism

Working with Scans in DynamoDB - Amazon DynamoDB

In the case of a parallel scan, you pass the following to the scan() method:

  • TotalSegments: Specify the number of parallel workers. For example, if you want 4-way parallelism, use 4.
  • Segment: An ID assigned to each parallel worker/segment (as I understand it). For TotalSegments: 4, you would assign 0 to 3.

One thing to note is that ExclusiveStartKey must be managed individually for each segment. Therefore, in the following sample code, I have prepared two ExclusiveStartKey variables for the 2-way parallel scan.

Also, as another point of caution, separate from the while loop's exclusiveStartKey !== undefined check, you need an exclusiveStartKey !== undefined check within each individual scan as well. This is because, depending on the combination of the total number of items and the degree of parallelism, undefined and { id: "{UUID}" } values might coexist in the respective exclusiveStartKey variables during the final stages of the repeated scans. If you pass undefined to ExclusiveStartKey (except for the first time), it might unintentionally trigger a "start scan from the beginning" behavior, potentially leading to an infinite (or nearly infinite) loop. To prevent this, we include an exclusiveStartKey !== undefined check for each scan.

parallel-scan-test-items.ts
import { DynamoDB } from "@aws-sdk/client-dynamodb"
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"

const main = async () => {
  // Initialize DynamoDB Document Client
  const ddbDoc = DynamoDBDocument.from(
    new DynamoDB({ region: "ap-northeast-1" })
  )

  let exclusiveStartKey0: any | null | undefined = null
  let exclusiveStartKey1: any | null | undefined = null
  let count = 0
  while (exclusiveStartKey0 !== undefined || exclusiveStartKey1 !== undefined) {
    const scanResults = await Promise.all([
      exclusiveStartKey0 !== undefined // Do not scan a segment that has already finished
        ? ddbDoc.scan({
            TableName: "testItems",
            ExclusiveStartKey: exclusiveStartKey0 ?? undefined,
            TotalSegments: 2,
            Segment: 0,
          })
        : undefined,
      exclusiveStartKey1 !== undefined // Do not scan a segment that has already finished
        ? ddbDoc.scan({
            TableName: "testItems",
            ExclusiveStartKey: exclusiveStartKey1 ?? undefined,
            TotalSegments: 2,
            Segment: 1,
          })
        : undefined,
    ])
    exclusiveStartKey0 = scanResults[0].LastEvaluatedKey
    exclusiveStartKey1 = scanResults[1].LastEvaluatedKey
    count += scanResults[0].Items?.length ?? 0
    count += scanResults[1].Items?.length ?? 0
    console.log({ count })
  }
}

main()

The execution output is as follows.

{ count: 6697 }
{ count: 13367 }
{ count: 20084 }
{ count: 26784 }
{ count: 33481 }
{ count: 40207 }
{ count: 46904 }
{ count: 53585 }
{ count: 60285 }
{ count: 66955 }
{ count: 73678 }
{ count: 80358 }
{ count: 87043 }
{ count: 93740 }
{ count: 100025 }

Approximately 6,700 items were retrieved in each batch, and you can see that the number of loops has decreased.

Refactoring the Parallel Scan Code (and 10-way Parallel Scan)

In the previous 2-way sample code, as the degree of parallelism increases, you have to manually define more variables to store ExclusiveStartKey and additional scan() calls. This is not only tedious but also increases the risk of bugs due to typos. Therefore, I'd like to refactor it to manage these using an array.

Here it is. This time, I've set it to 10-way parallelism.

parallel-scan-test-items.ts
import { DynamoDB } from "@aws-sdk/client-dynamodb"
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"

const main = async () => {
  // Initialize DynamoDB Document Client
  const ddbDoc = DynamoDBDocument.from(
    new DynamoDB({ region: "ap-northeast-1" })
  )

  // Specify the degree of parallelism
  const parallelsCount = 10

  let exclusiveStartKeys: (any | null | undefined)[] = Array.from(
    {
      length: parallelsCount,
    },
    () => null
  )
  let count = 0
  while (
    exclusiveStartKeys.some(
      (exclusiveStartKey) => exclusiveStartKey !== undefined
    )
  ) {
    const scanResults = await Promise.all(
      exclusiveStartKeys.map(async (exclusiveStartKey, i) => {
        if (exclusiveStartKey === undefined) {
          // Do not scan a segment that has already finished
          return undefined
        }

        return ddbDoc.scan({
          TableName: "testItems",
          ExclusiveStartKey: exclusiveStartKey ?? undefined,
          TotalSegments: parallelsCount,
          Segment: i,
        })
      })
    )
    exclusiveStartKeys = scanResults.map(
      (scanResult) => scanResult?.LastEvaluatedKey
    )
    scanResults.forEach(
      (scanResult) => (count += scanResult?.Items?.length ?? 0)
    )
    console.log({ count })
  }
}

main()

Now you can control the degree of parallelism simply by changing the value of const parallelsCount = 10.

The execution output is as follows.

{ count: 33450 }
{ count: 66935 }
{ count: 99797 }
{ count: 100025 }

Approximately 33,000 items were retrieved in each batch, and all items were retrieved in just 4 loops.

Are there any duplicate items in a parallel scan?

Just to be sure, I will check if there are any duplicates in the retrieval results.

I will collect all retrieved items into a variable and check for any duplicates in the id, which is the primary key.

parallel-scan-test-items.ts
import { DynamoDB } from "@aws-sdk/client-dynamodb"
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"

const main = async () => {
  // Initialize DynamoDB Document Client
  const ddbDoc = DynamoDBDocument.from(
    new DynamoDB({ region: "ap-northeast-1" })
  )

  // Specify the degree of parallelism
  const parallelsCount = 10

  let exclusiveStartKeys: (any | null | undefined)[] = Array.from(
    {
      length: parallelsCount,
    },
    () => null
  )
  let count = 0
+ let items: Record<string, any>[] = []
  while (
    exclusiveStartKeys.some(
      (exclusiveStartKey) => exclusiveStartKey !== undefined
    )
  ) {
    const scanResults = await Promise.all(
      exclusiveStartKeys.map(async (exclusiveStartKey, i) => {
        if (exclusiveStartKey === undefined) {
          // Do not scan a segment that has already finished
          return undefined
        }

        return ddbDoc.scan({
          TableName: "testItems",
          ExclusiveStartKey: exclusiveStartKey ?? undefined,
          TotalSegments: parallelsCount,
          Segment: i,
        })
      })
    )
    exclusiveStartKeys = scanResults.map(
      (scanResult) => scanResult?.LastEvaluatedKey
    )
-   scanResults.forEach(
-     (scanResult) => (count += scanResult?.Items?.length ?? 0)
-   )
+   scanResults.forEach((scanResult) => {
+     count += scanResult?.Items?.length ?? 0
+     items = items.concat(scanResult?.Items ?? [])
+   })
    console.log({ count })
  }
  
+ const ids = items.map((item) => item.id)
+ const uniqueIds = [...new Set(ids)]
+ console.log({ count, idsCount: ids.length, uniqueIdsCount: uniqueIds.length })
}

main()

The execution output is as follows.

{ count: 33450 }
{ count: 66935 }
{ count: 99797 }
{ count: 100025 }
{ count: 100025, idsCount: 100025, uniqueIdsCount: 100025 }

Since count, idsCount, and uniqueIdsCount all match at 100025, it appears there are no duplicates.

Results

The time taken for each case is shown below.

Case Execution Time (seconds)
Normal Scan 107.76s
2-way Parallel Scan 59.89s
10-way Parallel Scan 14.22s

You can see that using parallelism makes it significantly faster.

That's all for now, but if there are any misunderstandings regarding parallel scans, I would appreciate it if you could point them out in the comments section.

References

Discussion