Use AWS SAM when: (1) Pure serverless stack (Lambda, API Gateway, DynamoDB, EventBridge, SNS, SQS - no EC2, RDS, VPCs) - SAM abstracts serverless complexity (10 lines SAM vs 100 lines CloudFormation). (2) Local development priority - sam local start-api runs API Gateway + Lambda locally (Docker-based), sam local invoke tests functions with mock events. (3) Simpler learning curve - template-based YAML/JSON with serverless-specific transforms. (4) Rapid prototyping - sam init scaffolds production-ready structure in seconds.
AWS Sam Vs Cdk FAQ & Answers
16 expert AWS Sam Vs Cdk answers researched from official documentation. Every answer cites authoritative sources you can verify.
General
16 questionsUse AWS CDK when: (1) Multi-service infrastructure - serverless + containers (ECS/Fargate) + databases (RDS, Aurora) + networking (VPCs, ALB) + data pipelines. CDK handles full AWS service catalog. (2) Complex logic in IaC - loops, conditionals, helper functions in TypeScript/Python/Java/C#. (3) Reusable constructs - build custom L2/L3 constructs (higher-level abstractions). (4) Type safety - compile-time type checking prevents misconfiguration. (5) Multi-cloud patterns - CDK for Terraform (CDKTF) enables AWS, Azure, GCP with same syntax.
The 2025 recommended hybrid approach: (1) Write IaC in CDK (TypeScript/Python), synth to CloudFormation template: cdk synth > template.yaml. (2) Use SAM CLI for local testing: sam local start-api --template template.yaml. (3) Deploy via CDK: cdk deploy. Benefits: CDK's powerful abstractions + SAM's local dev tools. Both compile to CloudFormation - deployment speed identical. SAM local dev has ~2x faster startup than CDK local due to less abstraction overhead.
AWS CDK has three construct levels: L1 (Low-level) - Direct CloudFormation resource mapping with Cfn prefix (e.g., CfnTable, CfnFunction). Use only when L2/L3 unavailable. L2 (Mid-level) - AWS resources with higher-level intent-based API, sensible defaults, and best practices built-in. No Cfn prefix (e.g., Table, Function). L3 (Patterns) - Complete architectures involving multiple resources (e.g., ApplicationLoadBalancedFargateService creates ECS cluster, Fargate service, ALB, and networking in one construct).
The Globals section defines properties common to all serverless resources, avoiding duplication. Supported resources: Function (Runtime, MemorySize, Timeout, VpcConfig, Environment, Layers, Architectures), Api (Auth, Cors, EndpointConfiguration), HttpApi (Auth, CorsConfiguration), SimpleTable (SSESpecification). Override behavior: primitive types (strings) are replaced by resource-level values, maps are merged (resource wins on conflict), lists are prepended (globals first). Example: set Runtime: python3.12 globally, override per-function only when needed.
sam local start-api runs Lambda functions locally through a local HTTP server that mimics API Gateway. By default, creates HTTP server on localhost (127.0.0.1). Supports --warm-containers option with two modes: eager (all containers loaded at startup) or lazy (containers loaded on first invoke, then persist). Automatically invokes Lambda authorizers before function endpoints. Use --invoke-image to reference custom container images instead of default Lambda base images from Amazon ECR.
sam local invoke initiates a one-time invocation of a Lambda function locally using Docker. Key options: --event (-e) to pass JSON event file, --env-vars to set environment variables from JSON file, --docker-network to specify Docker network for container, --skip-pull-image to use local Docker image without pulling latest. Useful for testing individual function logic with specific events before deployment. Each invocation creates new container by default unless --warm-containers is used.
AWS SAM provides six serverless resource types: AWS::Serverless::Function (Lambda functions with event sources), AWS::Serverless::Api (REST API Gateway), AWS::Serverless::HttpApi (HTTP API Gateway v2), AWS::Serverless::SimpleTable (simplified DynamoDB), AWS::Serverless::LayerVersion (Lambda layers), AWS::Serverless::Application (nested applications from SAR). SAM templates also support all standard CloudFormation resources for non-serverless components.
AWS::Serverless::Function always generates AWS::Lambda::Function. Additional resources based on configuration: Api event without RestApiId generates AWS::ApiGateway::RestApi. HttpApi event without ApiId generates AWS::ApiGatewayV2::Api. DynamoDB/Kinesis/MQ/MSK/SQS events generate AWS::Lambda::EventSourceMapping. AutoPublishAlias generates AWS::Lambda::Version and AWS::Lambda::Alias. DeploymentPreference generates AWS::CodeDeploy::Application, AWS::CodeDeploy::DeploymentGroup, and AWS::IAM::Role.
AWS CDK officially supports five programming languages: TypeScript (most popular, best documentation), JavaScript, Python, Java, and C#/.NET. Go support is in developer preview. All languages produce identical CloudFormation output - choose based on team expertise. TypeScript recommended for new projects due to best IDE support, most examples, and fastest new feature adoption. CDK uses jsii to generate bindings for non-TypeScript languages.
Create custom constructs by extending the Construct base class. L2 constructs: extend Construct, wrap L1 resources with sensible defaults and validation. L3 patterns: compose multiple L2 constructs into reusable architectures. Best practices: (1) Accept props interface for configuration. (2) Expose underlying resources via public properties. (3) Use CDK's built-in validation (Validators). (4) Document with JSDoc/docstrings. Publish via npm/PyPI or use AWS CDK Construct Hub for discoverability.
sam local start-lambda starts a local endpoint that emulates AWS Lambda's invoke endpoint. Use for testing Lambda functions directly without API Gateway, through AWS SDKs or CLI. Example: aws lambda invoke --function-name MyFunction --endpoint-url http://127.0.0.1:3001 --payload '{}' response.json. Useful for Step Functions local testing, direct SDK invocations, and integration tests that call Lambda directly. Default port is 3001.
cdk synth synthesizes CDK code into CloudFormation templates. Output goes to cdk.out/ directory by default. Key uses: (1) Generate template.yaml for SAM CLI local testing. (2) Review generated CloudFormation before deployment. (3) CI/CD pipelines that deploy CloudFormation directly. (4) Debugging - see exactly what resources CDK will create. Options: --output to specify directory, --quiet to suppress output, specific stack name to synth single stack. Always run cdk synth before cdk deploy in CI/CD for validation.
SAM policy templates are pre-built IAM policy templates for common serverless patterns. Examples: DynamoDBCrudPolicy (CRUD on specific table), S3ReadPolicy (read from bucket), SQSPollerPolicy (receive/delete from queue), KinesisStreamReadPolicy (read from stream), SNSPublishMessagePolicy (publish to topic). Usage: Policies: - DynamoDBCrudPolicy: TableName: !Ref MyTable. Reduces IAM complexity and follows least-privilege. Over 50 templates available covering most serverless use cases.
CDK automatically manages cross-stack references using CloudFormation exports and imports. When Stack A uses a resource from Stack B, CDK: (1) Creates CfnOutput export in Stack B. (2) Uses Fn::ImportValue in Stack A. (3) Establishes deployment dependency (Stack B deploys before Stack A). Access via: otherStack.vpc or pass as construct prop. For complex scenarios, use CfnOutput explicitly with exportName. Cross-region references require custom resources or SSM Parameter Store.
SAM Accelerate (sam sync) provides rapid iterative development by synchronizing local changes to AWS without full CloudFormation deployments. Two modes: (1) --code syncs only code changes (Lambda, Step Functions) in seconds. (2) --watch monitors files and auto-syncs changes. Bypasses CloudFormation for code-only updates, reducing deploy time from minutes to seconds. Infrastructure changes still require full sam deploy. Available since SAM CLI 1.53.0.