Reusable AWS CDK Constructs: Factory Functions, Builders, and Aspects
How factory functions, higher-order functions, and composition turn AWS CDK into a type-safe, reusable infrastructure toolkit that prevents configuration drift.
AWS CDK lets you treat infrastructure as real code. Without shared patterns, though, teams end up with duplicated configurations, inconsistent settings, and deployment failures that a type checker could have caught. Two moves fix most of it: put every recurring resource behind a factory function, and enforce the settings nobody can afford to forget (RemovalPolicy, encryption, log retention) with CDK Aspects. Builders, composers, and custom L3 constructs are extensions of those two, added later.
The trade-off is indirection. Once a Lambda is created by createApiLambda, a reader has to open the factory to see what that function actually gets. That cost is worth paying for resources that repeat and policies that must hold everywhere, and it is not worth paying for a one-off bucket.
Related posts: Creational patterns in TypeScript and builder patterns cover the general shapes; what follows applies them to AWS CDK infrastructure. For environment management and migration context, see Serverless to CDK migration Part 4.
Versions: the examples use aws-cdk-lib v2 with constructs v10, TypeScript in strict mode, and Zod 4 for the configuration schema. The Lambda functions run on the nodejs24.x runtime.
The Configuration Drift Problem#
Working with AWS CDK across several microservices surfaces a recurring pattern: different developers configure Lambda functions differently. Some forget to set log retention, others use inconsistent timeout values, and memory sizes vary across similar workloads for no stated reason. Production databases get deleted because a RemovalPolicy.DESTROY copied from a dev stack reaches production. Development databases keep the CDK default (RETAIN), outlive their stacks, and quietly accumulate cost.
The fundamental issue wasn’t lack of knowledge; it was lack of enforcement. A Lambda configuration block copy-pasted into every stack has to be corrected in every stack. When the requirement changes, updating it consistently turns into a project-wide refactoring exercise.
Central NodejsFunction Configuration Factory#
The simplest pattern that made a significant difference was creating a factory function for Lambda configurations.
Without Pattern:
// Repeated across every Lambda stack
new NodejsFunction(this, 'UserHandler', {
runtime: Runtime.NODEJS_24_X,
handler: 'handler',
entry: 'src/handlers/user.ts',
timeout: Duration.seconds(30),
memorySize: 1024,
logGroup: new LogGroup(this, 'UserHandlerLogs', {
retention: RetentionDays.ONE_WEEK
}),
tracing: Tracing.ACTIVE,
environment: {
NODE_OPTIONS: '--enable-source-maps',
LOG_LEVEL: 'info'
},
bundling: {
minify: true,
sourceMap: true,
externalModules: ['@aws-sdk/*'],
mainFields: ['module', 'main']
}
});
// Same config duplicated for OrderHandler, ProductHandler, etc.
With Factory Pattern:
// lib/constructs/lambda-factory.ts
import { Duration } from 'aws-cdk-lib';
import { IVpc, SubnetSelection } from 'aws-cdk-lib/aws-ec2';
import { Architecture, Runtime, Tracing } from 'aws-cdk-lib/aws-lambda';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { LogGroup } from 'aws-cdk-lib/aws-logs';
import { Construct } from 'constructs';
// Defined in the configuration section below
import type { EnvironmentConfig } from '../../config/environment';
export interface LambdaConfig {
entry: string;
handler?: string;
environment?: Record<string, string>;
timeout?: Duration;
memorySize?: number;
// Constructor-only props: nothing can add them after the function exists
vpc?: IVpc;
vpcSubnets?: SubnetSelection;
architecture?: Architecture;
}
export function createApiLambda(
scope: Construct,
id: string,
env: EnvironmentConfig,
config: LambdaConfig
): NodejsFunction {
return new NodejsFunction(scope, id, {
runtime: Runtime.NODEJS_24_X,
handler: config.handler ?? 'handler',
entry: config.entry,
timeout: config.timeout ?? Duration.seconds(env.lambdaDefaults.timeout),
memorySize: config.memorySize ?? env.lambdaDefaults.memorySize,
vpc: config.vpc,
vpcSubnets: config.vpcSubnets,
architecture: config.architecture,
logGroup: new LogGroup(scope, `${id}Logs`, {
retention: env.logRetention
}),
tracing: env.monitoring.enableXRay ? Tracing.ACTIVE : Tracing.DISABLED,
environment: {
NODE_OPTIONS: '--enable-source-maps',
LOG_LEVEL: env.stage === 'prod' ? 'warn' : 'debug',
...config.environment
},
bundling: {
minify: true,
sourceMap: true,
externalModules: ['@aws-sdk/*'],
mainFields: ['module', 'main']
}
});
}
// Usage - config is the validated EnvironmentConfig from getConfig()
const userHandler = createApiLambda(this, 'UserHandler', config, {
entry: 'src/handlers/user.ts',
environment: { TABLE_NAME: userTable.tableName }
});
The stage-specific settings come from the typed EnvironmentConfig: the timeout and memory defaults, tracing, the log level, and log retention. Retention goes through an explicit LogGroup passed as logGroup. The older logRetention prop is deprecated in aws-cdk-lib, and it works through a custom resource that creates the log group behind the scenes. Moving off it changes the log group’s name, so dashboards and metric filters that reference /aws/lambda/<function> have to follow.
The payoff shows up on runtime upgrades. Lambda deprecated nodejs20.x on April 30, 2026. Moving every function to Node.js 24 is one line in the factory (Runtime.NODEJS_20_X becomes Runtime.NODEJS_24_X) rather than one edit per function definition, and no function that someone added last week gets missed. The factory test in the testing section pins the runtime, so the upgrade shows up there as well.
RemovalPolicy Enforcement with Higher-Order Functions#
Deleting a production table because RemovalPolicy.DESTROY was copied out of a dev stack is a routine failure with an expensive recovery path. Environment-specific policies belong in one place that applies them to every stateful resource automatically.
Without Pattern:
// No removalPolicy: the L2 default (RETAIN) applies
const userTable = new Table(this, 'UserTable', {
partitionKey: { name: 'id', type: AttributeType.STRING },
billingMode: BillingMode.PAY_PER_REQUEST
});
// Copied from the dev stack, DESTROY included
const sessionTable = new Table(this, 'SessionTable', {
partitionKey: { name: 'sessionId', type: AttributeType.STRING },
billingMode: BillingMode.PAY_PER_REQUEST,
removalPolicy: RemovalPolicy.DESTROY // deletes the table along with a prod stack
});
The forgotten policy is the safe case. CDK’s L2 Table and Bucket default to RETAIN, which is the opposite of the CloudFormation default. The dangerous line is the explicit DESTROY in sessionTable: correct in dev, it travels into production with the copy.
With Higher-Order Function:
// lib/utils/removal-policy.ts
import { RemovalPolicy, Resource } from 'aws-cdk-lib';
// Stage is the Zod enum from the configuration section below
import type { Stage } from '../../config/environment';
// Only the stages listed here may lose data on stack deletion
const EPHEMERAL_STAGES: ReadonlySet<Stage> = new Set<Stage>(['dev']);
export const isEphemeral = (stage: Stage): boolean =>
EPHEMERAL_STAGES.has(stage);
export function withRemovalPolicy<T extends Resource>(
resource: T,
stage: Stage
): T {
resource.applyRemovalPolicy(
isEphemeral(stage) ? RemovalPolicy.DESTROY : RemovalPolicy.RETAIN
);
return resource;
}
// Usage - policy follows the stage
const userTable = withRemovalPolicy(
new Table(this, 'UserTable', {
partitionKey: { name: 'id', type: AttributeType.STRING },
billingMode: BillingMode.PAY_PER_REQUEST
}),
config.stage // 'dev' | 'staging' | 'prod'
);
The default is RETAIN. A stage has to be listed in EPHEMERAL_STAGES before anything can be destroyed, so staging (or a qa stage added later) starts out safe. Stage comes from the Zod schema, so 'Prod', 'production' or a typo never reaches this code: getConfig rejects it during synth.
Even Better - Using CDK Aspects:
// lib/aspects/removal-policy-aspect.ts
import { CfnDeletionPolicy, CfnResource, IAspect, RemovalPolicy } from 'aws-cdk-lib';
import { IConstruct } from 'constructs';
import type { Stage } from '../../config/environment';
import { isEphemeral } from '../utils/removal-policy';
const STATEFUL_TYPES = new Set([
'AWS::DynamoDB::Table',
'AWS::DynamoDB::GlobalTable',
'AWS::S3::Bucket',
'AWS::RDS::DBCluster',
'AWS::RDS::DBInstance',
'AWS::EFS::FileSystem',
'AWS::KMS::Key'
]);
export class RemovalPolicyAspect implements IAspect {
private readonly keep: ReadonlySet<IConstruct>;
constructor(
private readonly stage: Stage,
keep: IConstruct[] = [] // resources a dev stack deliberately retains
) {
this.keep = new Set(keep.map((c) => c.node.defaultChild ?? c));
}
visit(node: IConstruct): void {
if (!(node instanceof CfnResource) || !STATEFUL_TYPES.has(node.cfnResourceType)) {
return;
}
if (isEphemeral(this.stage)) {
if (!this.keep.has(node)) {
node.applyRemovalPolicy(RemovalPolicy.DESTROY);
}
return;
}
// Outside dev, only move toward safety: an explicit RETAIN or SNAPSHOT stays
const current = node.cfnOptions.deletionPolicy;
if (current === undefined || current === CfnDeletionPolicy.DELETE) {
node.applyRemovalPolicy(RemovalPolicy.RETAIN);
}
}
}
// Apply to entire stack
Aspects.of(this).add(new RemovalPolicyAspect(config.stage));
An Aspect visits every node in the construct tree during synthesis, so the policy reaches resources that the individual stack files never mention. That is the difference between the wrapper and the Aspect: the wrapper only protects the tables somebody remembered to wrap.
The Aspect matches L1 resource types, so it also covers TableV2 (rendered as a GlobalTable), RDS instances and clusters, EFS file systems, and KMS keys. Outside dev it only moves a resource toward RETAIN. An explicit RETAIN or SNAPSHOT stays as written, and a copied DESTROY becomes RETAIN. In dev it applies DESTROY to everything except the resources passed in keep. CDK renders the L2 default and an explicit RETAIN as the same DeletionPolicy, so the Aspect cannot tell them apart; keep is how a dev stack marks the ones it wants to retain.
Buckets need one more step in dev. CloudFormation does not delete an S3 bucket that still contains objects, even under DESTROY. The L2 autoDeleteObjects prop empties the bucket first, but it is a constructor prop that the Aspect cannot add. Set it in the bucket props together with removalPolicy: RemovalPolicy.DESTROY, and only when isEphemeral(stage) is true.
Composable Configuration Builders#
Lambda functions often need different combinations of features: some need a failure queue, some need layers, some need alarms, some need all three. Configuring these combinations cleanly requires a composition approach.
// lib/constructs/lambda-composers.ts
import { Duration } from 'aws-cdk-lib';
import { Alarm } from 'aws-cdk-lib/aws-cloudwatch';
import { ILayerVersion } from 'aws-cdk-lib/aws-lambda';
import { SqsDestination } from 'aws-cdk-lib/aws-lambda-destinations';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { IQueue, Queue } from 'aws-cdk-lib/aws-sqs';
export type LambdaComposer = (fn: NodejsFunction) => void;
// Asynchronous invocations only: an event that fails every retry lands in the queue.
// SqsDestination also grants the function sqs:SendMessage on that queue.
export const withFailureQueue = (queue?: IQueue): LambdaComposer =>
(fn) => {
const failureQueue = queue ?? new Queue(fn, 'FailureQueue', {
retentionPeriod: Duration.days(14)
});
fn.configureAsyncInvoke({
onFailure: new SqsDestination(failureQueue)
});
};
export const withLayer = (layer: ILayerVersion): LambdaComposer =>
(fn) => {
fn.addLayers(layer);
};
export const withAlarm = (
errorThreshold: number = 10
): LambdaComposer =>
(fn) => {
new Alarm(fn, 'ErrorAlarm', {
metric: fn.metricErrors(),
threshold: errorThreshold,
evaluationPeriods: 2
});
};
// Compose multiple behaviors
export function composeLambda(
fn: NodejsFunction,
...composers: LambdaComposer[]
): NodejsFunction {
composers.forEach(composer => composer(fn));
return fn;
}
// Usage - a handler that S3 event notifications invoke asynchronously
const uploadHandler = composeLambda(
createApiLambda(this, 'UploadHandler', config, {
entry: 'src/handlers/upload.ts'
}),
withFailureQueue(),
withLayer(sharedLayer),
withAlarm(5)
);
Each composer handles one cross-cutting concern, and they can be combined as needed. withFailureQueue only matters for asynchronous invocations, such as S3 event notifications or SNS. Lambda retries the event, and once the retries run out it sends an invocation record to the queue. A synchronous caller such as API Gateway receives the error directly, so the composer adds nothing to an API handler. configureAsyncInvoke can be called only once per function, so this composer owns the function’s async settings.
The pattern has a hard limit. A composer receives a function that already exists, so it can only use what NodejsFunction exposes after construction: addEnvironment, addLayers, configureAsyncInvoke, addToRolePolicy, and the metric helpers. Props that exist only in the constructor (vpc, vpcSubnets, architecture, runtime, deadLetterQueue) cannot be composed in later. They belong in the factory’s LambdaConfig, which is why createApiLambda accepts vpc and architecture directly. The same limit explains why withFailureQueue uses an on-failure destination instead of the deadLetterQueue prop. The destination record also carries details about the request and response, while a dead-letter queue receives only the event content.
Type-Safe Environment Configuration#
Environment-specific settings (VPC IDs, subnet IDs, domain names) scattered across code makes it hard to understand what varies between environments. A strongly-typed configuration pattern solves this.
// config/environment.ts
import { RetentionDays } from 'aws-cdk-lib/aws-logs';
import { z } from 'zod';
export const StageSchema = z.enum(['dev', 'staging', 'prod']);
export type Stage = z.infer<typeof StageSchema>;
const EnvironmentSchema = z.object({
stage: StageSchema,
account: z.string().regex(/^\d{12}$/),
region: z.string(),
vpc: z.object({
id: z.string(),
privateSubnetIds: z.array(z.string()).min(2),
publicSubnetIds: z.array(z.string()).min(2)
}),
domain: z.string(),
logRetention: z.enum(RetentionDays),
lambdaDefaults: z.object({
timeout: z.number().int().min(3).max(900),
memorySize: z.number().int().min(128).max(10240)
}),
monitoring: z.object({
enableXRay: z.boolean(),
enableDetailedMetrics: z.boolean()
})
});
export type EnvironmentConfig = z.infer<typeof EnvironmentSchema>;
// config/dev.ts
export const devConfig: EnvironmentConfig = {
stage: 'dev',
account: '123456789012',
region: 'us-east-1',
vpc: {
id: 'vpc-dev123',
privateSubnetIds: ['subnet-dev1', 'subnet-dev2'],
publicSubnetIds: ['subnet-pub1', 'subnet-pub2']
},
domain: 'dev.example.com',
logRetention: RetentionDays.ONE_WEEK, // 7 days
lambdaDefaults: {
timeout: 30,
memorySize: 512
},
monitoring: {
enableXRay: false,
enableDetailedMetrics: false
}
};
// config/prod.ts
export const prodConfig: EnvironmentConfig = {
stage: 'prod',
account: '210987654321',
region: 'us-east-1',
vpc: {
id: 'vpc-prod456',
privateSubnetIds: ['subnet-prod1', 'subnet-prod2', 'subnet-prod3'],
publicSubnetIds: ['subnet-pub1', 'subnet-pub2', 'subnet-pub3']
},
domain: 'api.example.com',
logRetention: RetentionDays.THREE_MONTHS, // 90 days
lambdaDefaults: {
timeout: 60,
memorySize: 1024
},
monitoring: {
enableXRay: true,
enableDetailedMetrics: true
}
};
// config/index.ts
export function getConfig(stage: string): EnvironmentConfig {
const configs: Record<Stage, EnvironmentConfig> = {
dev: devConfig,
staging: stagingConfig, // config/staging.ts has the same shape
prod: prodConfig
};
// 'Prod', 'production' or a typo fails here, before any resource exists
return EnvironmentSchema.parse(configs[StageSchema.parse(stage)]);
}
// Usage in stack
export class ApiStack extends Stack {
constructor(scope: Construct, id: string, config: EnvironmentConfig) {
super(scope, id, {
env: {
account: config.account,
region: config.region
}
});
const vpc = Vpc.fromLookup(this, 'Vpc', { vpcId: config.vpc.id });
// Timeout, memory, tracing, log level and log retention come from config
createApiLambda(this, 'Handler', config, {
entry: 'src/handlers/api.ts',
vpc,
vpcSubnets: {
subnetFilters: [SubnetFilter.byIds(config.vpc.privateSubnetIds)]
}
});
Aspects.of(this).add(new RemovalPolicyAspect(config.stage));
}
}
Zod validation catches configuration errors during synth, before any deployment starts. StageSchema turns a misspelled stage into a synth error, and z.enum(RetentionDays) accepts only values from CDK’s RetentionDays enum. The factory reads tracing, the log level, log retention, and the Lambda defaults from this one object. With enableXRay: false it sets Tracing.DISABLED. With true it sets Tracing.ACTIVE, and CDK adds xray:PutTraceSegments and xray:PutTelemetryRecords to the function role itself, so no separate X-Ray policy is needed. TypeScript adds compile-time checks and editor autocomplete on top.
Custom L3 Constructs with Sensible Defaults#
Every API endpoint needing Lambda + API Gateway + DynamoDB table + CloudWatch alarms creates a lot of repetitive code. Custom L3 constructs encapsulate these patterns.
// lib/constructs/api-endpoint.ts
export interface ApiEndpointProps {
readonly config: EnvironmentConfig;
readonly handlerEntry: string;
readonly partitionKey: Attribute;
readonly sortKey?: Attribute;
// Required: an authorizer, or 'public' as an explicit opt-out
readonly authorizer: IAuthorizer | 'public';
readonly throttle?: { rateLimit: number; burstLimit: number };
readonly environment?: Record<string, string>;
readonly timeout?: Duration;
readonly memorySize?: number;
}
export class ApiEndpoint extends Construct {
public readonly handler: NodejsFunction;
public readonly table: Table;
public readonly api: RestApi;
constructor(scope: Construct, id: string, props: ApiEndpointProps) {
super(scope, id);
// No tableName: CloudFormation generates a unique one per stack
this.table = new Table(this, 'Table', {
partitionKey: props.partitionKey,
sortKey: props.sortKey,
billingMode: BillingMode.PAY_PER_REQUEST,
encryption: TableEncryption.AWS_MANAGED,
pointInTimeRecoverySpecification: { pointInTimeRecoveryEnabled: true },
removalPolicy: RemovalPolicy.RETAIN,
stream: StreamViewType.NEW_AND_OLD_IMAGES
});
// Create Lambda with standardized settings
this.handler = createApiLambda(this, 'Handler', props.config, {
entry: props.handlerEntry,
timeout: props.timeout,
memorySize: props.memorySize,
environment: {
TABLE_NAME: this.table.tableName,
...props.environment
}
});
// Grant permissions
this.table.grantReadWriteData(this.handler);
// Example limits: size them from the expected load
const throttle = props.throttle ?? { rateLimit: 50, burstLimit: 100 };
// Create API Gateway; every method inherits defaultMethodOptions
this.api = new RestApi(this, 'Api', {
restApiName: `${id}-api`,
deployOptions: {
stageName: 'v1',
tracingEnabled: props.config.monitoring.enableXRay,
loggingLevel: MethodLoggingLevel.INFO,
metricsEnabled: true,
throttlingRateLimit: throttle.rateLimit,
throttlingBurstLimit: throttle.burstLimit
},
defaultMethodOptions: props.authorizer === 'public'
? { authorizationType: AuthorizationType.NONE }
: { authorizer: props.authorizer }
});
const integration = new LambdaIntegration(this.handler);
this.api.root.addMethod('ANY', integration);
// Add monitoring
new Alarm(this, 'ErrorAlarm', {
metric: this.handler.metricErrors(),
threshold: 5,
evaluationPeriods: 2,
alarmDescription: `Errors on ${id}`
});
new Alarm(this, 'ThrottleAlarm', {
metric: this.handler.metricThrottles(),
threshold: 1,
evaluationPeriods: 1,
alarmDescription: `Throttles on ${id}`
});
}
// Helper method for additional routes
public addRoute(
path: string,
method: string,
handler: IFunction
): void {
const resource = this.api.root.resourceForPath(path);
resource.addMethod(method, new LambdaIntegration(handler));
}
}
// Usage - table, handler, API, and both alarms in one construct
const userEndpoint = new ApiEndpoint(this, 'UserEndpoint', {
config,
handlerEntry: 'src/handlers/user.ts',
partitionKey: { name: 'userId', type: AttributeType.STRING },
authorizer: new CognitoUserPoolsAuthorizer(this, 'UserAuth', {
cognitoUserPools: [userPool]
})
});
The construct bundles encryption at rest, point-in-time recovery in every stage, scoped IAM permissions, API Gateway logging, stage-level throttling, and CloudWatch alarms. Access control is a required decision. The caller passes an authorizer, or writes 'public' and leaves an open endpoint in plain sight of the reviewer. defaultMethodOptions applies that choice to every method, including the routes addRoute adds later.
The table has no tableName. A fixed name blocks a second stage in the same account and Region, and the CDK documentation warns that an update requiring replacement fails on any resource with a physical name. Two limits remain. Every ApiEndpoint creates its own RestApi, so once several endpoints belong to one API, pass a shared API in as a prop. A WAF web ACL, if the API needs one, is not part of the construct.
Policy Enforcement with CDK Aspects#
Security requirements (encryption at rest, encryption in transit, no public S3 buckets, CloudWatch logs for everything) need automatic enforcement.
// lib/aspects/security-compliance.ts
import { Annotations, Aspects, IAspect, Stack, StackProps } from 'aws-cdk-lib';
import { CfnFunction } from 'aws-cdk-lib/aws-lambda';
import { CfnLogGroup } from 'aws-cdk-lib/aws-logs';
import { CfnBucket } from 'aws-cdk-lib/aws-s3';
import { Construct, IConstruct } from 'constructs';
// Shape of CfnBucket.bucketEncryption once tokens are resolved
interface ResolvedEncryption {
serverSideEncryptionConfiguration?: {
serverSideEncryptionByDefault?: { sseAlgorithm?: string };
}[];
}
export class S3EncryptionAspect implements IAspect {
visit(node: IConstruct): void {
if (!(node instanceof CfnBucket)) {
return;
}
// S3 already applies SSE-S3 to every bucket; the requirement here is SSE-KMS
const encryption: ResolvedEncryption | undefined =
Stack.of(node).resolve(node.bucketEncryption);
const usesKms = encryption?.serverSideEncryptionConfiguration?.some(
(rule) => rule.serverSideEncryptionByDefault?.sseAlgorithm?.startsWith('aws:kms')
) ?? false;
if (!usesKms) {
Annotations.of(node).addError('S3 buckets must use SSE-KMS encryption');
}
}
}
export class PublicAccessBlockAspect implements IAspect {
visit(node: IConstruct): void {
if (node instanceof CfnBucket) {
if (!node.publicAccessBlockConfiguration) {
node.publicAccessBlockConfiguration = {
blockPublicAcls: true,
blockPublicPolicy: true,
ignorePublicAcls: true,
restrictPublicBuckets: true
};
}
}
}
}
export class LambdaLogGroupAspect implements IAspect {
visit(node: IConstruct): void {
// RetentionDays.INFINITE renders no RetentionInDays either
if (node instanceof CfnLogGroup && node.retentionInDays === undefined) {
Annotations.of(node).addWarningV2('app:log-retention', 'Log group has no retention');
}
// CfnFunction covers NodejsFunction and Function alike
if (!(node instanceof CfnFunction)) {
return;
}
const logging: { logGroup?: unknown } | undefined =
Stack.of(node).resolve(node.loggingConfig);
if (!logging?.logGroup) {
Annotations.of(node).addWarningV2(
'app:lambda-log-group',
'Lambda function has no explicit log group; create it with createApiLambda'
);
}
}
}
// Apply stack-wide
export class SecureStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// Enforce security policies on everything in this stack
Aspects.of(this).add(new S3EncryptionAspect());
Aspects.of(this).add(new PublicAccessBlockAspect());
Aspects.of(this).add(new LambdaLogGroupAspect());
}
}
Those three classes behave differently on purpose. S3EncryptionAspect fails the synth with an error annotation, PublicAccessBlockAspect repairs the resource silently, and LambdaLogGroupAspect only reports: a function without an explicit log group, and a log group without retention. Annotating is the safer choice for anything a team might legitimately want to override, because a silent mutation hides the decision from whoever reads the stack later.
The encryption check asks for SSE-KMS because S3 already encrypts every new object with SSE-S3 by default. A check for any encryption at all would protect nothing, and since the L2 Bucket does not render BucketEncryption in its default state, it would also flag every default bucket. The log checks report a missing log group or a missing retention and leave the fix to the factory. Without a retention setting, CloudWatch Logs keeps log data indefinitely, and RetentionDays.INFINITE renders the same template, so it gets the warning too. An Aspect that created a log group named /aws/lambda/<function> would fail with an already-exists error on any function that had run before the Aspect was added, because Lambda had already created that group on the first invocation and log group names are unique per account and Region. A warning does not stop a deploy on its own; cdk synth --strict in CI refuses to synthesize stacks that contain warnings.
Common Pitfalls and Solutions#
Over-Abstraction#
Creating factory functions for every single resource, even simple ones, leads to abstraction overhead without benefits. Apply patterns selectively to resources with repeated configurations or complex validation requirements. A single S3 bucket doesn’t need a factory.
When to abstract:
- Resource appears 3+ times with similar config
- Complex validation logic required
- Environment-specific variations needed
- Security/compliance policies must be enforced
Implicit Dependencies#
Factory functions that assume certain resources exist (VPC, security groups) without making dependencies explicit create fragile code. Make dependencies explicit through function parameters.
// Bad - where does 'vpc' come from?
function createLambda(entry: string): NodejsFunction {
return new NodejsFunction(this, 'Fn', {
entry,
vpc, // Implicit dependency
});
}
// Good - explicit dependency
function createLambda(
scope: Construct,
id: string,
entry: string,
vpc: IVpc
): NodejsFunction {
return new NodejsFunction(scope, id, { entry, vpc });
}
Type Safety Lost in Wrappers#
Using any types or overly permissive generics defeats TypeScript’s type checking. Maintain strict types through factory layers.
// Bad - type safety lost
function createResource(props: any): any {
// ...
}
// Good - type safety preserved
function createResource<T extends Construct, P>(
constructClass: new (scope: Construct, id: string, props: P) => T,
scope: Construct,
id: string,
props: P
): T {
return new constructClass(scope, id, props);
}
Configuration Drift Between Environments#
Using different configuration patterns in dev vs prod causes “works in dev” production failures. Use the same code path for all environments, different only in configuration values.
// Same factory, different config
const config = getConfig(stage); // validated EnvironmentConfig
const lambda = createApiLambda(this, 'Handler', config, {
entry: 'src/handler.ts'
});
Testing Infrastructure Code#
Infrastructure code should be tested like application code. Use the CDK assertions library to verify resource properties.
import { Stack } from 'aws-cdk-lib';
import { Match, Template } from 'aws-cdk-lib/assertions';
import { prodConfig } from '../config/prod';
import { createApiLambda } from '../lib/constructs/lambda-factory';
test('Lambda factory applies the prod settings from config', () => {
const stack = new Stack();
createApiLambda(stack, 'TestFn', prodConfig, {
entry: 'src/test.ts'
});
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::Lambda::Function', {
Runtime: 'nodejs24.x',
Timeout: 60,
MemorySize: 1024,
TracingConfig: { Mode: 'Active' },
Environment: { Variables: Match.objectLike({ LOG_LEVEL: 'warn' }) }
});
template.hasResourceProperties('AWS::Logs::LogGroup', {
RetentionInDays: 90
});
});
Testing catches configuration errors and validates that factory functions produce expected CloudFormation resources. The Runtime assertion pins the runtime on purpose. When the factory moves to the next runtime, this test fails until its expected value moves too, so a runtime upgrade lands as a deliberate two-line diff that a reviewer sees.
When Factories Earn Their Keep#
Reach for a factory once a resource type appears in three or more places, or once a setting has to hold everywhere whether or not anyone remembers it. RemovalPolicy, encryption, and log retention belong in that second group. An Aspect enforces the first two directly; log retention is set by the factory and checked by an Aspect. Either way, the Aspect also covers the stack a colleague writes next month. Layer builders, composers, and custom L3 constructs on top only after the combinations they hide have actually appeared in the codebase.
Override the default when the stack is small enough to read end to end, when a resource is genuinely one of a kind, or when the team has not yet agreed on what the standard should be. A factory written before the pattern exists encodes a guess, and a wrong guess in shared infrastructure code is harder to unwind than the duplication it replaced. Of the patterns above, the Aspect is the one to adopt first, since enforcement is where mistakes cost money, and Template.fromStack in a unit test is what keeps the factory honest afterwards.
References#
- AWS CDK Developer Guide (opens in new tab) - Official guide covering CDK concepts, constructs, stacks, and deployment workflows
- AWS CDK API Reference (opens in new tab) - Complete API documentation for all L1, L2, and L3 constructs in the AWS Construct Library
- AWS CDK Best Practices (opens in new tab) - Official guidance on project structure, construct design, and configuration management
- Working with CDK in TypeScript (opens in new tab) - TypeScript-specific patterns and tooling for CDK development
- Organize Code for Large-Scale CDK Projects (opens in new tab) - AWS Prescriptive Guidance on folder structure and code organization for CDK TypeScript projects
- Create or Extend Constructs - AWS Prescriptive Guidance (opens in new tab) - Best practices for building reusable and extensible CDK constructs
- Resources and the AWS CDK (opens in new tab) - Removal policies (CDK retains by default, unlike CloudFormation),
autoDeleteObjectsfor non-empty buckets, and why physical names block replacement updates - AWS CDK CLI Command Reference (opens in new tab) - Global CLI options, including
--strictfor refusing stacks that contain warnings - Lambda Runtimes (opens in new tab) - Supported Lambda runtimes and their projected deprecation dates, including
nodejs24.x - Lambda Runtime Deprecation (opens in new tab) - Deprecation policy and the deprecated-runtimes table, including
nodejs20.xdeprecated on Apr 30, 2026 - Working with Log Groups and Log Streams (opens in new tab) - Default indefinite log retention and how to set a retention period per log group
- Capturing Records of Lambda Asynchronous Invocations (opens in new tab) - On-failure destinations, their required permissions, and how they differ from dead-letter queues
- Configuring CloudWatch Log Groups for Lambda (opens in new tab) - The default
/aws/lambda/<function name>log group created on first invocation, and custom log groups - Configuring Default Encryption for S3 Buckets (opens in new tab) - SSE-S3 as the base level of encryption for every bucket, and when to choose SSE-KMS
Related posts
A lifecycle test for CDK stack layout: give a resource its own long-lived stack when it outlives any single deployer, then reach it by a well-known name.
aws-cdk · infrastructure-as-code · typescript +3
When to use service-based, domain-based, feature-based, or layer-based organization in AWS CDK projects, with decision frameworks and common pitfalls.
aws-cdk · typescript · infrastructure-as-code +3
A small, complete URL shortener on AWS Lambda and DynamoDB with Effect and SST v4, showing schema-at-the-boundary, layers, and tagged-error mapping.
functional-programming · lambda · typescript +2
A CDK guide for deploying a minimal Strands agent on AgentCore Runtime: parameterized stack, arm64 build, deploy and invoke, with IAM and Marketplace prerequisites.
aws-bedrock · ai-agents · aws-cdk +3
Overcome CloudFormation's 500 resource limit with nested stacks, cross-stack references, SSM Parameter Store, and microstack architecture, shown in TypeScript CDK.
aws-cdk · infrastructure-as-code · aws +2