
Trying Out AWS CDK Blocks, Now Generally Available (GA)
This page has been translated by machine translation. View original
Introduction
On November 20, 2026, AWS CDK Blocks (called AWS Blocks during the Preview) became generally available (GA).
A Block in CDK Blocks is an npm package that adds connection code for use from an app and a local implementation to a CDK construct.
In this article, I built an app that uses KVStore and AsyncJob, and tried deploying it to AWS and tearing it down.
Test environment
- Runtime environment: Docker (node:22, Linux)
- Node.js: v22.23.3
- npm: 10.9.9
- aws-cdk-blocks: 1.0.1
- @aws-cdk-blocks/core: 1.0.1
- @aws-cdk-blocks/bb-kv-store: 1.0.0
- @aws-cdk-blocks/bb-async-job: 1.0.0
- @aws-cdk-blocks/create-blocks-app: 1.0.1 (template default 0.1.0)
- @aws-cdk-blocks/create-block: 1.0.0
- aws-cdk-lib: 2.278.0
- aws-cdk (CLI): 2.1149.0
- Region: Tokyo (ap-northeast-1)
Running locally
I ran an app with Blocks defined on the local dev server.
Creating the app
npm create @aws-cdk-blocks/blocks-app@latest my-app
cd my-app
npm run dev
When running npm create, an explanation about the collection of usage data was output, along with instructions for opting out: run cdk cli-telemetry --disable or set the environment variable CDK_DISABLE_CLI_TELEMETRY=1.
When the dev server started, the following was displayed.
AWS CDK Blocks local server running on http://localhost:3000
You can look up the API of the Block you want to use from the app directory. npm run docs lists the Blocks, and adding a Block name, as in npm run docs AsyncJob, lets you read the individual guide.
Defining the backend
I defined KVStore, AsyncJob, and ApiNamespace in cdk-blocks/index.ts. In this article I don't use the frontend (src/); instead I call the ApiNamespace functions from scripts/local-check.ts.
import { ApiNamespace, Scope, KVStore, AsyncJob } from 'aws-cdk-blocks';
import { z } from 'zod';
const scope = new Scope('my-app');
// KVStore: a file locally, a DynamoDB table on AWS
const notes = new KVStore(scope, 'notes', {
schema: z.object({ id: z.string(), text: z.string() }),
key: { partitionKey: 'id' },
});
type Payload = { mode: 'ok' | 'fail-twice' | 'always-fail'; noteId: string };
// AsyncJob: an in-process queue locally, SQS + DLQ + Lambda on AWS
const worker = new AsyncJob<Payload>(scope, 'worker', {
maxRetries: 3,
trackStatus: true,
handler: async (payload, ctx) => {
console.log(`[worker] job=${ctx.jobId} mode=${payload.mode} receiveCount=${ctx.receiveCount}`);
if (payload.mode === 'always-fail') {
throw new Error(`always-fail (receiveCount=${ctx.receiveCount})`);
}
if (payload.mode === 'fail-twice' && ctx.receiveCount < 3) {
throw new Error(`fail-twice (receiveCount=${ctx.receiveCount})`);
}
await notes.put({ id: payload.noteId }, { id: payload.noteId, text: `processed by job ${ctx.jobId} on attempt ${ctx.receiveCount}` });
},
});
export const api = new ApiNamespace(scope, 'api', () => ({
async putNote(id: string, text: string) {
await notes.put({ id }, { id, text });
return { ok: true };
},
async getNote(id: string) {
return await notes.get({ id });
},
async submitJob(mode: Payload['mode'], noteId: string) {
return await worker.submit({ mode, noteId });
},
async jobStatus(jobId: string) {
return await worker.getStatus(jobId);
},
}));
I ran the invocation script in a separate terminal while the dev server kept running, specifying a scenario name (kv, ok, fail-twice, always-fail, greeting). I ran greeting after adding a method to api in the "Custom Block" section below.
BLOCKS_API_URL=http://localhost:3000/cdk-blocks/api npx tsx scripts/local-check.ts <シナリオ名>
Full text of scripts/local-check.ts
// Call KVStore and AsyncJob against the local dev server
// Run: BLOCKS_API_URL=http://localhost:3000/cdk-blocks/api npx tsx scripts/local-check.ts <scenario>
import { setTimeout as sleep } from 'node:timers/promises';
import { api } from 'cdk-blocks';
const scenario = process.argv[2] ?? 'kv';
async function waitDone(jobId: string) {
for (let i = 0; i < 40; i++) {
const s = await api.jobStatus(jobId);
if (s && (s.state === 'complete' || s.state === 'failed')) return s;
await sleep(250);
}
return await api.jobStatus(jobId);
}
if (scenario === 'kv') {
console.log('putNote:', JSON.stringify(await api.putNote('n1', 'hello from local')));
console.log('getNote n1:', JSON.stringify(await api.getNote('n1')));
console.log('getNote missing:', JSON.stringify(await api.getNote('missing')));
} else if (scenario === 'greeting') {
console.log('setGreeting:', JSON.stringify(await api.setGreeting('alice', 'Hello Alice')));
console.log('getGreeting alice:', JSON.stringify(await api.getGreeting('alice')));
try {
await api.setGreeting('bob', 'x'.repeat(101));
console.log('over-length: accepted (unexpected)');
} catch (e) {
console.log('over-length rejected:', (e as Error).name, '-', (e as Error).message);
}
} else {
const mode = scenario as 'ok' | 'fail-twice' | 'always-fail';
const noteId = `job-${mode}`;
const { jobId } = await api.submitJob(mode, noteId);
console.log('submitted:', jobId, 'mode=', mode);
const s = await waitDone(jobId);
console.log('status.state:', s?.state, 'attempts:', s?.attempts, 'error:', s?.error);
console.log('transitions:', s?.transitions.map((t) => `${t.state}#${t.attempt}`).join(' -> '));
console.log('note after job:', JSON.stringify(await api.getNote(noteId)));
}
Reading and writing with KVStore
These are the results of the kv scenario.
putNote: {"ok":true}
getNote n1: {"id":"n1","text":"hello from local"}
getNote missing: null
The local KVStore data was saved to .cdk-blocks/local/data/my-app-notes/store.json.
{
"version": 2,
"items": [
{
"id": "n1",
"text": "hello from local"
}
]
}
AsyncJob retries and the DLQ
Results of running locally
With submitJob, I submitted jobs in three modes: succeed (ok), fail twice and then succeed (fail-twice), and always fail (always-fail).
maxRetries is not the number of retries but the total number of deliveries, including the first one. The 3 used here corresponds to the first attempt plus two retries.
| Mode | Final state | attempts | transitions |
|---|---|---|---|
| ok | complete | 1 | queued#0 -> processing#1 -> complete#1 |
| fail-twice | complete | 3 | queued#0 -> processing#1 -> processing#2 -> processing#3 -> complete#3 |
| always-fail | failed | 3 | queued#0 -> processing#1 -> processing#2 -> processing#3 -> failed#3 |
The last handler error was recorded in the always-fail status as error: always-fail (receiveCount=3).
In the dev server log, moved to DLQ was displayed for the always-fail job that failed three times, and the payload was also output.
[AsyncJob:worker] submitted job a4463d7b-5b21
[worker] job=a4463d7b-5b21 mode=always-fail receiveCount=1
[AsyncJob:worker] job a4463d7b-5b21 failed (attempt 1/3): always-fail (receiveCount=1)
[AsyncJob:worker] retrying job a4463d7b-5b21 (attempt 2/3)
[worker] job=a4463d7b-5b21 mode=always-fail receiveCount=2
[AsyncJob:worker] job a4463d7b-5b21 failed (attempt 2/3): always-fail (receiveCount=2)
[AsyncJob:worker] retrying job a4463d7b-5b21 (attempt 3/3)
[worker] job=a4463d7b-5b21 mode=always-fail receiveCount=3
[AsyncJob:worker] job a4463d7b-5b21 moved to DLQ after 3 attempts
[AsyncJob:worker] DLQ payload: {"mode":"always-fail","noteId":"job-always-fail"}
cdk synth output
I checked which resources the same AsyncJob definition becomes with cdk synth.
npx cdk synth -c sandboxMode=true --quiet
The template was output to cdk.out/<スタック名>.template.json. The following table shows the main settings of the SQS queue, DLQ, event source mapping, and status table generated from the AsyncJob.
| Resource | Setting | Value |
|---|---|---|
| Main queue | VisibilityTimeout | 905 |
| Main queue | maxReceiveCount of RedrivePolicy | 3 |
| Main queue | SqsManagedSseEnabled | true |
| DLQ | MessageRetentionPeriod | 1209600 (14 days) |
| event source mapping | BatchSize | 10 |
| event source mapping | MaximumBatchingWindowInSeconds | 5 |
| event source mapping | FunctionResponseTypes | ReportBatchItemFailures |
| worker-status table (when trackStatus: true) | BillingMode | PAY_PER_REQUEST |
Custom Block
I built a Block that incorporates organizational requirements with create-block and used it from the app. The GreetingStore I built here includes the following requirements.
- It wraps a KVStore
- It fixes the table's PITR (point-in-time recovery) to enabled
- It limits the message length to 1–100 characters by default
Generating the scaffold
The create-block README lists the following command.
npm create @aws-cdk-blocks/block@latest <ClassName>
In the environment I tested (Docker node:22, npm 10.9.9), running npm create @aws-cdk-blocks/block@latest -- GreetingStore --dry-run produced no output. Running the package's dist/index.js directly with node displayed the help, so I ran npm install for @aws-cdk-blocks/create-block in a separate directory and ran dist/index.js directly from the app root.
# Run in a directory separate from the app
npm install @aws-cdk-blocks/create-block
# Run at the app root
node <導入先ディレクトリ>/node_modules/@aws-cdk-blocks/create-block/dist/index.js GreetingStore --yes
Because the app uses npm workspaces, create-block ran in customer mode. 15 files were generated in packages/bb-greeting-store, and this package was added to the workspaces in the root package.json. The build and tests (3 tests) right after generation also passed.
Among the generated files, the following four are the entry points for each situation in which they are run.
| File | When it is used |
|---|---|
| index.mock.ts | Local development and tests |
| index.aws.ts | When running as Lambda after deployment |
| index.cdk.ts | When running cdk synth |
| index.browser.ts | When loaded in the browser (stub) |
Implementing the requirements
I wrote the PITR fix in index.cdk.ts, which is used for synth.
packages/bb-greeting-store/src/index.cdk.ts
export class GreetingStore extends Scope {
constructor(scope: ScopeParent, id: string, _options?: GreetingStoreOptions) {
super(id, { parent: scope, bbName: BB_NAME });
new KVStore(this, 'store', { pointInTimeRecovery: true });
}
// ...
}
I wrote the message length check in index.mock.ts, which is used locally.
packages/bb-greeting-store/src/index.mock.ts
export class GreetingStore extends Scope {
private readonly store: KVStore;
private readonly maxLength: number;
constructor(scope: ScopeParent, id: string, options?: GreetingStoreOptions) {
super(id, { parent: scope, bbName: BB_NAME, bbVersion: BB_VERSION });
registerSdkIdentifiers(this.fullId, {});
this.maxLength = options?.maxLength ?? 100;
this.store = new KVStore(this, 'store', { pointInTimeRecovery: true });
}
/** Save a greeting for `name`. Throws `InvalidInputException` when it is empty or too long. */
async setGreeting(name: string, message: string): Promise<void> {
if (message.length === 0 || message.length > this.maxLength) {
throw blocksError(GreetingStoreErrors.InvalidInput, `message must be 1-${this.maxLength} characters`);
}
await this.store.put(name, message);
}
/** Read the greeting for `name`. Returns `null` when none is saved. */
async getGreeting(name: string): Promise<string | null> {
return await this.store.get(name);
}
}
After deployment, index.aws.ts is used in Lambda, so I wrote the same check there as well. The constructor and setGreeting are the same as in index.mock.ts.
GreetingStoreErrors.InvalidInput and the maxLength option are defined in errors.ts and types.ts, respectively.
errors.ts and types.ts
packages/bb-greeting-store/src/errors.ts
/**
* Typed error constants for GreetingStore. Match them in catch blocks with
* `isBlocksError(e, GreetingStoreErrors.Foo)` from `@aws-cdk-blocks/core` — errors
* cross the wire by `name`, so the same guard works server- and client-side.
*/
export const GreetingStoreErrors = {
/** The greeting is empty or longer than `maxLength`. */
InvalidInput: 'InvalidInputException',
} as const;
packages/bb-greeting-store/src/types.ts
/**
* Shared types for GreetingStore. Imported by the mock, aws, cdk, and browser
* entry points. Types only — this file has zero runtime dependencies.
*/
/** Options for constructing a {@link GreetingStore}. */
export interface GreetingStoreOptions {
/** Maximum greeting length. Defaults to 100 characters as an organizational rule. */
maxLength?: number;
}
Using it from the app
The exports in the Block's package.json point to ./dist/*.js, so I built the Block after changing src/.
cd packages/bb-greeting-store && npm run build
In cdk-blocks/index.ts, I imported GreetingStore, created an instance, and added two methods to api.
import { GreetingStore } from '@app/bb-greeting-store';
// ...
// Custom Block (packages/bb-greeting-store)
const greetings = new GreetingStore(scope, 'greetings');
// ...
export const api = new ApiNamespace(scope, 'api', () => ({
// ...
async setGreeting(name: string, message: string) {
await greetings.setGreeting(name, message);
return { ok: true };
},
async getGreeting(name: string) {
return await greetings.getGreeting(name);
},
// ...
}));
These are the results of the greeting scenario.
setGreeting: {"ok":true}
getGreeting alice: "Hello Alice"
over-length rejected: InvalidInputException - InvalidInputException: message must be 1-100 characters
In the synthesized template, only the greetings-store table had PointInTimeRecoveryEnabled set to true.
Verification on AWS
Deploying
Complete bootstrapping in the target account and region beforehand. Bootstrapping is required only once per account and region combination.
I ran the deployment with the following command.
npm run sandbox:deploy
The output was as follows (the API ID is masked).
CloudFormation: applying changes
68 resources applied in 3m 21s
✅ Sandbox deployed!
📡 API URL: https://<api-id>.execute-api.ap-northeast-1.amazonaws.com/prod/cdk-blocks/api
Checking operation
I ran the same script as locally, specifying the AWS API URL in the environment variable BLOCKS_API_URL.
BLOCKS_API_URL=https://<api-id>.execute-api.ap-northeast-1.amazonaws.com/prod/cdk-blocks/api npx tsx scripts/local-check.ts ok
submitted: de2ca1d1-8f0c-4f6c-8aef-73bd95621d82 mode= ok
status.state: complete attempts: 1 error: undefined
transitions: queued#0 -> processing#1 -> complete#1
note after job: {"id":"job-ok","text":"processed by job de2ca1d1-8f0c-4f6c-8aef-73bd95621d82 on attempt 1"}
The kv and greeting scenarios also gave the same results as locally.
I checked the SQS and DynamoDB settings after deployment with read-only AWS CLI commands. I specified the URLs of the main queue and the DLQ for the queue URL, respectively.
aws sqs get-queue-attributes --queue-url <キューの URL> --attribute-names RedrivePolicy VisibilityTimeout MessageRetentionPeriod
aws dynamodb describe-continuous-backups --table-name <テーブル名>
The main queue had a VisibilityTimeout of 905 and a RedrivePolicy maxReceiveCount of 3. The DLQ's MessageRetentionPeriod was 1209600. PITR was ENABLED only on the greetings-store table, and notes and worker-status were DISABLED. All of these matched the synth values.
Tearing down
npm run sandbox:destroy
CloudFormation: removing changes
68 resources removed in 2m 47s
✅ Sandbox destroyed!
After teardown, the stack became DELETE_COMPLETE, but the log groups for two CDK helper Lambda functions remained. The remaining log groups are outside the stack's management, so delete them manually.
/aws/lambda/<スタック名>-CustomCDKBucketDeploymen-<suffix>/aws/lambda/<スタック名>-CustomS3AutoDeleteObject-<suffix>
The sandbox stack could be torn down with a single command.
With the preset used by the production npm run deploy, the deletion policy for tables and buckets is RETAIN.
Summary
AWS Blocks, which was offered as a Public Preview in June 2026, has become GA as AWS CDK Blocks.
I was able to run an app using KVStore and AsyncJob with the same code both locally and on AWS. CDK Blocks has AWS-service-specific best practices built in, such as a retry implementation using a DLQ, so you can use it starting from a backend prototype. Please give it a try as a mechanism to support a rapid application development cycle.
