Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Double chunk DDB batch writes to not overwhelm DDB on load #293

Merged
merged 4 commits into from
Oct 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ AWS link: https://d1gwt3w78t4dm3.cloudfront.net

Vercel link: https://open-next.vercel.app

## Configuration

### Environment variables

- DYNAMO_BATCH_WRITE_COMMAND_CONCURRENCY: The number of concurrent batch write commands to DynamoDB. Defaults to 4 in an effort to leave plenty of DynamoDB write request capacity for the production load.

## Contribute

To run `OpenNext` locally:
Expand Down
12 changes: 3 additions & 9 deletions packages/open-next/src/adapters/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
} from "@aws-sdk/client-s3";
import path from "path";

import { MAX_DYNAMO_BATCH_WRITE_ITEM_COUNT } from "./constants.js";
import { debug, error } from "./logger.js";
import { chunk } from "./util.js";

interface CachedFetchValue {
kind: "FETCH";
Expand Down Expand Up @@ -160,7 +162,7 @@
}
}

async getIncrementalCache(

Check warning on line 165 in packages/open-next/src/adapters/cache.ts

View workflow job for this annotation

GitHub Actions / validate

Refactor this function to reduce its Cognitive Complexity from 24 to the 20 allowed
key: string,
keys: string[],
): Promise<CacheHandlerValue | null> {
Expand Down Expand Up @@ -420,7 +422,7 @@
try {
if (disableDynamoDBCache) return;
await Promise.all(
this.chunkArray(req, 25).map((Items) => {
chunk(req, MAX_DYNAMO_BATCH_WRITE_ITEM_COUNT).map((Items) => {
return this.dynamoClient.send(
new BatchWriteItemCommand({
RequestItems: {
Expand Down Expand Up @@ -455,14 +457,6 @@
};
}

private chunkArray<T>(array: T[], chunkSize: number) {
const chunks = [];
for (let i = 0; i < array.length; i += chunkSize) {
chunks.push(array.slice(i, i + chunkSize));
}
return chunks;
}

// S3 handling

private buildS3Key(key: string, extension: Extension) {
Expand Down
25 changes: 25 additions & 0 deletions packages/open-next/src/adapters/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export const MAX_DYNAMO_BATCH_WRITE_ITEM_COUNT = 25;

/**
* Sending to dynamo X commands at a time, using about X * 25 write units per batch to not overwhelm DDB
* and give production plenty of room to work with. With DDB Response times, you can expect about 10 batches per second.
*/
const DEFAULT_DYNAMO_BATCH_WRITE_COMMAND_CONCURRENCY = 4;

export const getDynamoBatchWriteCommandConcurrency = (): number => {
const dynamoBatchWriteCommandConcurrencyFromEnv =
process.env.DYNAMO_BATCH_WRITE_COMMAND_CONCURRENCY;
const parsedDynamoBatchWriteCommandConcurrencyFromEnv =
dynamoBatchWriteCommandConcurrencyFromEnv
? parseInt(dynamoBatchWriteCommandConcurrencyFromEnv)
: undefined;

if (
parsedDynamoBatchWriteCommandConcurrencyFromEnv &&
!isNaN(parsedDynamoBatchWriteCommandConcurrencyFromEnv)
) {
return parsedDynamoBatchWriteCommandConcurrencyFromEnv;
}

return DEFAULT_DYNAMO_BATCH_WRITE_COMMAND_CONCURRENCY;
};
45 changes: 29 additions & 16 deletions packages/open-next/src/adapters/dynamo-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@ import {
import { CdkCustomResourceEvent, CdkCustomResourceResponse } from "aws-lambda";
import { readFileSync } from "fs";

const client = new DynamoDBClient({});
import {
getDynamoBatchWriteCommandConcurrency,
MAX_DYNAMO_BATCH_WRITE_ITEM_COUNT,
} from "./constants.js";
import { chunk } from "./util.js";

const PHYSICAL_RESOURCE_ID = "dynamodb-cache";

const dynamoClient = new DynamoDBClient({});

type DataType = {
tag: {
Expand All @@ -32,44 +40,49 @@ export async function handler(
}

async function insert(): Promise<CdkCustomResourceResponse> {
const tableName = process.env.CACHE_DYNAMO_TABLE!;

const file = readFileSync(`dynamodb-cache.json`, "utf8");

const data: DataType[] = JSON.parse(file);

// Chunk array into batches of 25
const chunked = data.reduce((acc, curr, i) => {
const index = Math.floor(i / 25);
acc[index] = [...(acc[index] || []), curr];
return acc;
}, [] as DataType[][]);
const dataChunks = chunk(data, MAX_DYNAMO_BATCH_WRITE_ITEM_COUNT);

const TableName = process.env.CACHE_DYNAMO_TABLE!;

const promises = chunked.map((chunk) => {
const params = {
const batchWriteParamsArray = dataChunks.map((chunk) => {
return {
RequestItems: {
[TableName]: chunk.map((item) => ({
[tableName]: chunk.map((item) => ({
PutRequest: {
Item: item,
},
})),
},
};
return client.send(new BatchWriteItemCommand(params));
});

await Promise.all(promises);
const paramsChunks = chunk(
batchWriteParamsArray,
getDynamoBatchWriteCommandConcurrency(),
);

for (const paramsChunk of paramsChunks) {
await Promise.all(
paramsChunk.map((params) =>
dynamoClient.send(new BatchWriteItemCommand(params)),
),
);
}

return {
PhysicalResourceId: "dynamodb-cache",
PhysicalResourceId: PHYSICAL_RESOURCE_ID,
Data: {},
};
}

async function remove(): Promise<CdkCustomResourceResponse> {
// Do we want to actually delete anything here?
return {
PhysicalResourceId: "dynamodb-cache",
PhysicalResourceId: PHYSICAL_RESOURCE_ID,
Data: {},
};
}
16 changes: 16 additions & 0 deletions packages/open-next/src/adapters/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,19 @@ export function parseCookies(

return cookies;
}

/**
* Create an array of arrays of size `chunkSize` from `items`
* @param items Array of T
* @param chunkSize size of each chunk
* @returns T[][]
*/
export function chunk<T>(items: T[], chunkSize: number): T[][] {
const chunked = items.reduce((acc, curr, i) => {
const chunkIndex = Math.floor(i / chunkSize);
acc[chunkIndex] = [...(acc[chunkIndex] ?? []), curr];
return acc;
}, new Array<T[]>());

return chunked;
}
Loading