DevOps

AWS CDK best practices for serverless teams

How to structure AWS CDK apps for serverless: stacks and constructs, per-stage config, testing, safe refactoring, bundling, and pipelines.

  • 3 min read
  • Updated December 2, 2026

AWS CDK lets you define infrastructure in TypeScript with real abstractions, types, and tests. That power cuts both ways: a well-structured CDK app makes a large serverless system easy to change; a tangled one makes every deploy nerve-racking. These are the practices we apply on serverless projects, described in more depth in our AWS CDK and DevOps service.

Structure: apps, stacks, and constructs

  • One CDK app per deployable system, with an explicit entry point (bin/app.ts) that instantiates stacks for a given stage.
  • Stacks by lifecycle and blast radius, not by resource type. Stateful resources (DynamoDB tables, S3 buckets, Cognito user pools) change rarely and must never be replaced by accident; put them in their own stacks, separate from frequently deployed compute.
  • Constructs for reuse. If three services each create a function with the same logging, alarms, and tracing, that is a construct (ObservedFunction), not copy-paste.
  • Pass references, not names. Hand constructs to each other as props (table: ITable) so CDK creates the right cross-stack references and IAM grants.

Configuration per stage

Every environment (dev, staging, prod) should be the same code with different configuration:

  • Keep a typed configuration object per stage — account, region, domain, sizing, removal policies.
  • Select the stage explicitly (cdk deploy --context stage=prod), never by "whatever credentials happen to be active".
  • Retain data in production (RemovalPolicy.RETAIN, deletion protection, point-in-time recovery) and allow clean teardown in development.
  • Avoid environment-dependent if statements spread through constructs; push differences into configuration.

Lambda functions with `NodejsFunction`

For TypeScript functions, NodejsFunction bundles each handler with esbuild:

new NodejsFunction(this, "CreateOrderFunction", {
  entry: join(HANDLERS_DIR, "create-order.ts"),
  runtime: Runtime.NODEJS_22_X,
  architecture: Architecture.ARM_64,
  memorySize: 512,
  timeout: Duration.seconds(10),
  tracing: Tracing.ACTIVE,
  logGroup: new LogGroup(this, "CreateOrderLogs", { retention: RetentionDays.ONE_MONTH }),
  bundling: { minify: true, sourceMap: true, target: "node22" },
});
  • Set memory, timeout, architecture, and tracing explicitly for every function.
  • Create the log group explicitly with retention, so logs never accumulate forever.
  • Keep handler code in its own package or folder with its own tests; the CDK app only references the entry file.
  • Prefer grant* methods (table.grantReadWriteData(fn)) for IAM, and add narrow custom statements only when a grant doesn't exist.

Logical IDs and safe refactoring

CloudFormation identifies resources by logical ID, which CDK derives from the construct path. Renaming a construct or moving it to another parent changes the logical ID, and CloudFormation will delete and recreate the resource. For a table or bucket, that means data loss.

  • Treat construct IDs of stateful resources as permanent.
  • Read every cdk diff before deploying, and look specifically for [-] and replacement markers on stateful resources.
  • When you must move resources between stacks, use cdk refactor or CloudFormation resource import instead of delete-and-recreate.
  • Protect important resources with RemovalPolicy.RETAIN and deletion protection so a mistake can't destroy data.

Testing infrastructure

  • Assertion tests with aws-cdk-lib/assertions check what matters: encryption enabled, public access blocked, log retention set, alarms present, IAM scoped. They run in seconds in CI.
  • Snapshot tests catch unexpected changes but generate noisy diffs; use them sparingly, if at all.
  • Policy checks with cdk-nag or cfn-guard enforce baseline security rules across the whole app.
  • Synth in CI on every pull request, so broken infrastructure never reaches main.

Security defaults

  • Encrypt everything at rest (the default for most services today — assert it in tests).
  • Block public access on buckets, enforce TLS, and avoid wildcards in IAM actions and resources.
  • Keep secrets out of code and context; reference Secrets Manager or SSM Parameter Store.
  • Use Aspects to apply cross-cutting rules (tags, removal policies, compliance checks) to every construct.

Pipelines and deployment

  • Authenticate CI to AWS with OIDC federation, not stored access keys — see cross-account access without long-lived keys.
  • Every pipeline runs lint, typecheck, unit tests, cdk synth, and cdk diff before deploying.
  • Require a human approval before production, and deploy the exact artifact that was reviewed.
  • Bootstrap each account and region once, and deploy with the bootstrap roles rather than broad personal credentials.
  • Use separate AWS accounts per stage; AWS Organizations and IAM Identity Center keep access manageable.

Keep the app fast to work with

  • Commit cdk.context.json so lookups are deterministic.
  • Avoid unnecessary lookups (fromLookup) in hot paths; they need credentials at synth time.
  • Keep the number of stacks reasonable — each one adds deploy time.
  • Upgrade aws-cdk-lib regularly in small steps rather than in painful jumps.

Summary

Organize stacks by lifecycle, configure stages explicitly, define functions and log groups fully, never let a refactor replace stateful resources, test with assertions, and deploy through a pipeline with OIDC and an approval gate. A CDK app built this way stays easy to change long after the first deploy.

Services

Related services

How we can help you put this guide into practice.

Guides

More guides

Keep reading.

Let's make your serverless workload simpler, safer, and cheaper.

Start with a free 30-minute intro call with a serverless engineer.

Book a consultation