Sub topic 20
Best practices and common pitfalls
This chapter collects the habits that keep CDK projects safe to change and cheap to maintain. It also covers the mistakes that cause most production surprises. It assumes you can already define stacks and constructs, run cdk synth, cdk diff and cdk deploy, and read a basic assertion test. Examples are in TypeScript. The Python versions differ only in naming (snake_case).
Treat the synthesized template as the real output
The CDK is a generator. What AWS runs is the CloudFormation template in cdk.out. Most pitfalls come from forgetting this, so build the habit of checking the template.
- Run
cdk diffbefore every deploy and read it. Look for lines marked as replacement, and for IAM statements you did not expect. - Commit your lock file (
package-lock.jsonor your Python requirements pin) so every machine and pipeline resolves the sameaws-cdk-libversion. - Keep the CLI version and the
aws-cdk-libversion compatible. A CLI older than the library fails with a cloud assembly schema error.
Protect stateful resources
Databases, buckets and tables hold data that code cannot recreate. Two settings matter most.
- Set an explicit
removalPolicyon every stateful resource. Many L2 constructs default toRETAIN, but some default toDESTROYor snapshot behavior. Do not rely on memory. - Turn on termination protection for production stacks, so
cdk destroyand console deletion both refuse to remove them.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
export class DataStack extends cdk.Stack {
public readonly table: dynamodb.Table;
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, {
...props,
terminationProtection: true,
});
this.table = new dynamodb.Table(this, 'Orders', {
partitionKey: { name: 'orderId', type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
pointInTimeRecovery: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
}
}Retained resources are not free of consequences. After cdk destroy, the retained table stays in your account and keeps its name, so redeploying the same stack can fail with a name conflict.
Avoid accidental replacement
Changing a construct's logical ID makes CloudFormation create a new resource and delete the old one. The logical ID derives from the construct's path in the tree, so these changes trigger replacement:
- Renaming the
idstring of a construct. - Moving a construct into a different parent construct.
- Wrapping existing resources in a new custom construct.
For stateful resources this means data loss. Keep IDs stable. If you must refactor, check cdk diff for the resource and use overrideLogicalId on the underlying L1 resource to preserve the old ID.
const cfnBucket = bucket.node.defaultChild as s3.CfnBucket;
cfnBucket.overrideLogicalId('UploadsBucket1234ABCD');Hard-coded physical names cause a related problem. If you set bucketName or tableName, a change that needs replacement fails because the new resource cannot have the same name as the old one. Let the CDK generate names and pass them as values (bucket.bucketName) instead.
Prefer constructs and grants over raw IAM
- Use
grantRead,grantReadWriteand similar methods. They produce least-privilege statements scoped to the exact resource, including KMS permissions when the resource is encrypted. - Avoid
PolicyStatementwithresources: ['*']unless the API requires it. - When you need a custom statement, scope
actionsandresourcesas narrowly as the service allows.
Keep values and tokens straight
A token is a placeholder for a value known only at deploy time, such as bucket.bucketName. Common mistakes:
- Using a token in an
ifstatement or string operation at synthesis time.if (bucket.bucketName === 'x')is never meaningful, and slicing or parsing the string yields garbage. Usecdk.Fnfunctions,CfnCondition, or decide using configuration known at synth time. - Using a token as a map key or in a resource ID. These need concrete values.
- Looking up resources with
fromLookupand expecting it to work without a concreteenv. Lookups need an explicit account and region, and they write results tocdk.context.json. Commit that file so synthesis is repeatable.
Organize stacks by lifecycle
Split stacks by how often and how dangerously they change, not by service name. A common layout is a stateful stack (tables, buckets, databases) and a stateless stack (functions, APIs) that depends on it.
| Concern | Practice | Pitfall it avoids |
|---|---|---|
| Cross-stack references | Pass construct properties between stacks in the same app | Hand-typed export names that drift |
| Stack size | Keep each stack well under the 500-resource CloudFormation limit | Failed deploys that need a refactor |
| Dependencies | Avoid circular references between stacks | Synthesis errors about cyclic dependencies |
| Exports | Do not remove a value another stack imports | `Cannot delete export` errors during deploy |
Cross-stack exports lock the producing stack. To change an exported value, first deploy the consumer without the reference, then change the producer.
Configure per environment without branching on tokens
- Pass settings as props or read them from context (
cdk.jsonor--context), and keep one stack class for all environments. - Give every stack an explicit
envfor production. Environment-agnostic stacks cannot use lookups or some features such as region-dependent availability zones. - Do not read secrets into code. Reference Secrets Manager or SSM Parameter Store, and let the service resolve them at deploy or run time.
Test and enforce rules
- Write assertion tests for the properties you must never lose: encryption, public access blocking, removal policies, and resource counts.
- Use tags and aspects to apply organization-wide rules, such as adding a cost-center tag or failing synthesis when a bucket allows public access.
- Add a snapshot test only for small, stable constructs. Snapshots of whole stacks change on every library upgrade and teach people to approve diffs without reading them.
Operational pitfalls
- Re-run
cdk bootstrapwhen upgrading to a CDK version that needs a newer bootstrap stack. The error message names the required version. - Do not edit CDK-managed resources in the console. The next deploy overwrites the change, or fails on drift.
- Do not deploy from a laptop to production. Use CDK Pipelines or another CI system with a narrowly scoped role.
- Delete unused assets and old bootstrap bucket versions with lifecycle rules, since each deploy of changed code uploads a new asset.
Exercise
You wrap an existing s3.Bucket named 'UploadsBucket' inside a new custom construct called 'Storage' to tidy your code. The bucket has no explicit bucketName. What does cdk diff show, what is the risk, and how do you avoid it?
Show answer
The diff shows the old bucket resource removed and a new bucket resource added, because the logical ID changes with the construct path (it now includes 'Storage'). With a RETAIN policy the old bucket stays orphaned but the new one is empty, and with DESTROY the data is deleted. Avoid it by keeping the original logical ID with overrideLogicalId on the underlying CfnBucket, or by not moving the resource. Confirm with cdk diff that no replacement remains before deploying.
Exercise
A stack reads if (bucket.bucketName.startsWith('prod')) to choose a setting. Why is this wrong, and what should you use instead?
Show answer
bucket.bucketName is a token at synthesis time, a placeholder string, not the real name, so the comparison does not reflect the deployed value. Decide using a value known at synth time, such as a prop or context value for the environment name. If the decision must depend on a deploy-time value, use a CloudFormation condition or cdk.Fn functions.