AWS CDK Project Structure: Service-Based vs Domain-Based Organization
When to use service-based, domain-based, feature-based, or layer-based organization in AWS CDK projects, with decision frameworks and common pitfalls.
An AWS CDK app is a program, so its folder and stack layout is a design decision the framework leaves to you. Skip that decision and the cost shows up later as tight coupling, circular dependencies between stacks, and deploys nobody can run without checking with another team first. The layout that holds up at scale is domain-based organization with a thin foundation layer: everything a business domain owns lives in one folder and one stack, while VPC, security, and monitoring sit in a shared stack beneath them.
The starting point is smaller than that target. Begin with domain folders as constructs inside a single stack, and give each domain its own stack once a second team or a different deploy cadence shows up. Service-based, feature-based, layer-based, and hybrid layouts each win in specific contexts, and every pattern below comes with TypeScript plus the conditions under which it beats that default. A decision table maps team setup to layout, and the decision frameworks cover the two questions that bite hardest: when to split a stack instead of adding a construct, and when a monorepo stops paying for itself.
How Accidental Layouts Break#
A recurring pattern in CDK projects: good intentions gradually erode as maintainability declines. Infrastructure code grows organically, files are placed wherever convenient, and before long teams struggle with merge conflicts, unclear ownership, and deployment dependencies they cannot untangle.
The technical challenges manifest in several ways. Teams organizing by AWS service (creating separate folders for lambda/, dynamodb/, api-gateway/) find that changes to a single business feature require touching multiple directories. Cross-stack references create deployment dependencies that aren’t obvious until something breaks. When multiple teams work on shared infrastructure, unclear domain boundaries lead to merge conflicts and coordination overhead.
The question is not really where files live. It is how to model infrastructure so that it reflects business architecture, deployment requirements, and team structure, without the coupling that makes systems fragile.
Whatever layout you land on has to hold up against the same demands. Teams need to deploy their own changes without coordinating with other teams or worrying about breaking unrelated systems. Every stack and construct needs an obvious owner, so it is clear who to ask when something breaks. Related resources should sit together, so developers can find what they need quickly. The pattern has to survive growth from 10 resources to 500, and from 1 team to 10, without a major restructure. And shared infrastructure like VPCs, security policies, and monitoring has to land somewhere without duplication or awkward dependencies.
Four Layouts and a Hybrid#
Service-Based Organization#
The service-based pattern organizes code by AWS service type: all Lambda functions together, all DynamoDB tables together, all API Gateways together.
// Directory structure
// cdk-project/
// ├── lib/
// │ ├── lambda/
// │ │ ├── user-handler.ts
// │ │ ├── order-handler.ts
// │ │ └── payment-handler.ts
// │ ├── dynamodb/
// │ │ ├── user-table.ts
// │ │ ├── order-table.ts
// │ │ └── payment-table.ts
// │ ├── api-gateway/
// │ │ ├── user-api.ts
// │ │ ├── order-api.ts
// │ │ └── payment-api.ts
// │ └── stacks/
// │ ├── lambda-stack.ts
// │ ├── dynamodb-stack.ts
// │ └── api-gateway-stack.ts
// lib/stacks/dynamodb-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Table, BillingMode, AttributeType } from 'aws-cdk-lib/aws-dynamodb';
export class DynamoDBStack extends Stack {
public readonly userTable: Table;
public readonly orderTable: Table;
public readonly paymentTable: Table;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
this.userTable = new Table(this, 'UserTable', {
partitionKey: { name: 'userId', type: AttributeType.STRING },
billingMode: BillingMode.PAY_PER_REQUEST
});
this.orderTable = new Table(this, 'OrderTable', {
partitionKey: { name: 'orderId', type: AttributeType.STRING },
billingMode: BillingMode.PAY_PER_REQUEST
});
this.paymentTable = new Table(this, 'PaymentTable', {
partitionKey: { name: 'paymentId', type: AttributeType.STRING },
billingMode: BillingMode.PAY_PER_REQUEST
});
}
}
// lib/stacks/lambda-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Table } from 'aws-cdk-lib/aws-dynamodb';
export interface LambdaStackProps extends StackProps {
readonly userTable: Table;
readonly orderTable: Table;
readonly paymentTable: Table;
}
export class LambdaStack extends Stack {
constructor(scope: Construct, id: string, props: LambdaStackProps) {
super(scope, id, props);
const userHandler = new NodejsFunction(this, 'UserHandler', {
entry: 'src/handlers/user.ts',
environment: {
TABLE_NAME: props.userTable.tableName
}
});
props.userTable.grantReadWriteData(userHandler);
// Similar for order and payment handlers...
}
}
This approach seems logical initially: all Lambda functions are in one place, making it easy to apply consistent configurations. However, the problems become apparent quickly:
- Making a change to user functionality requires touching multiple directories and stacks
- Cross-stack references create deployment dependencies (DynamoDB stack must deploy before Lambda stack)
- Team ownership is unclear (who owns the “Lambda stack”?)
- Deploying a subset of infrastructure (just user-related resources) is difficult
None of that hurts much on a small project. Under 10 resources, in a learning or experimentation phase, or in a single-service application, the layout has not started to matter yet.
Domain-Based Organization#
The domain-based pattern organizes code by business domain or bounded context, grouping all infrastructure for a domain together.
// Directory structure
// cdk-project/
// ├── lib/
// │ ├── domains/
// │ │ ├── user/
// │ │ │ ├── user-stack.ts
// │ │ │ ├── user-handler.ts
// │ │ │ ├── user-table.ts
// │ │ │ ├── user-api.ts
// │ │ │ └── constructs/
// │ │ │ └── user-service.ts
// │ │ ├── order/
// │ │ │ ├── order-stack.ts
// │ │ │ ├── order-handler.ts
// │ │ │ ├── order-table.ts
// │ │ │ └── order-api.ts
// │ │ └── payment/
// │ │ ├── payment-stack.ts
// │ │ ├── payment-handler.ts
// │ │ └── payment-table.ts
// │ └── shared/
// │ ├── networking-stack.ts
// │ ├── security-stack.ts
// │ └── monitoring-stack.ts
// lib/domains/user/user-stack.ts
import { Stack, StackProps, RemovalPolicy } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Table, BillingMode, AttributeType, TableEncryption } from 'aws-cdk-lib/aws-dynamodb';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { RestApi, LambdaIntegration } from 'aws-cdk-lib/aws-apigateway';
export class UserStack extends Stack {
public readonly api: RestApi;
public readonly apiEndpoint: string;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// All user-related infrastructure in one place
const table = new Table(this, 'UserTable', {
partitionKey: { name: 'userId', type: AttributeType.STRING },
billingMode: BillingMode.PAY_PER_REQUEST,
encryption: TableEncryption.AWS_MANAGED,
pointInTimeRecovery: true,
removalPolicy: RemovalPolicy.RETAIN
});
const handler = new NodejsFunction(this, 'UserHandler', {
entry: 'src/handlers/user.ts',
environment: {
TABLE_NAME: table.tableName
}
});
table.grantReadWriteData(handler);
this.api = new RestApi(this, 'UserApi', {
restApiName: 'user-service',
deployOptions: {
stageName: 'v1',
tracingEnabled: true
}
});
const users = this.api.root.addResource('users');
users.addMethod('GET', new LambdaIntegration(handler));
users.addMethod('POST', new LambdaIntegration(handler));
const user = users.addResource('{userId}');
user.addMethod('GET', new LambdaIntegration(handler));
user.addMethod('PUT', new LambdaIntegration(handler));
user.addMethod('DELETE', new LambdaIntegration(handler));
this.apiEndpoint = this.api.url;
}
}
// bin/app.ts
import { App } from 'aws-cdk-lib';
import { UserStack } from '../lib/domains/user/user-stack';
import { OrderStack } from '../lib/domains/order/order-stack';
import { PaymentStack } from '../lib/domains/payment/payment-stack';
const app = new App();
const userStack = new UserStack(app, 'UserStack', {
env: { account: '123456789012', region: 'us-east-1' }
});
const orderStack = new OrderStack(app, 'OrderStack', {
env: { account: '123456789012', region: 'us-east-1' },
userApiEndpoint: userStack.apiEndpoint
});
// Passing userStack.apiEndpoint already makes OrderStack depend on UserStack
const paymentStack = new PaymentStack(app, 'PaymentStack', {
env: { account: '123456789012', region: 'us-east-1' }
});
This organization aligns infrastructure with business capabilities. Changes to user functionality only touch the user/ directory. Team ownership is clear: the user team owns the user stack. Domains can deploy independently (after shared infrastructure), and extracting a domain into a separate repository is straightforward if needed. Those properties pay off in microservices architectures and multi-team organizations, wherever the bounded contexts are already clear.
Single-Table Design compatibility: Domain-based organization pairs exceptionally well with DynamoDB Single-Table Design pattern. When a single table contains multiple entity types (User, Order, Payment), each domain can maintain its own access patterns and repository logic within its folder. For example, the user/ folder contains user-repository.ts with User-specific queries, while order/ folder has order-repository.ts managing Order access patterns, all against the same physical table. The table definition lives in shared/, while domains own only their access patterns.
Feature-Based Organization#
For product-focused teams, organizing by user-facing features makes more sense than technical domains.
// Directory structure
// cdk-project/
// ├── lib/
// │ ├── features/
// │ │ ├── authentication/
// │ │ │ ├── auth-stack.ts
// │ │ │ ├── cognito-pool.ts
// │ │ │ ├── auth-lambda.ts
// │ │ │ └── auth-api.ts
// │ │ ├── user-profile/
// │ │ │ ├── profile-stack.ts
// │ │ │ ├── profile-handler.ts
// │ │ │ └── profile-table.ts
// │ │ ├── notifications/
// │ │ │ ├── notification-stack.ts
// │ │ │ ├── sns-topics.ts
// │ │ │ ├── email-handler.ts
// │ │ │ └── sms-handler.ts
// │ │ └── search/
// │ │ ├── search-stack.ts
// │ │ ├── opensearch-domain.ts
// │ │ └── indexer-lambda.ts
// lib/features/notifications/notification-stack.ts
import { Stack, StackProps, Duration } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Topic } from 'aws-cdk-lib/aws-sns';
import { EmailSubscription, SmsSubscription, SqsSubscription, LambdaSubscription } from 'aws-cdk-lib/aws-sns-subscriptions';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { SqsEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
import { Queue } from 'aws-cdk-lib/aws-sqs';
export class NotificationStack extends Stack {
public readonly emailTopic: Topic;
public readonly smsTopic: Topic;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// Email notifications
this.emailTopic = new Topic(this, 'EmailTopic', {
displayName: 'Email Notifications'
});
const emailQueue = new Queue(this, 'EmailQueue', {
visibilityTimeout: Duration.seconds(300)
});
const emailHandler = new NodejsFunction(this, 'EmailHandler', {
entry: 'src/handlers/send-email.ts',
environment: {
SMTP_HOST: 'smtp.example.com'
}
});
emailHandler.addEventSource(new SqsEventSource(emailQueue));
this.emailTopic.addSubscription(new SqsSubscription(emailQueue));
// SMS notifications
this.smsTopic = new Topic(this, 'SmsTopic', {
displayName: 'SMS Notifications'
});
const smsHandler = new NodejsFunction(this, 'SmsHandler', {
entry: 'src/handlers/send-sms.ts'
});
this.smsTopic.addSubscription(new LambdaSubscription(smsHandler));
}
}
Feature folders pay off when features span multiple AWS services and domains, when teams are organized around product features rather than technical layers, and when the product needs features developed and deployed independently of each other.
Layer-Based Organization#
Layer-based organization separates infrastructure by technical layer, grouping resources by lifecycle and change frequency.
// Directory structure
// cdk-project/
// ├── lib/
// │ ├── layers/
// │ │ ├── foundation/
// │ │ │ ├── vpc-stack.ts
// │ │ │ ├── security-groups-stack.ts
// │ │ │ └── base-stack.ts
// │ │ ├── data/
// │ │ │ ├── rds-stack.ts
// │ │ │ ├── dynamodb-stack.ts
// │ │ │ └── s3-stack.ts
// │ │ ├── compute/
// │ │ │ ├── lambda-stack.ts
// │ │ │ ├── ecs-stack.ts
// │ │ │ └── batch-stack.ts
// │ │ └── api/
// │ │ ├── apigw-stack.ts
// │ │ └── alb-stack.ts
// bin/app.ts
import { App } from 'aws-cdk-lib';
import { FoundationStack } from '../lib/layers/foundation/vpc-stack';
import { DataStack } from '../lib/layers/data/dynamodb-stack';
import { ComputeStack } from '../lib/layers/compute/lambda-stack';
import { ApiStack } from '../lib/layers/api/apigw-stack';
const app = new App();
// Foundation layer - deployed once, rarely updated
const foundationStack = new FoundationStack(app, 'Foundation', {
env: { account: '123456789012', region: 'us-east-1' }
});
// Data layer - stateful, needs RETAIN removal policy
const dataStack = new DataStack(app, 'Data', {
env: { account: '123456789012', region: 'us-east-1' },
vpc: foundationStack.vpc
});
// Compute layer - stateless, frequently updated
const computeStack = new ComputeStack(app, 'Compute', {
env: { account: '123456789012', region: 'us-east-1' },
vpc: foundationStack.vpc,
tables: dataStack.tables
});
// API layer - deployment artifact, very frequent updates
const apiStack = new ApiStack(app, 'Api', {
env: { account: '123456789012', region: 'us-east-1' },
handlers: computeStack.handlers
});
// The props above already order the deploys: Foundation, Data, Compute, Api.
// Each cross-stack reference adds its dependency, so no addDependency calls.
Splitting by layer keeps stateful and stateless resources apart and lets each layer move at its own pace: foundation changes rarely, APIs change constantly. Deployment risk drops because the data layer rarely changes, and each layer can carry its own removal policy. The price is that business logic gets scattered across layers, team ownership is less clear, and deploying a complete feature means coordinating across several of them.
Hybrid Approach#
Real-world projects often benefit from combining patterns: layers for cross-cutting concerns, domains for business logic.
// Directory structure
// cdk-project/
// ├── lib/
// │ ├── foundation/
// │ │ ├── network-stack.ts // Shared VPC, subnets
// │ │ ├── security-stack.ts // Security groups, IAM roles
// │ │ └── monitoring-stack.ts // CloudWatch, X-Ray
// │ ├── domains/
// │ │ ├── user/
// │ │ │ ├── user-service-stack.ts
// │ │ │ └── constructs/
// │ │ │ ├── user-api.ts
// │ │ │ ├── user-storage.ts
// │ │ │ └── user-lambda.ts
// │ │ ├── order/
// │ │ │ ├── order-service-stack.ts
// │ │ │ └── constructs/
// │ │ └── payment/
// │ │ ├── payment-service-stack.ts
// │ │ └── constructs/
// │ ├── shared/
// │ │ ├── constructs/
// │ │ │ ├── api-endpoint.ts // Reusable L3 construct
// │ │ │ ├── lambda-factory.ts // Factory functions
// │ │ │ └── monitored-table.ts
// │ │ └── aspects/
// │ │ ├── tagging-aspect.ts
// │ │ ├── security-aspect.ts
// │ │ └── removal-policy-aspect.ts
// │ └── config/
// │ ├── environment.ts // Type-safe config
// │ ├── dev.ts
// │ ├── staging.ts
// │ └── prod.ts
// lib/foundation/network-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Vpc, SubnetType, GatewayVpcEndpointAwsService } from 'aws-cdk-lib/aws-ec2';
export class NetworkStack extends Stack {
public readonly vpc: Vpc;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
this.vpc = new Vpc(this, 'Vpc', {
maxAzs: 3,
natGateways: 1,
subnetConfiguration: [
{
cidrMask: 24,
name: 'public',
subnetType: SubnetType.PUBLIC
},
{
cidrMask: 24,
name: 'private',
subnetType: SubnetType.PRIVATE_WITH_EGRESS
},
{
cidrMask: 28,
name: 'isolated',
subnetType: SubnetType.PRIVATE_ISOLATED
}
]
});
// VPC endpoints save data transfer costs
this.vpc.addGatewayEndpoint('S3Endpoint', {
service: GatewayVpcEndpointAwsService.S3
});
this.vpc.addGatewayEndpoint('DynamoDBEndpoint', {
service: GatewayVpcEndpointAwsService.DYNAMODB
});
}
}
// lib/domains/user/user-service-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { IVpc } from 'aws-cdk-lib/aws-ec2';
export interface UserServiceStackProps extends StackProps {
readonly vpc: IVpc;
readonly monitoringDashboardName?: string;
}
export class UserServiceStack extends Stack {
public readonly apiEndpoint: string;
constructor(scope: Construct, id: string, props: UserServiceStackProps) {
super(scope, id, props);
// Use constructs to organize within the stack
const storage = new UserStorageConstruct(this, 'Storage', {
vpc: props.vpc
});
const compute = new UserComputeConstruct(this, 'Compute', {
vpc: props.vpc,
table: storage.table
});
const api = new UserApiConstruct(this, 'Api', {
handler: compute.handler
});
this.apiEndpoint = api.url;
}
}
// bin/app.ts
import { App } from 'aws-cdk-lib';
import { NetworkStack } from '../lib/foundation/network-stack';
import { UserServiceStack } from '../lib/domains/user/user-service-stack';
import { OrderServiceStack } from '../lib/domains/order/order-service-stack';
import { getConfig } from '../lib/config/environment';
const app = new App();
const config = getConfig(process.env.STAGE || 'dev');
// Foundation layer - deployed first, rarely changes
const network = new NetworkStack(app, 'Network', {
env: config.env
});
// Domain stacks - business logic, independent deployment
const userStack = new UserServiceStack(app, 'UserService', {
env: config.env,
vpc: network.vpc
});
const orderStack = new OrderServiceStack(app, 'OrderService', {
env: config.env,
vpc: network.vpc,
userApiEndpoint: userStack.apiEndpoint
});
Here the foundation layer handles cross-cutting concerns while the domain stacks keep business logic cohesive, and the dependency graph stays explicit enough for domains to deploy independently once the foundation is established.
Picking a Layout#
Team setup and the need for independent deploys decide the layout more than the AWS services involved. The table reads top to bottom as a growth path.
| Team setup | Independent deploys | Domain boundaries | Layout | Stacks |
|---|---|---|---|---|
| One team, a prototype or under 10 resources | Not needed | Not visible yet | Service-based or flat | One stack |
| One team, several business domains | Rarely | Emerging | Domain folders | One stack, one construct per domain |
| A separate team per business capability | Per domain | Clear | Domain-based | One stack per domain, plus a foundation stack |
| Product teams shipping features across domains | Per feature | Cut by features | Feature-based | One stack per feature, plus a foundation stack |
| A platform team owns network and data | Per layer | Any | Hybrid: layers below, domains above | Foundation and data stacks, then domain stacks |
The default lives on the second and third rows. Start on the second, and move to the third when a second team or a different release cadence appears. The case for a teammate fits in one sentence: a stack is a deploy boundary, so draw stacks where teams and release cadences differ and use constructs everywhere else.
Where to Draw Stack and Repo Boundaries#
When to Split Stacks vs Use Constructs#
One of the most common CDK questions is: “When should I create a new stack versus just using a construct?” The answer comes down to deployment independence.
Use multiple stacks when:
- Different teams will maintain different parts
- Different deployment schedules (data layer deploys monthly, compute layer deploys daily)
- Different environments or accounts (dev in one account, prod in another)
- Independent deployment is critical for CI/CD
- Approaching CloudFormation’s 500 resource limit per stack
- Different business domains with clear boundaries
- Stateful resources need different removal policies than stateless resources
Use constructs (not stacks) when:
- Only separating code ownership within the same team
- Resources change together and should deploy together
- No need for independent deployment
- Resources have tight coupling and many references
- Organizing purely for code maintainability
Here’s a decision tree example:
// Question 1: Do resources change together?
// YES → Single stack with constructs
// NO → Continue
// Question 2: Different teams maintaining?
// YES → Separate stacks
// NO → Continue
// Question 3: Different deployment schedules?
// YES → Separate stacks
// NO → Continue
// Question 4: Approaching 500 resources?
// YES → Separate stacks (or nested stacks)
// NO → Single stack with constructs
// Example: User service with API, Lambda, DynamoDB
// All change together, same team, deploy together → Single stack
export class UserServiceStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// Organize with constructs, not separate stacks
const storage = new UserStorageConstruct(this, 'Storage');
const compute = new UserComputeConstruct(this, 'Compute', {
table: storage.table
});
const api = new UserApiConstruct(this, 'Api', {
handler: compute.handler
});
}
}
// Example: Foundation (VPC) vs Application (Lambda/API)
// Different change frequency, different lifecycle → Separate stacks
const foundationStack = new FoundationStack(app, 'Foundation');
const appStack = new AppStack(app, 'App', {
vpc: foundationStack.vpc
});
// Passing vpc already makes App depend on Foundation; no addDependency call needed
Monorepo vs Multi-Repo Strategy#
The monorepo versus multi-repo decision affects how teams collaborate and deploy infrastructure.
Monorepo pattern:
// Directory structure
// company-infrastructure/ # Single repository
// ├── packages/
// │ ├── foundation/
// │ │ ├── src/
// │ │ │ └── network-stack.ts
// │ │ ├── package.json
// │ │ └── cdk.json
// │ ├── user-service/
// │ │ ├── src/
// │ │ │ └── user-stack.ts
// │ │ ├── package.json
// │ │ └── cdk.json
// │ ├── order-service/
// │ │ ├── src/
// │ │ │ └── order-stack.ts
// │ │ ├── package.json
// │ │ └── cdk.json
// │ └── shared-constructs/
// │ ├── src/
// │ │ ├── api-endpoint.ts
// │ │ └── lambda-factory.ts
// │ ├── package.json
// │ └── tsconfig.json
// ├── package.json # Root package.json
// ├── nx.json # NX workspace config
// └── tsconfig.base.json
// package.json (root)
{
"name": "company-infrastructure",
"private": true,
"workspaces": ["packages/*"],
"scripts": {
"build": "nx run-many --target=build --all",
"deploy:dev": "nx run-many --target=deploy --all --args='--context stage=dev'",
"deploy:user": "nx run user-service:deploy"
},
"devDependencies": {
"nx": "^17.0.0",
"aws-cdk": "^2.100.0"
}
}
A monorepo buys a single source of truth: atomic changes across services, shared constructs without publishing to npm, easier refactoring across boundaries, simpler dependency management, and one CI/CD pipeline configuration. What it costs is slower clones, a standing risk of tight coupling between services, pipeline logic to detect which service actually changed, coarser team permissions, and a wider deployment blast radius.
Multi-repo flips both sides. Separate repositories per service, with shared constructs published to a private npm registry, give you clear service boundaries, independent versioning and deployment, obvious ownership and permissions, smaller checkouts, and room for language diversity. In exchange, cross-service changes need multiple PRs, shared constructs need publishing and versioning, dependency versions get harder to manage, consistency is harder to enforce, and every service carries its own pipeline overhead.
Recommendation: Start with a monorepo for teams under 10 people. The simplicity of atomic changes and shared constructs outweighs the drawbacks at small scale. Split to multi-repo when team size or deployment independence demands it: usually around 50+ engineers or when there are truly independent services with different lifecycles.
What Lives Below the Domains#
Networking, security, monitoring, and other cross-cutting concerns don’t fit cleanly into domain boundaries.
Foundation Stack Pattern#
// lib/foundation/foundation-stack.ts
import { Stack, StackProps, Tags } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Vpc, IVpc, SubnetType, SecurityGroup } from 'aws-cdk-lib/aws-ec2';
import { Dashboard, GraphWidget } from 'aws-cdk-lib/aws-cloudwatch';
export interface FoundationStackProps extends StackProps {
readonly stage: string;
}
export class FoundationStack extends Stack {
public readonly vpc: IVpc;
public readonly monitoring: Dashboard;
public readonly lambdaSecurityGroup: SecurityGroup;
constructor(scope: Construct, id: string, props: FoundationStackProps) {
super(scope, id, props);
// VPC with standard subnets
this.vpc = new Vpc(this, 'Vpc', {
maxAzs: 3,
natGateways: props.stage === 'prod' ? 3 : 1,
subnetConfiguration: [
{
cidrMask: 24,
name: 'public',
subnetType: SubnetType.PUBLIC
},
{
cidrMask: 24,
name: 'private',
subnetType: SubnetType.PRIVATE_WITH_EGRESS
},
{
cidrMask: 28,
name: 'isolated',
subnetType: SubnetType.PRIVATE_ISOLATED
}
]
});
// Centralized monitoring dashboard
this.monitoring = new Dashboard(this, 'Monitoring', {
dashboardName: `${props.stage}-metrics`
});
// Standard security group for Lambda functions
this.lambdaSecurityGroup = new SecurityGroup(this, 'LambdaSG', {
vpc: this.vpc,
description: 'Security group for Lambda functions',
allowAllOutbound: true
});
// Apply tags to everything in this stack
Tags.of(this).add('Environment', props.stage);
Tags.of(this).add('ManagedBy', 'CDK');
Tags.of(this).add('CostCenter', 'Engineering');
}
}
// Domain stacks consume foundation
export class UserServiceStack extends Stack {
constructor(
scope: Construct,
id: string,
props: StackProps & { foundation: FoundationStack }
) {
super(scope, id, props);
const handler = new NodejsFunction(this, 'Handler', {
vpc: props.foundation.vpc,
securityGroups: [props.foundation.lambdaSecurityGroup],
entry: 'src/handlers/user.ts'
});
// Add Lambda metrics to centralized dashboard
props.foundation.monitoring.addWidgets(
new GraphWidget({
title: 'User Service Invocations',
left: [handler.metricInvocations()]
})
);
}
}
CDK Aspects for Cross-Cutting Policies#
CDK Aspects visit every construct in a scope during synthesis. AWS recommends them for validating removal and logging policies, so the aspect below reports violations and leaves the fix to the code that owns the resource.
// lib/shared/aspects/security-compliance-aspect.ts
import { App, Annotations, Aspects, CfnDeletionPolicy, IAspect, Tokenization } from 'aws-cdk-lib';
import { IConstruct } from 'constructs';
import { CfnTable } from 'aws-cdk-lib/aws-dynamodb';
import { CfnFunction } from 'aws-cdk-lib/aws-lambda';
export class SecurityComplianceAspect implements IAspect {
visit(node: IConstruct): void {
// Stateful data must survive stack deletion and resource replacement
if (node instanceof CfnTable) {
if (node.cfnOptions.deletionPolicy !== CfnDeletionPolicy.RETAIN) {
Annotations.of(node).addError('DynamoDB tables must use RemovalPolicy.RETAIN');
}
}
// Every function should log to a log group whose retention is set in code.
// CfnFunction also covers NodejsFunction, which extends lambda.Function.
if (node instanceof CfnFunction) {
const logging = node.loggingConfig;
if (!logging || (!Tokenization.isResolvable(logging) && !logging.logGroup)) {
Annotations.of(node).addWarningV2(
'compliance:lambda-log-group',
'Set the logGroup prop so log retention is defined in code'
);
}
}
}
}
// Apply to entire app
const app = new App();
Aspects.of(app).add(new SecurityComplianceAspect());
An error from addError fails the synth, and the CLI will not deploy a stack that carries one. A warning from addWarningV2 only prints, unless you synthesize with --strict, and a team can acknowledge it on a construct it does not control, such as a function that a library construct creates internally. The fix for the log group lives in the shared MonitoredLambda construct below, which passes its own log group through the logGroup prop. Creating a log group named /aws/lambda/<function name> from inside an aspect is the trap to avoid: Lambda creates that group on the function’s first invocation, so the stack may try to create a log group that already exists. There is no S3 branch either. Since January 5, 2023, Amazon S3 encrypts every new object with SSE-S3 by default.
Shared Constructs Library#
Create reusable L3 constructs that encapsulate best practices. Factory patterns and functional composition take these constructs further; AWS CDK Functional Patterns covers that ground.
// lib/shared/constructs/monitored-lambda.ts
import { Construct } from 'constructs';
import { NodejsFunction, NodejsFunctionProps } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Alarm, ComparisonOperator } from 'aws-cdk-lib/aws-cloudwatch';
import { Topic } from 'aws-cdk-lib/aws-sns';
import { EmailSubscription } from 'aws-cdk-lib/aws-sns-subscriptions';
import { SnsAction } from 'aws-cdk-lib/aws-cloudwatch-actions';
import { Tracing } from 'aws-cdk-lib/aws-lambda';
import { LogGroup, RetentionDays } from 'aws-cdk-lib/aws-logs';
export interface MonitoredLambdaProps extends NodejsFunctionProps {
readonly alarmEmail?: string;
readonly errorThreshold?: number;
}
export class MonitoredLambda extends Construct {
public readonly function: NodejsFunction;
public readonly errorAlarm: Alarm;
public readonly throttleAlarm: Alarm;
constructor(scope: Construct, id: string, props: MonitoredLambdaProps) {
super(scope, id);
this.function = new NodejsFunction(this, 'Function', {
...props,
// Own log group with explicit retention, which satisfies the aspect above
logGroup: props.logGroup ?? new LogGroup(this, 'LogGroup', {
retention: RetentionDays.ONE_MONTH
}),
tracing: Tracing.ACTIVE // Enable X-Ray by default
});
// Automatic error alarm
this.errorAlarm = new Alarm(this, 'ErrorAlarm', {
metric: this.function.metricErrors(),
threshold: props.errorThreshold ?? 5,
evaluationPeriods: 2,
comparisonOperator: ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
alarmDescription: `Errors on ${this.function.functionName}`
});
// Automatic throttle alarm
this.throttleAlarm = new Alarm(this, 'ThrottleAlarm', {
metric: this.function.metricThrottles(),
threshold: 1,
evaluationPeriods: 1,
comparisonOperator: ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
alarmDescription: `Throttles on ${this.function.functionName}`
});
// Optional SNS notification
if (props.alarmEmail) {
const topic = new Topic(this, 'AlarmTopic');
topic.addSubscription(new EmailSubscription(props.alarmEmail));
this.errorAlarm.addAlarmAction(new SnsAction(topic));
this.throttleAlarm.addAlarmAction(new SnsAction(topic));
}
}
}
// Usage in any domain stack
const handler = new MonitoredLambda(this, 'Handler', {
entry: 'src/handlers/user.ts',
alarmEmail: 'oncall@example.com',
errorThreshold: 10
});
Environments Created at Synth Time#
Managing dev, staging, and prod takes a deliberate configuration strategy. AWS recommends modeling every production stage in code, so each environment becomes a stack whose configuration lives in the repository.
// config/environment.ts
export interface EnvironmentConfig {
readonly stage: 'dev' | 'staging' | 'prod';
readonly account: string;
readonly region: string;
readonly vpcCidr: string;
readonly lambdaDefaults: {
readonly timeout: number;
readonly memorySize: number;
};
readonly enableDetailedMonitoring: boolean;
}
// config/dev.ts
export const devConfig: EnvironmentConfig = {
stage: 'dev',
account: '111111111111',
region: 'us-east-1',
vpcCidr: '10.0.0.0/16',
lambdaDefaults: {
timeout: 30,
memorySize: 512
},
enableDetailedMonitoring: false
};
// config/prod.ts
export const prodConfig: EnvironmentConfig = {
stage: 'prod',
account: '222222222222',
region: 'us-east-1',
vpcCidr: '10.1.0.0/16',
lambdaDefaults: {
timeout: 60,
memorySize: 1024
},
enableDetailedMonitoring: true
};
// bin/app.ts
import { App } from 'aws-cdk-lib';
import { devConfig, stagingConfig, prodConfig } from '../config';
import { UserServiceStack } from '../lib/domains/user/user-service-stack';
const app = new App();
// Create all environments during synthesis
[devConfig, stagingConfig, prodConfig].forEach(config => {
new UserServiceStack(app, `UserService-${config.stage}`, {
env: { account: config.account, region: config.region },
config
});
});
// What this gives you:
// - One synth writes a separate template per environment to cdk.out
// - Dev and prod share construct code; only the config values differ
// - TypeScript checks every environment's config during development
// - `cdk list` shows all stacks across all environments
//
// What it costs:
// - Each stack pins a real account, so lookups such as Vpc.fromLookup
// query every account during synth. A local synth then needs prod
// credentials, or a committed cdk.context.json that already holds the values
A missing field or a wrong type in the production config fails the local cdk synth, long before a production deploy. The lookup cost is the trade-off to plan for. Commit cdk.context.json so synthesis stays deterministic and developers do not need production credentials for every synth, and refresh single entries on purpose with cdk context --reset. A pipeline’s synth step has no permission to run lookups by default, which is one more reason to commit the file. When an account must run lookups against prod without being able to deploy there, cdk bootstrap --trust-for-lookup grants exactly that.
Once an environment consists of more than one stack, wrap those stacks in a Stage and let CDK Pipelines promote it. The pipeline runs cdk synth once in its synth step and deploys the resulting cloud assembly stage by stage, so prod deploys from the same synth run that dev already received. Aspects added to the App stop at a Stage boundary, so the stage below adds the compliance aspect from the previous section itself.
// lib/user-service-stage.ts
import { Aspects, Stage, StageProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { EnvironmentConfig } from '../config/environment';
import { SecurityComplianceAspect } from './shared/aspects/security-compliance-aspect';
import { UserServiceStack } from './domains/user/user-service-stack';
export interface UserServiceStageProps extends StageProps {
readonly config: EnvironmentConfig;
}
export class UserServiceStage extends Stage {
constructor(scope: Construct, id: string, props: UserServiceStageProps) {
super(scope, id, props);
// Stacks inside a stage inherit its env
new UserServiceStack(this, 'UserService', { config: props.config });
// App-level aspects do not reach into a Stage
Aspects.of(this).add(new SecurityComplianceAspect());
}
}
// lib/pipeline-stack.ts
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { CodePipeline, CodePipelineSource, ManualApprovalStep, ShellStep } from 'aws-cdk-lib/pipelines';
import { devConfig, prodConfig } from '../config';
import { UserServiceStage } from './user-service-stage';
// The pipeline deploys to other accounts, so its own stack needs an explicit env:
// bin/app.ts: new PipelineStack(app, 'Pipeline', { env: { account: '<tooling account>', region: 'us-east-1' } })
export class PipelineStack extends Stack {
constructor(scope: Construct, id: string, props: StackProps) {
super(scope, id, props);
const pipeline = new CodePipeline(this, 'Pipeline', {
// Dev and prod live in other accounts: encrypt the artifact bucket with a KMS key
crossAccountKeys: true,
synth: new ShellStep('Synth', {
input: CodePipelineSource.gitHub('OWNER/REPO', 'main'),
commands: ['npm ci', 'npm run build', 'npx cdk synth']
})
});
for (const config of [devConfig, prodConfig]) {
const deployment = pipeline.addStage(new UserServiceStage(this, config.stage, {
env: { account: config.account, region: config.region },
config
}));
if (config.stage === 'prod') {
deployment.addPre(new ManualApprovalStep('PromoteToProd'));
}
}
}
}
Deploying to another account needs crossAccountKeys: true, which encrypts the artifact bucket with a KMS key that has its own running cost. Each target account also has to trust the pipeline account: bootstrap it with cdk bootstrap --trust <pipeline account> --cloudformation-execution-policies <policy ARN>. Anyone with access to a trusted account gets every permission those execution policies grant, so keep the trust list short.
Splitting, Cycles, and Logical IDs#
Premature Stack Splitting#
Creating too many small stacks leads to excessive cross-stack references and deployment complexity.
// Over-splitting - 6 stacks for one service (don't do this)
const vpcStack = new VpcStack(app, 'Vpc');
const sgStack = new SecurityGroupStack(app, 'SG', { vpc: vpcStack.vpc });
const tableStack = new TableStack(app, 'Table');
const lambdaStack = new LambdaStack(app, 'Lambda', {
table: tableStack.table,
sg: sgStack.lambdaSG
});
const apiStack = new ApiStack(app, 'Api', { handler: lambdaStack.handler });
const alarmStack = new AlarmStack(app, 'Alarm', {
lambda: lambdaStack.handler,
api: apiStack.api
});
// Every change requires deploying 6 stacks in correct order
// Cross-stack references create fragile dependencies
// Better: Single stack with constructs for organization
export class UserServiceStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const network = new NetworkConstruct(this, 'Network');
const storage = new StorageConstruct(this, 'Storage');
const compute = new ComputeConstruct(this, 'Compute', {
table: storage.table,
vpc: network.vpc
});
const api = new ApiConstruct(this, 'Api', { handler: compute.handler });
const monitoring = new MonitoringConstruct(this, 'Monitoring', {
lambda: compute.handler,
api: api.restApi
});
}
}
// Deploy once, all resources update together
Start with larger stacks and split only when there’s a clear reason: different teams, different lifecycles, or approaching resource limits.
Circular Dependencies#
Circular dependencies between stacks are a common issue when designing resource relationships.
// Circular dependency problem (don't do this)
export class UserStack extends Stack {
public readonly apiUrl: string;
constructor(scope: Construct, id: string, props: { orderTable: ITable }) {
super(scope, id);
// User service needs order table ← dependency on OrderStack
const handler = new NodejsFunction(this, 'Handler', {
environment: { ORDER_TABLE: props.orderTable.tableName }
});
const api = new RestApi(this, 'UserApi', {/* routes to handler */});
this.apiUrl = api.url;
}
}
export class OrderStack extends Stack {
public readonly table: Table;
constructor(scope: Construct, id: string, props: { userApiUrl: string }) {
super(scope, id);
// Order service needs user API ← dependency on UserStack
const handler = new NodejsFunction(this, 'Handler', {
environment: { USER_API_URL: props.userApiUrl }
});
this.table = new Table(/*...*/);
}
}
// Cannot instantiate either stack first!
There are two ways out, and both keep each table with the domain that owns it. The first keeps one direction as a normal reference and moves the other to runtime. OrderStack still receives the user API URL. UserStack stops reading Order’s table and calls Order’s API, whose URL OrderStack publishes under a fixed parameter name.
// Solution 1: one deploy-time reference, one runtime lookup
export class OrderStack extends Stack {
constructor(scope: Construct, id: string, props: StackProps & { userApiUrl: string }) {
super(scope, id, props);
const handler = new NodejsFunction(this, 'Handler', {
entry: 'src/handlers/order.ts',
environment: { USER_API_URL: props.userApiUrl }
});
const api = new RestApi(this, 'OrderApi', {/* routes to handler */});
// Publish the URL under a name both teams agree on
new StringParameter(this, 'ApiUrlParameter', {
parameterName: '/order-service/api-url',
stringValue: api.url
});
}
}
export class UserStack extends Stack {
public readonly apiUrl: string;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// Only the parameter name crosses the boundary; the handler reads the URL at runtime
const handler = new NodejsFunction(this, 'Handler', {
entry: 'src/handlers/user.ts',
environment: { ORDER_API_URL_PARAMETER: '/order-service/api-url' }
});
StringParameter.fromStringParameterName(this, 'OrderApiUrl', '/order-service/api-url')
.grantRead(handler);
const api = new RestApi(this, 'UserApi', {/* routes to handler */});
this.apiUrl = api.url;
}
}
// bin/app.ts: the reference now points one way only
const userStack = new UserStack(app, 'User');
const orderStack = new OrderStack(app, 'Order', { userApiUrl: userStack.apiUrl });
The second way removes both references. The services exchange events through EventBridge or SQS, and neither stack needs the other’s outputs. Moving Order’s table into a shared foundation stack also breaks the cycle, but it takes ownership of the table away from the Order team. Keep the foundation stack for infrastructure that is shared by nature, such as the VPC or a hosted zone.
Cross-Account/Region References#
Stacks in different accounts or Regions cannot share a value through Fn::ImportValue, because CloudFormation exports only work inside one account and Region. A common workaround writes the value to SSM Parameter Store in the producing account and reads it in the consumer with StringParameter.valueFromLookup. Across accounts, that lookup cannot succeed. It runs during synthesis against the consuming stack’s own account and Region, where the parameter does not exist, so the synth fails, or returns the dummy default if you passed one. Standard parameters cannot be shared with other accounts at all; sharing a parameter needs the advanced tier and an AWS RAM resource share.
Current CDK v2 releases pass the reference directly. Within one account, a cross-region reference goes through a writer and reader pair that CDK manages; earlier releases needed crossRegionReferences: true on the stack for this. Across accounts, CDK falls back to a weak reference: the consuming stack reads the producer’s output with CloudFormation’s Fn::GetStackOutput, through an IAM role that CDK adds to the producing stack. A weak reference does not stop anyone from deleting the producer, so protect that stack yourself. Resources whose ARN contains their name, such as a DynamoDB table, cannot use either mechanism: they need an explicit physical name or PhysicalName.GENERATE_IF_NEEDED, otherwise synth fails with a ‘cross-environment fashion’ error. With one, CDK writes the ARN straight into the consumer’s template.
Passing the ARN is half of the work. The table still lives in the other account, and DynamoDB allows cross-account access only when both sides agree: a resource-based policy on the table and an identity-based policy on the caller.
// lib/data-stack.ts (account 111111111111, us-east-1)
import { PhysicalName, Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { AttributeType, BillingMode, Table } from 'aws-cdk-lib/aws-dynamodb';
import { AccountPrincipal, PolicyStatement } from 'aws-cdk-lib/aws-iam';
export interface DataStackProps extends StackProps {
readonly consumerAccount: string;
}
export class DataStack extends Stack {
public readonly table: Table;
constructor(scope: Construct, id: string, props: DataStackProps) {
super(scope, id, props);
this.table = new Table(this, 'Table', {
// Lets CDK compute the table ARN for stacks in other accounts
tableName: PhysicalName.GENERATE_IF_NEEDED,
partitionKey: { name: 'pk', type: AttributeType.STRING },
billingMode: BillingMode.PAY_PER_REQUEST
});
// Resource-based policy: the owning account lets the consumer account in
this.table.addToResourcePolicy(new PolicyStatement({
principals: [new AccountPrincipal(props.consumerAccount)],
actions: ['dynamodb:GetItem', 'dynamodb:Query'],
resources: ['*'] // the table itself; avoids a self-reference
}));
}
}
// lib/app-stack.ts (account 222222222222, eu-west-1)
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { ITable } from 'aws-cdk-lib/aws-dynamodb';
import { PolicyStatement } from 'aws-cdk-lib/aws-iam';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
export interface AppStackProps extends StackProps {
readonly table: ITable;
}
export class AppStack extends Stack {
constructor(scope: Construct, id: string, props: AppStackProps) {
super(scope, id, props);
const handler = new NodejsFunction(this, 'Handler', {
entry: 'src/handlers/app.ts',
// The SDK accepts the full table ARN for cross-account calls
environment: { TABLE_ARN: props.table.tableArn }
});
// Identity-based policy: the consumer's role may call the table
handler.addToRolePolicy(new PolicyStatement({
actions: ['dynamodb:GetItem', 'dynamodb:Query'],
resources: [props.table.tableArn]
}));
}
}
// bin/app.ts
const dataStack = new DataStack(app, 'Data', {
env: { account: '111111111111', region: 'us-east-1' },
consumerAccount: '222222222222'
});
const appStack = new AppStack(app, 'App', {
env: { account: '222222222222', region: 'eu-west-1' },
table: dataStack.table
});
// A cross-account reference adds no deploy order, so declare it
appStack.addStackDependency(dataStack);
Two details in this setup are easy to miss. The generated physical name is fixed once the table exists, so a change that replaces the table needs a new name. And unlike same-account references, a cross-account reference does not order the deploys, so the explicit addStackDependency is what keeps the consumer from deploying before the table exists.
Logical IDs and the Refactor Command#
CloudFormation tracks every resource by its logical ID, and CDK derives that ID from the construct path. It joins the path components below the stack and appends an 8-character hash of the path. A table created as new Table(this, 'UserTable', ...) directly in a stack synthesizes as UserTableBD4BF69E. Rename the construct or wrap it in a new construct, and the logical ID changes. Move it to another stack, and the ID may stay the same while the owning stack changes.
// Before: service-based layout, the table lives in DynamoDBStack
new Table(this, 'UserTable', {/*...*/});
// Template: DynamoDBStack, logical ID UserTableBD4BF69E
// After: domain-based layout, the same code moved into UserStack
new Table(this, 'UserTable', {/*...*/});
// Template: UserStack, logical ID UserTableBD4BF69E
// Same logical ID, different stack: CloudFormation sees a new table
// in UserStack and a removed table in DynamoDBStack
A logical ID is unique only within its stack. Keeping the old construct ID, or pinning the old logical ID with overrideLogicalId, works for a rename inside one stack and does nothing for a move between stacks. On a plain deploy, UserStack creates a second, empty table. DynamoDBStack then drops the old table from its template, and because Table defaults to RemovalPolicy.RETAIN, CloudFormation leaves it in the account with all its data and no stack managing it. If the table has a fixed tableName, the create fails instead, because the old table still holds the name.
cdk refactor handles the move. It is in preview, so every call needs --unstable=refactor. The command compares the synthesized app with the deployed stacks and works out which resources moved or were renamed. It then shows the mapping and, after confirmation, uses CloudFormation’s refactoring API to change logical IDs and stack membership without replacing anything.
# 1. Before touching the layout, deploy all pending changes
cdk deploy --all
# 2. Move the table in code, then preview the mapping without applying it
cdk refactor --unstable=refactor --dry-run
# 3. Apply the mapping, then continue with normal deploys
cdk refactor --unstable=refactor
cdk deploy --all
The command rejects a run in which any resource is added, deleted, or modified, so property changes go into a separate deploy. Moves work only between stacks in the same account and Region. When two identical resources move at once and the mapping is ambiguous, --override-file takes explicit <stack name>.<logical ID> pairs. The feature needs new permissions in the bootstrap stack, so run cdk bootstrap with a recent CLI before the first refactor.
When the Default Holds#
The domain-based default is worth keeping when teams map to business capabilities, when domains deploy on different cadences, and when the project will outgrow a single team. Inside it, reach for a construct rather than a new stack whenever resources change together.
A single-team project with one business domain, or a prototype under about 10 resources, gains nothing from domain folders, and service-based grouping stays readable at that size. Product teams that ship user-facing features across several domains do better with feature folders, because a feature is the unit they actually deploy. Organizations with a separate platform team usually need layer-based stacks so the stateful data layer can carry its own removal policies and change cadence. Whichever direction you move, treat logical IDs as part of the migration: run cdk refactor for every move or rename, and keep property changes in a separate deploy.
References#
- AWS CDK Best Practices (opens in new tab) - Official guidance on organizing CDK apps, modeling every stage in code, committing
cdk.context.json, and validating removal and logging policies with Aspects - Organize Code for Large-Scale CDK Projects (opens in new tab) - AWS Prescriptive Guidance on folder structure and code organization for TypeScript CDK projects
- Working with CDK in TypeScript (opens in new tab) - TypeScript setup, project layout, and CDK application structure
- Best Practices for Scaling CDK Adoption (opens in new tab) - AWS DevOps Blog post covering multi-team CDK project structures and sharing constructs
- Best Practices for Developing Cloud Applications with CDK (opens in new tab) - AWS DevOps Blog post on construct boundaries, testing, and deployment pipelines
- Aspects and the AWS CDK (opens in new tab) - How aspects visit constructs, why an error annotation fails the synth, and why aspects stop at a Stage boundary
- Annotations API Reference (opens in new tab) -
addError,addWarningV2, acknowledgeable warnings, and the--strictmode - 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 - Amazon S3 Default Encryption FAQ (opens in new tab) - SSE-S3 applied to all new object uploads since January 5, 2023
- Context Values and the AWS CDK (opens in new tab) - How lookups such as
valueFromLookupquery the target environment, howcdk.context.jsoncaches the results, andcdk context --reset - CDK Pipelines API Reference (opens in new tab) - Synth step, stages, manual approval steps, and context lookups inside a pipeline
- Fn::GetStackOutput (opens in new tab) - CloudFormation’s weak, cross-account and cross-region stack output reference, compared with
Fn::ImportValue, and how the CDK uses it - Sharing a Parameter in Parameter Store (opens in new tab) - Cross-account sharing limited to advanced-tier parameters through AWS RAM
- Cross-Account Access with Resource-Based Policies in DynamoDB (opens in new tab) - Why cross-account table access needs both a resource-based and an identity-based policy, and full table ARNs in API calls
- DynamoDB Table API Reference (opens in new tab) -
RemovalPolicy.RETAINdefault,resourcePolicy, andaddToResourcePolicy - Logical IDs in the AWS CDK (opens in new tab) - How the CDK builds logical IDs from the construct path and an 8-character hash
- Preserve Deployed Resources When Refactoring CDK Code (opens in new tab) - The
cdk refactorworkflow, its same-environment limit, override files, and bootstrap requirements - cdk refactor Command Reference (opens in new tab) - Options for
cdk refactor, including--dry-runand--override-file
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
How factory functions, higher-order functions, and composition turn AWS CDK into a type-safe, reusable infrastructure toolkit that prevents configuration drift.
aws-cdk · typescript · infrastructure-as-code +2
A comprehensive introduction to Domain-Driven Design: core concepts, building blocks, strategic patterns, and when and how to apply DDD in practice.
domain-driven-design · architecture · design-patterns +2
A presentation service is the thin backend behind a UI fragment. Ports-and-adapters keeps it from rotting into glue code by pointing dependencies inward.
architecture · nodejs · typescript +3
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