
Aws Solution Architect
- 1.5k installs
- 23.5k repo stars
- Updated July 17, 2026
- alirezarezvani/claude-skills
Design AWS architectures for startups using serverless patterns and IaC templates. Use when asked to design serverless architecture, create CloudFormation templates, optimize AWS costs, set up CI/CD p
About
The aws solution architect skill Design AWS architectures for startups using serverless patterns and IaC templates. Use when asked to design serverless architecture, create CloudFormation templates, optimize AWS costs, set up CI/CD pipelines, or migrate to AWS. Covers Lambda, API Gateway, DynamoDB, ECS, Aurora, and cost optimization. Documentation covers workflows, commands, and guardrails agents should follow when users invoke this capability. Key documented areas include Application type (web app, mobile backend, data pipeline, SaaS); Expected users and requests per second; Budget constraints (monthly spend limit); Team size and AWS experience level. Reference commands include - Application type (web app, mobile backend, data pipeline, SaaS); - Expected users and requests per second. Use when developers or agents need structured guidance for aws solution architect tasks with evidence grounded in the bundled SKILL.md rather than generic advice.
- Application type (web app, mobile backend, data pipeline, SaaS)
- Expected users and requests per second
- Budget constraints (monthly spend limit)
- Team size and AWS experience level
- Compliance requirements (GDPR, HIPAA, SOC 2)
Aws Solution Architect by the numbers
- 1,528 all-time installs (skills.sh)
- +14 installs in the week ending Jul 29, 2026 (Skillselion tracking)
- Ranked #264 of 1,039 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Jul 31, 2026 (Skillselion catalog sync)
aws-solution-architect capabilities & compatibility
- Capabilities
- application type (web app, mobile backend, data · expected users and requests per second · budget constraints (monthly spend limit) · team size and aws experience level · compliance requirements (gdpr, hipaa, soc 2)
npx skills add https://github.com/alirezarezvani/claude-skills --skill aws-solution-architectAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.5k |
|---|---|
| repo stars | ★ 23.5k |
| Security audit | 3 / 3 scanners passed |
| Last updated | July 17, 2026 |
| Repository | alirezarezvani/claude-skills ↗ |
How do I handle aws solution architect tasks with agent guidance?
Design AWS architectures for startups using serverless patterns and IaC templates. Use when asked to design serverless architecture, create CloudFormation templates, optimize AWS costs, set up CI/CD p
Who is it for?
Teams needing documented aws solution architect workflows.
Skip if: Teams already locked into serverless-only or multi-cloud stacks who will not use ALB, ECS Fargate, or RDS Aurora.
When should I use this skill?
Design AWS architectures for startups using serverless patterns and IaC templates. Use when asked to design serverless architecture, create CloudFormation templates, optimize AWS costs, set up CI/CD p
What you get
Structured workflow from aws solution architect documentation applied to the user request.
- Reference architecture JSON
- Cost breakdown
- IaC templates
By the numbers
- Reference architecture estimated monthly cost: $1,450
- Scaling range: 10k–500k users and 1,000–50,000 requests per second
- Maps 7 AWS services: ALB, ECS Fargate, RDS Aurora, ElastiCache, CloudFront, S3, Cognito
Files
AWS Solution Architect
Design scalable, cost-effective AWS architectures for startups with infrastructure-as-code templates.
---
Workflow
Step 1: Gather Requirements
Collect application specifications:
- Application type (web app, mobile backend, data pipeline, SaaS)
- Expected users and requests per second
- Budget constraints (monthly spend limit)
- Team size and AWS experience level
- Compliance requirements (GDPR, HIPAA, SOC 2)
- Availability requirements (SLA, RPO/RTO)Step 2: Design Architecture
Run the architecture designer to get pattern recommendations:
python scripts/architecture_designer.py --input requirements.jsonExample output:
{
"recommended_pattern": "serverless_web",
"service_stack": ["S3", "CloudFront", "API Gateway", "Lambda", "DynamoDB", "Cognito"],
"estimated_monthly_cost_usd": 35,
"pros": ["Low ops overhead", "Pay-per-use", "Auto-scaling"],
"cons": ["Cold starts", "15-min Lambda limit", "Eventual consistency"]
}Select from recommended patterns:
- Serverless Web: S3 + CloudFront + API Gateway + Lambda + DynamoDB
- Event-Driven Microservices: EventBridge + Lambda + SQS + Step Functions
- Three-Tier: ALB + ECS Fargate + Aurora + ElastiCache
- GraphQL Backend: AppSync + Lambda + DynamoDB + Cognito
See references/architecture_patterns.md for detailed pattern specifications.
Validation checkpoint: Confirm the recommended pattern matches the team's operational maturity and compliance requirements before proceeding to Step 3.
Step 3: Generate IaC Templates
Create infrastructure-as-code for the selected pattern:
# Serverless stack (CloudFormation)
python scripts/serverless_stack.py --app-name my-app --region us-east-1Example CloudFormation YAML output (core serverless resources):
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
AppName:
Type: String
Default: my-app
Resources:
ApiFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs20.x
MemorySize: 512
Timeout: 30
Environment:
Variables:
TABLE_NAME: !Ref DataTable
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref DataTable
Events:
ApiEvent:
Type: Api
Properties:
Path: /{proxy+}
Method: ANY
DataTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: pk
AttributeType: S
- AttributeName: sk
AttributeType: S
KeySchema:
- AttributeName: pk
KeyType: HASH
- AttributeName: sk
KeyType: RANGEFull templates including API Gateway, Cognito, IAM roles, and CloudWatch logging are generated byserverless_stack.pyand also available inreferences/architecture_patterns.md.
Example CDK TypeScript snippet (three-tier pattern):
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as rds from 'aws-cdk-lib/aws-rds';
const vpc = new ec2.Vpc(this, 'AppVpc', { maxAzs: 2 });
const cluster = new ecs.Cluster(this, 'AppCluster', { vpc });
const db = new rds.ServerlessCluster(this, 'AppDb', {
engine: rds.DatabaseClusterEngine.auroraPostgres({
version: rds.AuroraPostgresEngineVersion.VER_15_2,
}),
vpc,
scaling: { minCapacity: 0.5, maxCapacity: 4 },
});Step 4: Review Costs
Analyze estimated costs and optimization opportunities:
python scripts/cost_optimizer.py --resources current_setup.json --monthly-spend 2000Example output:
{
"current_monthly_usd": 2000,
"recommendations": [
{ "action": "Right-size RDS db.r5.2xlarge → db.r5.large", "savings_usd": 420, "priority": "high" },
{ "action": "Purchase 1-yr Compute Savings Plan at 40% utilization", "savings_usd": 310, "priority": "high" },
{ "action": "Move S3 objects >90 days to Glacier Instant Retrieval", "savings_usd": 85, "priority": "medium" }
],
"total_potential_savings_usd": 815
}Output includes:
- Monthly cost breakdown by service
- Right-sizing recommendations
- Savings Plans opportunities
- Potential monthly savings
Step 5: Deploy
Deploy the generated infrastructure:
# CloudFormation
aws cloudformation create-stack \
--stack-name my-app-stack \
--template-body file://template.yaml \
--capabilities CAPABILITY_IAM
# CDK
cdk deploy
# Terraform
terraform init && terraform applyStep 6: Validate and Handle Failures
Verify deployment and set up monitoring:
# Check stack status
aws cloudformation describe-stacks --stack-name my-app-stack
# Set up CloudWatch alarms
aws cloudwatch put-metric-alarm --alarm-name high-errors ...If stack creation fails:
1. Check the failure reason:
aws cloudformation describe-stack-events \
--stack-name my-app-stack \
--query 'StackEvents[?ResourceStatus==`CREATE_FAILED`]'2. Review CloudWatch Logs for Lambda or ECS errors. 3. Fix the template or resource configuration. 4. Delete the failed stack before retrying:
aws cloudformation delete-stack --stack-name my-app-stack
# Wait for deletion
aws cloudformation wait stack-delete-complete --stack-name my-app-stack
# Redeploy
aws cloudformation create-stack ...Common failure causes:
- IAM permission errors → verify
--capabilities CAPABILITY_IAMand role trust policies - Resource limit exceeded → request quota increase via Service Quotas console
- Invalid template syntax → run
aws cloudformation validate-template --template-body file://template.yamlbefore deploying
---
Tools
architecture_designer.py
Generates architecture patterns based on requirements.
python scripts/architecture_designer.py --input requirements.json --output design.jsonInput: JSON with app type, scale, budget, compliance needs Output: Recommended pattern, service stack, cost estimate, pros/cons
serverless_stack.py
Creates serverless CloudFormation templates.
python scripts/serverless_stack.py --app-name my-app --region us-east-1Output: Production-ready CloudFormation YAML with:
- API Gateway + Lambda
- DynamoDB table
- Cognito user pool
- IAM roles with least privilege
- CloudWatch logging
cost_optimizer.py
Analyzes costs and recommends optimizations.
python scripts/cost_optimizer.py --resources inventory.json --monthly-spend 5000Output: Recommendations for:
- Idle resource removal
- Instance right-sizing
- Reserved capacity purchases
- Storage tier transitions
- NAT Gateway alternatives
---
Quick Start
MVP Architecture (< $100/month)
Ask: "Design a serverless MVP backend for a mobile app with 1000 users"
Result:
- Lambda + API Gateway for API
- DynamoDB pay-per-request for data
- Cognito for authentication
- S3 + CloudFront for static assets
- Estimated: $20-50/monthScaling Architecture ($500-2000/month)
Ask: "Design a scalable architecture for a SaaS platform with 50k users"
Result:
- ECS Fargate for containerized API
- Aurora Serverless for relational data
- ElastiCache for session caching
- CloudFront for CDN
- CodePipeline for CI/CD
- Multi-AZ deploymentCost Optimization
Ask: "Optimize my AWS setup to reduce costs by 30%. Current spend: $3000/month"
Provide: Current resource inventory (EC2, RDS, S3, etc.)
Result:
- Idle resource identification
- Right-sizing recommendations
- Savings Plans analysis
- Storage lifecycle policies
- Target savings: $900/monthIaC Generation
Ask: "Generate CloudFormation for a three-tier web app with auto-scaling"
Result:
- VPC with public/private subnets
- ALB with HTTPS
- ECS Fargate with auto-scaling
- Aurora with read replicas
- Security groups and IAM roles---
Input Requirements
Provide these details for architecture design:
| Requirement | Description | Example |
|---|---|---|
| Application type | What you're building | SaaS platform, mobile backend |
| Expected scale | Users, requests/sec | 10k users, 100 RPS |
| Budget | Monthly AWS limit | $500/month max |
| Team context | Size, AWS experience | 3 devs, intermediate |
| Compliance | Regulatory needs | HIPAA, GDPR, SOC 2 |
| Availability | Uptime requirements | 99.9% SLA, 1hr RPO |
JSON Format:
{
"application_type": "saas_platform",
"expected_users": 10000,
"requests_per_second": 100,
"budget_monthly_usd": 500,
"team_size": 3,
"aws_experience": "intermediate",
"compliance": ["SOC2"],
"availability_sla": "99.9%"
}---
Output Formats
Architecture Design
- Pattern recommendation with rationale
- Service stack diagram (ASCII)
- Monthly cost estimate and trade-offs
IaC Templates
- CloudFormation YAML: Production-ready SAM/CFN templates
- CDK TypeScript: Type-safe infrastructure code
- Terraform HCL: Multi-cloud compatible configs
Cost Analysis
- Current spend breakdown with optimization recommendations
- Priority action list (high/medium/low) and implementation checklist
---
Reference Documentation
| Document | Contents |
|---|---|
references/architecture_patterns.md | 6 patterns: serverless, microservices, three-tier, data processing, GraphQL, multi-region |
references/service_selection.md | Decision matrices for compute, database, storage, messaging |
references/best_practices.md | Serverless design, cost optimization, security hardening, scalability |
{
"recommended_architecture": {
"pattern_name": "Modern Three-Tier Application",
"description": "Classic architecture with containers and managed services",
"estimated_monthly_cost": 1450,
"scaling_characteristics": {
"users_supported": "10k - 500k",
"requests_per_second": "1,000 - 50,000"
}
},
"services": {
"load_balancer": "Application Load Balancer (ALB)",
"compute": "ECS Fargate",
"database": "RDS Aurora (MySQL/PostgreSQL)",
"cache": "ElastiCache Redis",
"cdn": "CloudFront",
"storage": "S3",
"authentication": "Cognito"
},
"cost_breakdown": {
"ALB": "20-30 USD",
"ECS_Fargate": "50-200 USD",
"RDS_Aurora": "100-300 USD",
"ElastiCache": "30-80 USD",
"CloudFront": "10-50 USD",
"S3": "10-30 USD"
},
"implementation_phases": [
{
"phase": "Foundation",
"duration": "1 week",
"tasks": ["VPC setup", "IAM roles", "CloudTrail", "AWS Config"]
},
{
"phase": "Core Services",
"duration": "2 weeks",
"tasks": ["Deploy ALB", "ECS Fargate", "RDS Aurora", "ElastiCache"]
},
{
"phase": "Security & Monitoring",
"duration": "1 week",
"tasks": ["WAF rules", "CloudWatch dashboards", "Alarms", "X-Ray"]
},
{
"phase": "CI/CD",
"duration": "1 week",
"tasks": ["CodePipeline", "Blue/Green deployment", "Rollback procedures"]
}
],
"iac_templates_generated": [
"CloudFormation template (YAML)",
"AWS CDK stack (TypeScript)",
"Terraform configuration (HCL)"
]
}
{
"application_type": "saas_platform",
"expected_users": 50000,
"requests_per_second": 100,
"budget_monthly_usd": 1500,
"team_size": 5,
"aws_experience": "intermediate",
"compliance": ["GDPR"],
"data_size_gb": 500,
"region": "us-east-1",
"requirements": {
"authentication": true,
"real_time_features": false,
"multi_region": false,
"high_availability": true,
"auto_scaling": true
}
}
AWS Architecture Patterns for Startups
Reference guide for selecting the right AWS architecture pattern based on application requirements.
---
Table of Contents
- Pattern Selection Matrix
- Pattern 1: Serverless Web Application
- Pattern 2: Event-Driven Microservices
- Pattern 3: Modern Three-Tier Application
- Pattern 4: Real-Time Data Processing
- Pattern 5: GraphQL API Backend
- Pattern 6: Multi-Region High Availability
---
Pattern Selection Matrix
| Pattern | Best For | Users | Monthly Cost | Complexity |
|---|---|---|---|---|
| Serverless Web | MVP, SaaS, mobile backend | <50K | $50-500 | Low |
| Event-Driven Microservices | Complex workflows, async processing | Any | $100-1000 | Medium |
| Three-Tier | Traditional web, e-commerce | 10K-500K | $300-2000 | Medium |
| Real-Time Data | Analytics, IoT, streaming | Any | $200-1500 | High |
| GraphQL Backend | Mobile apps, SPAs | <100K | $50-400 | Medium |
| Multi-Region HA | Global apps, DR requirements | >100K | 1.5-2x single | High |
---
Pattern 1: Serverless Web Application
Use Case
SaaS platforms, mobile backends, low-traffic websites, MVPs
Architecture Diagram
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ CloudFront │────▶│ S3 │ │ Cognito │
│ (CDN) │ │ (Static) │ │ (Auth) │
└─────────────┘ └─────────────┘ └──────┬──────┘
│
┌─────────────┐ ┌─────────────┐ ┌──────▼──────┐
│ Route 53 │────▶│ API Gateway │────▶│ Lambda │
│ (DNS) │ │ (REST) │ │ (Functions) │
└─────────────┘ └─────────────┘ └──────┬──────┘
│
┌──────▼──────┐
│ DynamoDB │
│ (Database) │
└─────────────┘Service Stack
| Layer | Service | Configuration |
|---|---|---|
| Frontend | S3 + CloudFront | Static hosting with HTTPS |
| API | API Gateway + Lambda | REST endpoints with throttling |
| Database | DynamoDB | Pay-per-request billing |
| Auth | Cognito | User pools with MFA support |
| CI/CD | Amplify or CodePipeline | Automated deployments |
CloudFormation Template
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
# API Function
ApiFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: nodejs18.x
Handler: index.handler
MemorySize: 512
Timeout: 10
Events:
Api:
Type: Api
Properties:
Path: /{proxy+}
Method: ANY
# DynamoDB Table
DataTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: PK
AttributeType: S
- AttributeName: SK
AttributeType: S
KeySchema:
- AttributeName: PK
KeyType: HASH
- AttributeName: SK
KeyType: RANGECost Breakdown (10K users)
| Service | Monthly Cost |
|---|---|
| Lambda | $5-20 |
| API Gateway | $10-30 |
| DynamoDB | $10-50 |
| CloudFront | $5-15 |
| S3 | $1-5 |
| Cognito | $0-50 |
| Total | $31-170 |
Pros and Cons
Pros:
- Zero server management
- Pay only for what you use
- Auto-scaling built-in
- Low operational overhead
Cons:
- Cold start latency (100-500ms)
- 15-minute Lambda execution limit
- Vendor lock-in
---
Pattern 2: Event-Driven Microservices
Use Case
Complex business workflows, asynchronous processing, decoupled systems
Architecture Diagram
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Service │────▶│ EventBridge │────▶│ Service │
│ A │ │ (Event Bus)│ │ B │
└─────────────┘ └──────┬──────┘ └─────────────┘
│
┌──────▼──────┐
│ SQS │
│ (Queue) │
└──────┬──────┘
│
┌─────────────┐ ┌──────▼──────┐ ┌─────────────┐
│ Step │◀────│ Lambda │────▶│ DynamoDB │
│ Functions │ │ (Processor) │ │ (Storage) │
└─────────────┘ └─────────────┘ └─────────────┘Service Stack
| Layer | Service | Purpose |
|---|---|---|
| Events | EventBridge | Central event bus |
| Processing | Lambda or ECS Fargate | Event handlers |
| Queue | SQS | Dead letter queue for failures |
| Orchestration | Step Functions | Complex workflow state |
| Storage | DynamoDB, S3 | Persistent data |
Event Schema Example
{
"source": "orders.service",
"detail-type": "OrderCreated",
"detail": {
"orderId": "ord-12345",
"customerId": "cust-67890",
"items": [...],
"total": 99.99,
"timestamp": "2024-01-15T10:30:00Z"
}
}Cost Breakdown
| Service | Monthly Cost |
|---|---|
| EventBridge | $1-10 |
| Lambda | $20-100 |
| SQS | $5-20 |
| Step Functions | $25-100 |
| DynamoDB | $20-100 |
| Total | $71-330 |
Pros and Cons
Pros:
- Loose coupling between services
- Independent scaling per service
- Failure isolation
- Easy to test individually
Cons:
- Distributed system complexity
- Eventual consistency
- Harder to debug
---
Pattern 3: Modern Three-Tier Application
Use Case
Traditional web apps, e-commerce, CMS, applications with complex queries
Architecture Diagram
┌─────────────┐ ┌─────────────┐
│ CloudFront │────▶│ ALB │
│ (CDN) │ │ (Load Bal.) │
└─────────────┘ └──────┬──────┘
│
┌──────▼──────┐
│ ECS Fargate │
│ (Auto-scale)│
└──────┬──────┘
│
┌──────────────────┼──────────────────┐
│ │ │
┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
│ Aurora │ │ ElastiCache │ │ S3 │
│ (Database) │ │ (Redis) │ │ (Storage) │
└─────────────┘ └─────────────┘ └─────────────┘Service Stack
| Layer | Service | Configuration |
|---|---|---|
| CDN | CloudFront | Edge caching, HTTPS |
| Load Balancer | ALB | Path-based routing, health checks |
| Compute | ECS Fargate | Container auto-scaling |
| Database | Aurora MySQL/PostgreSQL | Multi-AZ, auto-scaling |
| Cache | ElastiCache Redis | Session, query caching |
| Storage | S3 | Static assets, uploads |
Terraform Example
# ECS Service with Auto-scaling
resource "aws_ecs_service" "app" {
name = "app-service"
cluster = aws_ecs_cluster.main.id
task_definition = aws_ecs_task_definition.app.arn
desired_count = 2
capacity_provider_strategy {
capacity_provider = "FARGATE"
weight = 100
}
load_balancer {
target_group_arn = aws_lb_target_group.app.arn
container_name = "app"
container_port = 3000
}
}
# Auto-scaling Policy
resource "aws_appautoscaling_target" "app" {
max_capacity = 10
min_capacity = 2
resource_id = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.app.name}"
scalable_dimension = "ecs:service:DesiredCount"
service_namespace = "ecs"
}Cost Breakdown (50K users)
| Service | Monthly Cost |
|---|---|
| ECS Fargate (2 tasks) | $100-200 |
| ALB | $25-50 |
| Aurora | $100-300 |
| ElastiCache | $50-100 |
| CloudFront | $20-50 |
| Total | $295-700 |
---
Pattern 4: Real-Time Data Processing
Use Case
Analytics, IoT data ingestion, log processing, streaming data
Architecture Diagram
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ IoT Core │────▶│ Kinesis │────▶│ Lambda │
│ (Devices) │ │ (Stream) │ │ (Process) │
└─────────────┘ └─────────────┘ └──────┬──────┘
│
┌─────────────┐ ┌─────────────┐ ┌──────▼──────┐
│ QuickSight │◀────│ Athena │◀────│ S3 │
│ (Viz) │ │ (Query) │ │ (Data Lake) │
└─────────────┘ └─────────────┘ └─────────────┘
│
┌──────▼──────┐
│ CloudWatch │
│ (Alerts) │
└─────────────┘Service Stack
| Layer | Service | Purpose |
|---|---|---|
| Ingestion | Kinesis Data Streams | Real-time data capture |
| Processing | Lambda or Kinesis Analytics | Transform and analyze |
| Storage | S3 (data lake) | Long-term storage |
| Query | Athena | SQL queries on S3 |
| Visualization | QuickSight | Dashboards and reports |
| Alerting | CloudWatch + SNS | Threshold-based alerts |
Kinesis Producer Example
import boto3
import json
kinesis = boto3.client('kinesis')
def send_event(stream_name, data, partition_key):
response = kinesis.put_record(
StreamName=stream_name,
Data=json.dumps(data),
PartitionKey=partition_key
)
return response['SequenceNumber']
# Send sensor reading
send_event(
'sensor-stream',
{'sensor_id': 'temp-01', 'value': 23.5, 'unit': 'celsius'},
'sensor-01'
)Cost Breakdown
| Service | Monthly Cost |
|---|---|
| Kinesis (1 shard) | $15-30 |
| Lambda | $10-50 |
| S3 | $5-50 |
| Athena | $5-25 |
| QuickSight | $24+ |
| Total | $59-179 |
---
Pattern 5: GraphQL API Backend
Use Case
Mobile apps, single-page applications, flexible data queries
Architecture Diagram
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Mobile App │────▶│ AppSync │────▶│ Lambda │
│ or SPA │ │ (GraphQL) │ │ (Resolvers) │
└─────────────┘ └──────┬──────┘ └─────────────┘
│
┌──────▼──────┐
│ DynamoDB │
│ (Direct) │
└──────┬──────┘
│
┌──────▼──────┐
│ Cognito │
│ (Auth) │
└─────────────┘AppSync Schema Example
type Query {
getUser(id: ID!): User
listPosts(limit: Int, nextToken: String): PostConnection
}
type Mutation {
createPost(input: CreatePostInput!): Post
updatePost(input: UpdatePostInput!): Post
}
type Subscription {
onCreatePost: Post @aws_subscribe(mutations: ["createPost"])
}
type User {
id: ID!
email: String!
posts: [Post]
}
type Post {
id: ID!
title: String!
content: String!
author: User!
createdAt: AWSDateTime!
}Cost Breakdown
| Service | Monthly Cost |
|---|---|
| AppSync | $4-40 |
| Lambda | $5-30 |
| DynamoDB | $10-50 |
| Cognito | $0-50 |
| Total | $19-170 |
---
Pattern 6: Multi-Region High Availability
Use Case
Global applications, disaster recovery, data sovereignty compliance
Architecture Diagram
┌─────────────┐
│ Route 53 │
│(Geo routing)│
└──────┬──────┘
│
┌────────────────┼────────────────┐
│ │
┌──────▼──────┐ ┌──────▼──────┐
│ us-east-1 │ │ eu-west-1 │
│ CloudFront │ │ CloudFront │
└──────┬──────┘ └──────┬──────┘
│ │
┌──────▼──────┐ ┌──────▼──────┐
│ ECS/Lambda │ │ ECS/Lambda │
└──────┬──────┘ └──────┬──────┘
│ │
┌──────▼──────┐◀── Replication ──▶┌──────▼──────┐
│ DynamoDB │ │ DynamoDB │
│Global Table │ │Global Table │
└─────────────┘ └─────────────┘Service Stack
| Component | Service | Configuration |
|---|---|---|
| DNS | Route 53 | Geolocation or latency routing |
| CDN | CloudFront | Multiple origins per region |
| Compute | Lambda or ECS | Deployed in each region |
| Database | DynamoDB Global Tables | Automatic replication |
| Storage | S3 CRR | Cross-region replication |
Route 53 Failover Policy
# Primary record
HealthCheck:
Type: AWS::Route53::HealthCheck
Properties:
HealthCheckConfig:
Port: 443
Type: HTTPS
ResourcePath: /health
FullyQualifiedDomainName: api-us-east-1.example.com
RecordSetPrimary:
Type: AWS::Route53::RecordSet
Properties:
Name: api.example.com
Type: A
SetIdentifier: primary
Failover: PRIMARY
HealthCheckId: !Ref HealthCheck
AliasTarget:
DNSName: !GetAtt USEast1ALB.DNSName
HostedZoneId: !GetAtt USEast1ALB.CanonicalHostedZoneIDCost Considerations
| Factor | Impact |
|---|---|
| Compute | 2x (each region) |
| Database | 25% premium for global tables |
| Data Transfer | Cross-region replication costs |
| Route 53 | Health checks + geo queries |
| Total | 1.5-2x single region |
---
Pattern Comparison Summary
Latency
| Pattern | Typical Latency |
|---|---|
| Serverless | 50-200ms (cold: 500ms+) |
| Three-Tier | 20-100ms |
| GraphQL | 30-150ms |
| Multi-Region | <50ms (regional) |
Scaling Characteristics
| Pattern | Scale Limit | Scale Speed |
|---|---|---|
| Serverless | 1000 concurrent/function | Instant |
| Three-Tier | Instance limits | Minutes |
| Event-Driven | Unlimited | Instant |
| Multi-Region | Regional limits | Instant |
Operational Complexity
| Pattern | Setup | Maintenance | Debugging |
|---|---|---|---|
| Serverless | Low | Low | Medium |
| Three-Tier | Medium | Medium | Low |
| Event-Driven | High | Medium | High |
| Multi-Region | High | High | High |
AWS Best Practices for Startups
Production-ready practices for serverless, cost optimization, security, and operational excellence.
---
Table of Contents
- Serverless Best Practices
- Cost Optimization
- Security Hardening
- Scalability Patterns
- DevOps and Reliability
- Common Pitfalls
---
Serverless Best Practices
Lambda Function Design
1. Keep Functions Stateless
Store state externally in DynamoDB, S3, or ElastiCache.
# BAD: Function-level state
cache = {}
def handler(event, context):
if event['key'] in cache:
return cache[event['key']]
# ...
# GOOD: External state
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('cache')
def handler(event, context):
response = table.get_item(Key={'pk': event['key']})
if 'Item' in response:
return response['Item']['value']
# ...2. Implement Idempotency
Handle retries gracefully with unique request IDs.
import boto3
import hashlib
dynamodb = boto3.resource('dynamodb')
idempotency_table = dynamodb.Table('idempotency')
def handler(event, context):
# Generate idempotency key
idempotency_key = hashlib.sha256(
f"{event['orderId']}-{event['action']}".encode()
).hexdigest()
# Check if already processed
try:
response = idempotency_table.get_item(Key={'pk': idempotency_key})
if 'Item' in response:
return response['Item']['result']
except Exception:
pass
# Process request
result = process_order(event)
# Store result for idempotency
idempotency_table.put_item(
Item={
'pk': idempotency_key,
'result': result,
'ttl': int(time.time()) + 86400 # 24h TTL
}
)
return result3. Optimize Cold Starts
# Initialize outside handler (reused across invocations)
import boto3
from aws_xray_sdk.core import patch_all
# SDK initialization happens once
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('my-table')
patch_all()
def handler(event, context):
# Handler code uses pre-initialized resources
return table.get_item(Key={'pk': event['id']})Cold Start Reduction Techniques:
- Use provisioned concurrency for critical paths
- Minimize package size (use layers for dependencies)
- Choose interpreted languages (Python, Node.js) over compiled
- Avoid VPC unless necessary (adds 6-10 sec cold start)
4. Set Appropriate Timeouts
# Lambda configuration
Functions:
ApiHandler:
Timeout: 10 # Shorter for synchronous APIs
MemorySize: 512
BackgroundProcessor:
Timeout: 300 # Longer for async processing
MemorySize: 1024Timeout Guidelines:
- API handlers: 10-30 seconds
- Event processors: 60-300 seconds
- Use Step Functions for >15 minute workflows
---
Cost Optimization
1. Right-Sizing Strategy
# Check EC2 utilization
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=i-1234567890abcdef0 \
--start-time $(date -d '7 days ago' -u +"%Y-%m-%dT%H:%M:%SZ") \
--end-time $(date -u +"%Y-%m-%dT%H:%M:%SZ") \
--period 3600 \
--statistics AverageRight-Sizing Rules:
- <10% CPU average: Downsize instance
- >80% CPU average: Consider upgrade or horizontal scaling
- Review every month for the first 6 months
2. Savings Plans and Reserved Instances
| Commitment | Savings | Best For |
|---|---|---|
| No Upfront, 1-year | 20-30% | Unknown future |
| Partial Upfront, 1-year | 30-40% | Moderate confidence |
| All Upfront, 3-year | 50-60% | Stable workloads |
# Check Savings Plans recommendations
aws cost-explorer get-savings-plans-purchase-recommendation \
--savings-plans-type COMPUTE_SP \
--term-in-years ONE_YEAR \
--payment-option NO_UPFRONT \
--lookback-period-in-days THIRTY_DAYS3. S3 Lifecycle Policies
{
"Rules": [
{
"ID": "Transition to cheaper storage",
"Status": "Enabled",
"Filter": {
"Prefix": "logs/"
},
"Transitions": [
{ "Days": 30, "StorageClass": "STANDARD_IA" },
{ "Days": 90, "StorageClass": "GLACIER" }
],
"Expiration": { "Days": 365 }
}
]
}4. Lambda Memory Optimization
Test different memory settings to find optimal cost/performance.
# Use AWS Lambda Power Tuning
# https://github.com/alexcasalboni/aws-lambda-power-tuning
# Example results:
# 128 MB: 2000ms, $0.000042
# 512 MB: 500ms, $0.000042
# 1024 MB: 300ms, $0.000050
# Optimal: 512 MB (same cost, 4x faster)5. NAT Gateway Alternatives
NAT Gateway: $0.045/hour + $0.045/GB = ~$32/month + data
Alternatives:
1. VPC Endpoints: $0.01/hour = ~$7.30/month (for AWS services)
2. NAT Instance: t3.nano = ~$3.80/month (limited throughput)
3. No NAT: Use VPC endpoints + Lambda outside VPC6. CloudWatch Log Retention
# Set retention policies to avoid unbounded growth
LogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: /aws/lambda/my-function
RetentionInDays: 14 # 7, 14, 30, 60, 90, etc.Retention Guidelines:
- Development: 7 days
- Production non-critical: 30 days
- Production critical: 90 days
- Compliance requirements: As specified
---
Security Hardening
1. IAM Least Privilege
// BAD: Overly permissive
{
"Effect": "Allow",
"Action": "dynamodb:*",
"Resource": "*"
}
// GOOD: Specific actions and resources
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:Query"
],
"Resource": [
"arn:aws:dynamodb:us-east-1:123456789:table/users",
"arn:aws:dynamodb:us-east-1:123456789:table/users/index/*"
]
}2. Encryption Configuration
# Enable encryption everywhere
Resources:
# DynamoDB
Table:
Type: AWS::DynamoDB::Table
Properties:
SSESpecification:
SSEEnabled: true
SSEType: KMS
KMSMasterKeyId: !Ref EncryptionKey
# S3
Bucket:
Type: AWS::S3::Bucket
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: aws:kms
KMSMasterKeyID: !Ref EncryptionKey
# RDS
Database:
Type: AWS::RDS::DBInstance
Properties:
StorageEncrypted: true
KmsKeyId: !Ref EncryptionKey3. Network Isolation
# Private subnets with VPC endpoints
Resources:
PrivateSubnet:
Type: AWS::EC2::Subnet
Properties:
MapPublicIpOnLaunch: false
# DynamoDB Gateway Endpoint (free)
DynamoDBEndpoint:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcId: !Ref VPC
ServiceName: !Sub com.amazonaws.${AWS::Region}.dynamodb
VpcEndpointType: Gateway
RouteTableIds:
- !Ref PrivateRouteTable
# Secrets Manager Interface Endpoint
SecretsEndpoint:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcId: !Ref VPC
ServiceName: !Sub com.amazonaws.${AWS::Region}.secretsmanager
VpcEndpointType: Interface
PrivateDnsEnabled: true4. Secrets Management
# Never hardcode secrets
import boto3
import json
def get_secret(secret_name):
client = boto3.client('secretsmanager')
response = client.get_secret_value(SecretId=secret_name)
return json.loads(response['SecretString'])
# Usage
db_creds = get_secret('prod/database/credentials')
connection = connect(
host=db_creds['host'],
user=db_creds['username'],
password=db_creds['password']
)5. API Protection
# WAF + API Gateway
WebACL:
Type: AWS::WAFv2::WebACL
Properties:
DefaultAction:
Allow: {}
Rules:
- Name: RateLimit
Priority: 1
Action:
Block: {}
Statement:
RateBasedStatement:
Limit: 2000
AggregateKeyType: IP
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: RateLimitRule
- Name: AWSManagedRulesCommonRuleSet
Priority: 2
OverrideAction:
None: {}
Statement:
ManagedRuleGroupStatement:
VendorName: AWS
Name: AWSManagedRulesCommonRuleSet6. Audit Logging
# Enable CloudTrail for all API calls
CloudTrail:
Type: AWS::CloudTrail::Trail
Properties:
IsMultiRegionTrail: true
IsLogging: true
S3BucketName: !Ref AuditLogsBucket
IncludeGlobalServiceEvents: true
EnableLogFileValidation: true
EventSelectors:
- ReadWriteType: All
IncludeManagementEvents: true---
Scalability Patterns
1. Horizontal vs Vertical Scaling
Horizontal (preferred):
- Add more Lambda concurrent executions
- Add more Fargate tasks
- Add more DynamoDB capacity
Vertical (when necessary):
- Increase Lambda memory
- Upgrade RDS instance
- Larger EC2 instances2. Database Sharding
# Partition by tenant ID
def get_table_for_tenant(tenant_id):
shard = hash(tenant_id) % NUM_SHARDS
return f"data-shard-{shard}"
# Or use DynamoDB single-table design with partition keys
def get_partition_key(tenant_id, entity_type, entity_id):
return f"TENANT#{tenant_id}#{entity_type}#{entity_id}"3. Caching Layers
Edge (CloudFront): Global, static content, TTL: hours-days
Application (Redis): Regional, session/query cache, TTL: minutes-hours
Database (DAX): DynamoDB-specific, TTL: minutes# ElastiCache Redis caching pattern
import redis
import json
cache = redis.Redis(host='cache.abc123.cache.amazonaws.com', port=6379)
def get_user(user_id):
# Check cache first
cached = cache.get(f"user:{user_id}")
if cached:
return json.loads(cached)
# Fetch from database
user = db.get_user(user_id)
# Cache for 5 minutes
cache.setex(f"user:{user_id}", 300, json.dumps(user))
return user4. Auto-Scaling Configuration
# ECS Service Auto-scaling
AutoScalingTarget:
Type: AWS::ApplicationAutoScaling::ScalableTarget
Properties:
MaxCapacity: 10
MinCapacity: 2
ResourceId: !Sub service/${Cluster}/${Service.Name}
ScalableDimension: ecs:service:DesiredCount
ServiceNamespace: ecs
ScalingPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
Properties:
PolicyType: TargetTrackingScaling
TargetTrackingScalingPolicyConfiguration:
PredefinedMetricSpecification:
PredefinedMetricType: ECSServiceAverageCPUUtilization
TargetValue: 70
ScaleInCooldown: 300
ScaleOutCooldown: 60---
DevOps and Reliability
1. Infrastructure as Code
# Version control all infrastructure
git init
git add .
git commit -m "Initial infrastructure setup"
# Use separate stacks per environment
cdk deploy --context environment=dev
cdk deploy --context environment=staging
cdk deploy --context environment=production2. Blue/Green Deployments
# CodeDeploy Blue/Green for ECS
DeploymentGroup:
Type: AWS::CodeDeploy::DeploymentGroup
Properties:
DeploymentConfigName: CodeDeployDefault.ECSAllAtOnce
DeploymentStyle:
DeploymentType: BLUE_GREEN
DeploymentOption: WITH_TRAFFIC_CONTROL
BlueGreenDeploymentConfiguration:
DeploymentReadyOption:
ActionOnTimeout: CONTINUE_DEPLOYMENT
WaitTimeInMinutes: 0
TerminateBlueInstancesOnDeploymentSuccess:
Action: TERMINATE
TerminationWaitTimeInMinutes: 53. Health Checks
# Application health endpoint
from flask import Flask, jsonify
import boto3
app = Flask(__name__)
@app.route('/health')
def health():
checks = {
'database': check_database(),
'cache': check_cache(),
'external_api': check_external_api()
}
status = 'healthy' if all(checks.values()) else 'unhealthy'
code = 200 if status == 'healthy' else 503
return jsonify({'status': status, 'checks': checks}), code
def check_database():
try:
# Quick connectivity test
db.execute('SELECT 1')
return True
except Exception:
return False4. Monitoring Setup
# CloudWatch Dashboard
Dashboard:
Type: AWS::CloudWatch::Dashboard
Properties:
DashboardName: production-overview
DashboardBody: |
{
"widgets": [
{
"type": "metric",
"properties": {
"metrics": [
["AWS/Lambda", "Invocations", "FunctionName", "api-handler"],
[".", "Errors", ".", "."],
[".", "Duration", ".", ".", {"stat": "p99"}]
],
"period": 60,
"title": "Lambda Metrics"
}
}
]
}
# Critical Alarms
ErrorAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: high-error-rate
MetricName: Errors
Namespace: AWS/Lambda
Statistic: Sum
Period: 60
EvaluationPeriods: 3
Threshold: 10
ComparisonOperator: GreaterThanThreshold
AlarmActions:
- !Ref AlertTopic---
Common Pitfalls
Technical Debt
| Pitfall | Solution |
|---|---|
| Over-engineering early | Start simple, scale when needed |
| Under-monitoring | Set up CloudWatch from day one |
| Ignoring costs | Enable Cost Explorer and billing alerts |
| Single region only | Plan for multi-region from start |
Security Mistakes
| Mistake | Prevention |
|---|---|
| Public S3 buckets | Block public access, use bucket policies |
| Overly permissive IAM | Never use "*", specify resources |
| Hardcoded credentials | Use Secrets Manager, IAM roles |
| Unencrypted data | Enable encryption by default |
Performance Issues
| Issue | Solution |
|---|---|
| No caching | Add CloudFront, ElastiCache early |
| Inefficient queries | Use indexes, avoid DynamoDB scans |
| Large Lambda packages | Use layers, minimize dependencies |
| N+1 queries | Implement DataLoader, batch operations |
Cost Surprises
| Surprise | Prevention |
|---|---|
| Undeleted resources | Tag everything, review weekly |
| Data transfer costs | Keep traffic in same AZ/region |
| NAT Gateway charges | Use VPC endpoints for AWS services |
| Log accumulation | Set CloudWatch retention policies |
AWS Service Selection Guide
Quick reference for choosing the right AWS service based on requirements.
---
Table of Contents
- Compute Services
- Database Services
- Storage Services
- Messaging and Events
- API and Integration
- Networking
- Security and Identity
---
Compute Services
Decision Matrix
| Requirement | Recommended Service |
|---|---|
| Event-driven, short tasks (<15 min) | Lambda |
| Containerized apps, predictable traffic | ECS Fargate |
| Custom configs, GPU/FPGA | EC2 |
| Simple container from source | App Runner |
| Kubernetes workloads | EKS |
| Batch processing | AWS Batch |
Lambda
Best for: Event-driven functions, API backends, scheduled tasks
Limits:
- Execution: 15 minutes max
- Memory: 128 MB - 10 GB
- Package: 50 MB (zip), 10 GB (container)
- Concurrency: 1000 default (soft limit)
Pricing: $0.20 per 1M requests + compute timeUse when:
- Variable/unpredictable traffic
- Pay-per-use is important
- No server management desired
- Short-duration operations
Avoid when:
- Long-running processes (>15 min)
- Low-latency requirements (<50ms)
- Heavy compute (consider Fargate)
ECS Fargate
Best for: Containerized applications, microservices
Limits:
- vCPU: 0.25 - 16
- Memory: 0.5 GB - 120 GB
- Storage: 20 GB - 200 GB ephemeral
Pricing: Per vCPU-hour + GB-hourUse when:
- Containerized applications
- Predictable traffic patterns
- Long-running processes
- Need more control than Lambda
EC2
Best for: Custom configurations, specialized hardware
Instance Types:
- General: t3, m6i
- Compute: c6i
- Memory: r6i
- GPU: p4d, g5
- Storage: i3, d3Use when:
- Need GPU/FPGA
- Windows applications
- Specific instance configurations
- Reserved capacity makes sense
---
Database Services
Decision Matrix
| Data Type | Query Pattern | Scale | Recommended |
|---|---|---|---|
| Key-value | Simple lookups | Any | DynamoDB |
| Document | Flexible queries | <1TB | DocumentDB |
| Relational | Complex joins | Variable | Aurora Serverless |
| Relational | High volume | Fixed | Aurora Standard |
| Time-series | Time-based | Any | Timestream |
| Graph | Relationships | Any | Neptune |
DynamoDB
Best for: Key-value and document data, serverless applications
Limits:
- Item size: 400 KB max
- Partition key: 2048 bytes
- Sort key: 1024 bytes
- GSI: 20 per table
Pricing:
- On-demand: $1.25 per million writes, $0.25 per million reads
- Provisioned: Per RCU/WCUData Modeling Example:
# Single-table design for e-commerce
PK SK Attributes
USER#123 PROFILE {name, email, ...}
USER#123 ORDER#456 {total, status, ...}
USER#123 ORDER#456#ITEM#1 {product, qty, ...}
PRODUCT#789 METADATA {name, price, ...}Aurora
Best for: Relational data with complex queries
| Edition | Use Case | Scaling |
|---|---|---|
| Aurora Serverless v2 | Variable workloads | 0.5-128 ACUs, auto |
| Aurora Standard | Predictable workloads | Instance-based |
| Aurora Global | Multi-region | Cross-region replication |
Limits:
- Storage: 128 TB max
- Replicas: 15 read replicas
- Connections: Instance-dependent
Pricing:
- Serverless: $0.12 per ACU-hour
- Standard: Instance + storage + I/OComparison: DynamoDB vs Aurora
| Factor | DynamoDB | Aurora |
|---|---|---|
| Query flexibility | Limited (key-based) | Full SQL |
| Scaling | Instant, unlimited | Minutes, up to limits |
| Consistency | Eventually/Strong | ACID |
| Cost model | Per-request | Per-hour |
| Operational | Zero management | Some management |
---
Storage Services
S3 Storage Classes
| Class | Access Pattern | Retrieval | Cost (GB/mo) |
|---|---|---|---|
| Standard | Frequent | Instant | $0.023 |
| Intelligent-Tiering | Unknown | Instant | $0.023 + monitoring |
| Standard-IA | Infrequent (30+ days) | Instant | $0.0125 |
| One Zone-IA | Infrequent, single AZ | Instant | $0.01 |
| Glacier Instant | Archive, instant access | Instant | $0.004 |
| Glacier Flexible | Archive | Minutes-hours | $0.0036 |
| Glacier Deep Archive | Long-term archive | 12-48 hours | $0.00099 |
Lifecycle Policy Example
{
"Rules": [
{
"ID": "Archive old data",
"Status": "Enabled",
"Transitions": [
{
"Days": 30,
"StorageClass": "STANDARD_IA"
},
{
"Days": 90,
"StorageClass": "GLACIER"
},
{
"Days": 365,
"StorageClass": "DEEP_ARCHIVE"
}
],
"Expiration": {
"Days": 2555
}
}
]
}Block and File Storage
| Service | Use Case | Access |
|---|---|---|
| EBS | EC2 block storage | Single instance |
| EFS | Shared file system | Multiple instances |
| FSx for Lustre | HPC workloads | High throughput |
| FSx for Windows | Windows apps | SMB protocol |
---
Messaging and Events
Decision Matrix
| Pattern | Service | Use Case |
|---|---|---|
| Event routing | EventBridge | Microservices, SaaS integration |
| Pub/sub | SNS | Fan-out notifications |
| Queue | SQS | Decoupling, buffering |
| Streaming | Kinesis | Real-time analytics |
| Message broker | Amazon MQ | Legacy migrations |
EventBridge
Best for: Event-driven architectures, SaaS integration
# EventBridge rule pattern
{
"source": ["orders.service"],
"detail-type": ["OrderCreated"],
"detail": {
"total": [{"numeric": [">=", 100]}]
}
}SQS
Best for: Decoupling services, handling load spikes
| Feature | Standard | FIFO |
|---|---|---|
| Throughput | Unlimited | 3000 msg/sec |
| Ordering | Best effort | Guaranteed |
| Delivery | At least once | Exactly once |
| Deduplication | No | Yes |
# SQS with dead letter queue
import boto3
sqs = boto3.client('sqs')
def process_with_dlq(queue_url, dlq_url, max_retries=3):
response = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=10,
WaitTimeSeconds=20,
AttributeNames=['ApproximateReceiveCount']
)
for message in response.get('Messages', []):
receive_count = int(message['Attributes']['ApproximateReceiveCount'])
try:
process(message)
sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=message['ReceiptHandle'])
except Exception as e:
if receive_count >= max_retries:
sqs.send_message(QueueUrl=dlq_url, MessageBody=message['Body'])
sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=message['ReceiptHandle'])Kinesis
Best for: Real-time streaming data, analytics
| Service | Use Case |
|---|---|
| Data Streams | Custom processing |
| Data Firehose | Direct to S3/Redshift |
| Data Analytics | SQL on streams |
| Video Streams | Video ingestion |
---
API and Integration
API Gateway vs AppSync
| Factor | API Gateway | AppSync |
|---|---|---|
| Protocol | REST, WebSocket | GraphQL |
| Real-time | WebSocket setup | Built-in subscriptions |
| Caching | Response caching | Field-level caching |
| Integration | Lambda, HTTP, AWS | Lambda, DynamoDB, HTTP |
| Pricing | Per request | Per request + data |
API Gateway Configuration
# Throttling and caching
Resources:
ApiGateway:
Type: AWS::ApiGateway::RestApi
Properties:
Name: my-api
ApiStage:
Type: AWS::ApiGateway::Stage
Properties:
StageName: prod
MethodSettings:
- HttpMethod: "*"
ResourcePath: "/*"
ThrottlingBurstLimit: 500
ThrottlingRateLimit: 1000
CachingEnabled: true
CacheTtlInSeconds: 300Step Functions
Best for: Workflow orchestration, long-running processes
{
"StartAt": "ProcessOrder",
"States": {
"ProcessOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:processOrder",
"Next": "CheckInventory"
},
"CheckInventory": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.inStock",
"BooleanEquals": true,
"Next": "ShipOrder"
}
],
"Default": "BackOrder"
},
"ShipOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:shipOrder",
"End": true
},
"BackOrder": {
"Type": "Task",
"Resource": "arn:aws:lambda:...:backOrder",
"End": true
}
}
}---
Networking
VPC Components
| Component | Purpose |
|---|---|
| VPC | Isolated network |
| Subnet | Network segment (public/private) |
| Internet Gateway | Public internet access |
| NAT Gateway | Private subnet outbound |
| VPC Endpoint | Private AWS service access |
| Transit Gateway | VPC interconnection |
VPC Design Pattern
VPC: 10.0.0.0/16
Public Subnets (AZ a, b, c):
10.0.1.0/24, 10.0.2.0/24, 10.0.3.0/24
- ALB, NAT Gateway, Bastion
Private Subnets (AZ a, b, c):
10.0.11.0/24, 10.0.12.0/24, 10.0.13.0/24
- Application servers, Lambda
Database Subnets (AZ a, b, c):
10.0.21.0/24, 10.0.22.0/24, 10.0.23.0/24
- RDS, ElastiCacheVPC Endpoints (Cost Savings)
# Interface endpoint for Secrets Manager
SecretsManagerEndpoint:
Type: AWS::EC2::VPCEndpoint
Properties:
VpcId: !Ref VPC
ServiceName: !Sub com.amazonaws.${AWS::Region}.secretsmanager
VpcEndpointType: Interface
SubnetIds: !Ref PrivateSubnets
SecurityGroupIds:
- !Ref EndpointSecurityGroup---
Security and Identity
IAM Best Practices
// Least privilege policy example
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:Query"
],
"Resource": "arn:aws:dynamodb:us-east-1:123456789:table/users",
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": ["${aws:userid}"]
}
}
}
]
}Secrets Manager vs Parameter Store
| Factor | Secrets Manager | Parameter Store |
|---|---|---|
| Auto-rotation | Built-in | Manual |
| Cross-account | Yes | Limited |
| Pricing | $0.40/secret/month | Free (standard) |
| Use case | Credentials, API keys | Config, non-secrets |
Cognito Configuration
UserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: my-app-users
AutoVerifiedAttributes:
- email
MfaConfiguration: OPTIONAL
EnabledMfas:
- SOFTWARE_TOKEN_MFA
Policies:
PasswordPolicy:
MinimumLength: 12
RequireLowercase: true
RequireUppercase: true
RequireNumbers: true
RequireSymbols: true
AccountRecoverySetting:
RecoveryMechanisms:
- Name: verified_email
Priority: 1"""
AWS architecture design and service recommendation module.
Generates architecture patterns based on application requirements.
"""
from typing import Dict, List, Any, Optional
from enum import Enum
class ApplicationType(Enum):
"""Types of applications supported."""
WEB_APP = "web_application"
MOBILE_BACKEND = "mobile_backend"
DATA_PIPELINE = "data_pipeline"
MICROSERVICES = "microservices"
SAAS_PLATFORM = "saas_platform"
IOT_PLATFORM = "iot_platform"
class ArchitectureDesigner:
"""Design AWS architectures based on requirements."""
def __init__(self, requirements: Dict[str, Any]):
"""
Initialize with application requirements.
Args:
requirements: Dictionary containing app type, traffic, budget, etc.
"""
self.app_type = requirements.get('application_type', 'web_application')
self.expected_users = requirements.get('expected_users', 1000)
self.requests_per_second = requirements.get('requests_per_second', 10)
self.budget_monthly = requirements.get('budget_monthly_usd', 500)
self.team_size = requirements.get('team_size', 3)
self.aws_experience = requirements.get('aws_experience', 'beginner')
self.compliance_needs = requirements.get('compliance', [])
self.data_size_gb = requirements.get('data_size_gb', 10)
def recommend_architecture_pattern(self) -> Dict[str, Any]:
"""
Recommend architecture pattern based on requirements.
Returns:
Dictionary with recommended pattern and services
"""
# Determine pattern based on app type and scale
if self.app_type in ['web_application', 'saas_platform']:
if self.expected_users < 10000:
return self._serverless_web_architecture()
elif self.expected_users < 100000:
return self._modern_three_tier_architecture()
else:
return self._multi_region_architecture()
elif self.app_type == 'mobile_backend':
return self._serverless_mobile_backend()
elif self.app_type == 'data_pipeline':
return self._event_driven_data_pipeline()
elif self.app_type == 'microservices':
return self._event_driven_microservices()
elif self.app_type == 'iot_platform':
return self._iot_architecture()
else:
return self._serverless_web_architecture() # Default
def _serverless_web_architecture(self) -> Dict[str, Any]:
"""Serverless web application pattern."""
return {
'pattern_name': 'Serverless Web Application',
'description': 'Fully serverless architecture with zero server management',
'use_case': 'SaaS platforms, low to medium traffic websites, MVPs',
'services': {
'frontend': {
'service': 'S3 + CloudFront',
'purpose': 'Static website hosting with global CDN',
'configuration': {
's3_bucket': 'website-bucket',
'cloudfront_distribution': 'HTTPS with custom domain',
'caching': 'Cache-Control headers, edge caching'
}
},
'api': {
'service': 'API Gateway + Lambda',
'purpose': 'REST API backend with auto-scaling',
'configuration': {
'api_type': 'REST API',
'authorization': 'Cognito User Pools or API Keys',
'throttling': f'{self.requests_per_second * 10} requests/second',
'lambda_memory': '512 MB (optimize based on testing)',
'lambda_timeout': '10 seconds'
}
},
'database': {
'service': 'DynamoDB',
'purpose': 'NoSQL database with pay-per-request pricing',
'configuration': {
'billing_mode': 'PAY_PER_REQUEST',
'backup': 'Point-in-time recovery enabled',
'encryption': 'KMS encryption at rest'
}
},
'authentication': {
'service': 'Cognito',
'purpose': 'User authentication and authorization',
'configuration': {
'user_pools': 'Email/password + social providers',
'mfa': 'Optional MFA with SMS or TOTP',
'token_expiration': '1 hour access, 30 days refresh'
}
},
'cicd': {
'service': 'AWS Amplify or CodePipeline',
'purpose': 'Automated deployment from Git',
'configuration': {
'source': 'GitHub or CodeCommit',
'build': 'Automatic on commit',
'environments': 'dev, staging, production'
}
}
},
'estimated_cost': {
'monthly_usd': self._calculate_serverless_cost(),
'breakdown': {
'CloudFront': '10-30 USD',
'Lambda': '5-20 USD',
'API Gateway': '10-40 USD',
'DynamoDB': '5-30 USD',
'Cognito': '0-10 USD (free tier: 50k MAU)',
'S3': '1-5 USD'
}
},
'pros': [
'No server management',
'Auto-scaling built-in',
'Pay only for what you use',
'Fast to deploy and iterate',
'High availability by default'
],
'cons': [
'Cold start latency (100-500ms)',
'Vendor lock-in to AWS',
'Debugging distributed systems complex',
'Learning curve for serverless patterns'
],
'scaling_characteristics': {
'users_supported': '1k - 100k',
'requests_per_second': '100 - 10,000',
'scaling_method': 'Automatic (Lambda concurrency)'
}
}
def _modern_three_tier_architecture(self) -> Dict[str, Any]:
"""Traditional three-tier with modern AWS services."""
return {
'pattern_name': 'Modern Three-Tier Application',
'description': 'Classic architecture with containers and managed services',
'use_case': 'Traditional web apps, e-commerce, content management',
'services': {
'load_balancer': {
'service': 'Application Load Balancer (ALB)',
'purpose': 'Distribute traffic across instances',
'configuration': {
'scheme': 'internet-facing',
'target_type': 'ECS tasks or EC2 instances',
'health_checks': '/health endpoint, 30s interval',
'ssl': 'ACM certificate for HTTPS'
}
},
'compute': {
'service': 'ECS Fargate or EC2 Auto Scaling',
'purpose': 'Run containerized applications',
'configuration': {
'container_platform': 'ECS Fargate (serverless containers)',
'task_definition': '512 MB memory, 0.25 vCPU (start small)',
'auto_scaling': f'2-{max(4, self.expected_users // 5000)} tasks',
'deployment': 'Rolling update, 50% at a time'
}
},
'database': {
'service': 'RDS Aurora (MySQL/PostgreSQL)',
'purpose': 'Managed relational database',
'configuration': {
'instance_class': 'db.t3.medium or db.t4g.medium',
'multi_az': 'Yes (high availability)',
'read_replicas': '1-2 for read scaling',
'backup_retention': '7 days',
'encryption': 'KMS encryption enabled'
}
},
'cache': {
'service': 'ElastiCache Redis',
'purpose': 'Session storage, application caching',
'configuration': {
'node_type': 'cache.t3.micro or cache.t4g.micro',
'replication': 'Multi-AZ with automatic failover',
'eviction_policy': 'allkeys-lru'
}
},
'cdn': {
'service': 'CloudFront',
'purpose': 'Cache static assets globally',
'configuration': {
'origins': 'ALB (dynamic), S3 (static)',
'caching': 'Cache based on headers/cookies',
'compression': 'Gzip compression enabled'
}
},
'storage': {
'service': 'S3',
'purpose': 'User uploads, backups, logs',
'configuration': {
'storage_class': 'S3 Standard with lifecycle policies',
'versioning': 'Enabled for important buckets',
'lifecycle': 'Transition to IA after 30 days'
}
}
},
'estimated_cost': {
'monthly_usd': self._calculate_three_tier_cost(),
'breakdown': {
'ALB': '20-30 USD',
'ECS Fargate': '50-200 USD',
'RDS Aurora': '100-300 USD',
'ElastiCache': '30-80 USD',
'CloudFront': '10-50 USD',
'S3': '10-30 USD'
}
},
'pros': [
'Proven architecture pattern',
'Easy to understand and debug',
'Flexible scaling options',
'Support for complex applications',
'Managed services reduce operational burden'
],
'cons': [
'Higher baseline costs',
'More complex than serverless',
'Requires more operational knowledge',
'Manual scaling configuration needed'
],
'scaling_characteristics': {
'users_supported': '10k - 500k',
'requests_per_second': '1,000 - 50,000',
'scaling_method': 'Auto Scaling based on CPU/memory/requests'
}
}
def _serverless_mobile_backend(self) -> Dict[str, Any]:
"""Serverless mobile backend with GraphQL."""
return {
'pattern_name': 'Serverless Mobile Backend',
'description': 'Mobile-first backend with GraphQL and real-time features',
'use_case': 'Mobile apps, single-page apps, offline-first applications',
'services': {
'api': {
'service': 'AppSync (GraphQL)',
'purpose': 'Flexible GraphQL API with real-time subscriptions',
'configuration': {
'api_type': 'GraphQL',
'authorization': 'Cognito User Pools + API Keys',
'resolvers': 'Direct DynamoDB or Lambda',
'subscriptions': 'WebSocket for real-time updates',
'caching': 'Server-side caching (1 hour TTL)'
}
},
'database': {
'service': 'DynamoDB',
'purpose': 'Fast NoSQL database with global tables',
'configuration': {
'billing_mode': 'PAY_PER_REQUEST (on-demand)',
'global_tables': 'Multi-region if needed',
'streams': 'Enabled for change data capture',
'ttl': 'Automatic expiration for temporary data'
}
},
'file_storage': {
'service': 'S3 + CloudFront',
'purpose': 'User uploads (images, videos, documents)',
'configuration': {
'access': 'Signed URLs or Cognito credentials',
'lifecycle': 'Intelligent-Tiering for cost optimization',
'cdn': 'CloudFront for fast global delivery'
}
},
'authentication': {
'service': 'Cognito',
'purpose': 'User management and federation',
'configuration': {
'identity_providers': 'Email, Google, Apple, Facebook',
'mfa': 'SMS or TOTP',
'groups': 'Admin, premium, free tiers',
'custom_attributes': 'User metadata storage'
}
},
'push_notifications': {
'service': 'SNS Mobile Push',
'purpose': 'Push notifications to mobile devices',
'configuration': {
'platforms': 'iOS (APNs), Android (FCM)',
'topics': 'Group notifications by topic',
'delivery_status': 'CloudWatch Logs for tracking'
}
},
'analytics': {
'service': 'Pinpoint',
'purpose': 'User analytics and engagement',
'configuration': {
'events': 'Custom events tracking',
'campaigns': 'Targeted messaging',
'segments': 'User segmentation'
}
}
},
'estimated_cost': {
'monthly_usd': 50 + (self.expected_users * 0.005),
'breakdown': {
'AppSync': '5-40 USD',
'DynamoDB': '10-50 USD',
'Cognito': '0-15 USD',
'S3 + CloudFront': '10-40 USD',
'SNS': '1-10 USD',
'Pinpoint': '10-30 USD'
}
},
'pros': [
'Single GraphQL endpoint',
'Real-time subscriptions built-in',
'Offline-first capabilities',
'Auto-generated mobile SDK',
'Flexible querying (no over/under fetching)'
],
'cons': [
'GraphQL learning curve',
'Complex queries can be expensive',
'Debugging subscriptions challenging',
'Limited to AWS AppSync features'
],
'scaling_characteristics': {
'users_supported': '1k - 1M',
'requests_per_second': '100 - 100,000',
'scaling_method': 'Automatic (AppSync managed)'
}
}
def _event_driven_microservices(self) -> Dict[str, Any]:
"""Event-driven microservices architecture."""
return {
'pattern_name': 'Event-Driven Microservices',
'description': 'Loosely coupled services with event bus',
'use_case': 'Complex business workflows, asynchronous processing',
'services': {
'event_bus': {
'service': 'EventBridge',
'purpose': 'Central event routing between services',
'configuration': {
'bus_type': 'Custom event bus',
'rules': 'Route events by type/source',
'targets': 'Lambda, SQS, Step Functions',
'archive': 'Event replay capability'
}
},
'compute': {
'service': 'Lambda + ECS Fargate (hybrid)',
'purpose': 'Service implementation',
'configuration': {
'lambda': 'Lightweight services, event handlers',
'fargate': 'Long-running services, heavy processing',
'auto_scaling': 'Lambda (automatic), Fargate (target tracking)'
}
},
'queues': {
'service': 'SQS',
'purpose': 'Decouple services, handle failures',
'configuration': {
'queue_type': 'Standard (high throughput) or FIFO (ordering)',
'dlq': 'Dead letter queue after 3 retries',
'visibility_timeout': '30 seconds (adjust per service)',
'retention': '4 days'
}
},
'orchestration': {
'service': 'Step Functions',
'purpose': 'Complex workflows, saga patterns',
'configuration': {
'type': 'Standard (long-running) or Express (high volume)',
'error_handling': 'Retry, catch, rollback logic',
'timeouts': 'Per-state timeouts',
'logging': 'CloudWatch Logs integration'
}
},
'database': {
'service': 'DynamoDB (per service)',
'purpose': 'Each microservice owns its data',
'configuration': {
'pattern': 'Database per service',
'streams': 'DynamoDB Streams for change events',
'backup': 'Point-in-time recovery'
}
},
'api_gateway': {
'service': 'API Gateway',
'purpose': 'Unified API facade',
'configuration': {
'integration': 'Lambda proxy or HTTP proxy',
'authentication': 'Cognito or Lambda authorizer',
'rate_limiting': 'Per-client throttling'
}
}
},
'estimated_cost': {
'monthly_usd': 100 + (self.expected_users * 0.01),
'breakdown': {
'EventBridge': '5-20 USD',
'Lambda': '20-100 USD',
'SQS': '1-10 USD',
'Step Functions': '10-50 USD',
'DynamoDB': '30-150 USD',
'API Gateway': '10-40 USD'
}
},
'pros': [
'Loose coupling between services',
'Independent scaling and deployment',
'Failure isolation',
'Technology diversity possible',
'Easy to test individual services'
],
'cons': [
'Operational complexity',
'Distributed tracing required',
'Eventual consistency challenges',
'Network latency between services',
'More moving parts to monitor'
],
'scaling_characteristics': {
'users_supported': '10k - 10M',
'requests_per_second': '1,000 - 1,000,000',
'scaling_method': 'Per-service auto-scaling'
}
}
def _event_driven_data_pipeline(self) -> Dict[str, Any]:
"""Real-time data processing pipeline."""
return {
'pattern_name': 'Real-Time Data Pipeline',
'description': 'Scalable data ingestion and processing',
'use_case': 'Analytics, IoT data, log processing, ETL',
'services': {
'ingestion': {
'service': 'Kinesis Data Streams',
'purpose': 'Real-time data ingestion',
'configuration': {
'shards': f'{max(1, self.data_size_gb // 10)} shards',
'retention': '24 hours (extend to 7 days if needed)',
'encryption': 'KMS encryption'
}
},
'processing': {
'service': 'Lambda or Kinesis Analytics',
'purpose': 'Transform and enrich data',
'configuration': {
'lambda_concurrency': 'Match shard count',
'batch_size': '100-500 records per invocation',
'error_handling': 'DLQ for failed records'
}
},
'storage': {
'service': 'S3 Data Lake',
'purpose': 'Long-term storage and analytics',
'configuration': {
'format': 'Parquet (compressed, columnar)',
'partitioning': 'By date (year/month/day/hour)',
'lifecycle': 'Transition to Glacier after 90 days',
'catalog': 'AWS Glue Data Catalog'
}
},
'analytics': {
'service': 'Athena',
'purpose': 'SQL queries on S3 data',
'configuration': {
'query_results': 'Store in separate S3 bucket',
'workgroups': 'Separate dev and prod',
'cost_controls': 'Query limits per workgroup'
}
},
'visualization': {
'service': 'QuickSight',
'purpose': 'Business intelligence dashboards',
'configuration': {
'source': 'Athena or direct S3',
'refresh': 'Hourly or daily',
'sharing': 'Embedded dashboards or web access'
}
},
'alerting': {
'service': 'CloudWatch + SNS',
'purpose': 'Monitor metrics and alerts',
'configuration': {
'metrics': 'Custom metrics from processing',
'alarms': 'Threshold-based alerts',
'notifications': 'Email, Slack, PagerDuty'
}
}
},
'estimated_cost': {
'monthly_usd': self._calculate_data_pipeline_cost(),
'breakdown': {
'Kinesis': '15-100 USD (per shard)',
'Lambda': '10-50 USD',
'S3': '10-50 USD',
'Athena': '5-30 USD (per TB scanned)',
'QuickSight': '9-18 USD per user',
'Glue': '5-20 USD'
}
},
'pros': [
'Real-time processing capability',
'Scales to millions of events',
'Cost-effective long-term storage',
'SQL analytics on raw data',
'Serverless architecture'
],
'cons': [
'Kinesis shard management required',
'Athena costs based on data scanned',
'Schema evolution complexity',
'Cold data queries can be slow'
],
'scaling_characteristics': {
'events_per_second': '1,000 - 1,000,000',
'data_volume': '1 GB - 1 PB per day',
'scaling_method': 'Add Kinesis shards, partition S3 data'
}
}
def _iot_architecture(self) -> Dict[str, Any]:
"""IoT platform architecture."""
return {
'pattern_name': 'IoT Platform',
'description': 'Scalable IoT device management and data processing',
'use_case': 'Connected devices, sensors, smart devices',
'services': {
'device_management': {
'service': 'IoT Core',
'purpose': 'Device connectivity and management',
'configuration': {
'protocol': 'MQTT over TLS',
'thing_registry': 'Device metadata storage',
'device_shadow': 'Desired and reported state',
'rules_engine': 'Route messages to services'
}
},
'device_provisioning': {
'service': 'IoT Device Management',
'purpose': 'Fleet provisioning and updates',
'configuration': {
'fleet_indexing': 'Search devices',
'jobs': 'OTA firmware updates',
'bulk_operations': 'Manage device groups'
}
},
'data_processing': {
'service': 'IoT Analytics',
'purpose': 'Process and analyze IoT data',
'configuration': {
'channels': 'Ingest device data',
'pipelines': 'Transform and enrich',
'data_store': 'Time-series storage',
'notebooks': 'Jupyter notebooks for analysis'
}
},
'time_series_db': {
'service': 'Timestream',
'purpose': 'Store time-series metrics',
'configuration': {
'memory_store': 'Recent data (hours)',
'magnetic_store': 'Historical data (years)',
'retention': 'Auto-tier based on age'
}
},
'real_time_alerts': {
'service': 'IoT Events',
'purpose': 'Detect and respond to events',
'configuration': {
'detector_models': 'Define alert conditions',
'actions': 'SNS, Lambda, SQS',
'state_tracking': 'Per-device state machines'
}
}
},
'estimated_cost': {
'monthly_usd': 50 + (self.expected_users * 0.1), # Expected_users = device count
'breakdown': {
'IoT Core': '10-100 USD (per million messages)',
'IoT Analytics': '5-50 USD',
'Timestream': '10-80 USD',
'IoT Events': '1-20 USD',
'Data transfer': '10-50 USD'
}
},
'pros': [
'Built for IoT scale',
'Secure device connectivity',
'Managed device lifecycle',
'Time-series optimized',
'Real-time event detection'
],
'cons': [
'IoT-specific pricing model',
'MQTT protocol required',
'Regional limitations',
'Complexity for simple use cases'
],
'scaling_characteristics': {
'devices_supported': '100 - 10,000,000',
'messages_per_second': '1,000 - 100,000',
'scaling_method': 'Automatic (managed service)'
}
}
def _multi_region_architecture(self) -> Dict[str, Any]:
"""Multi-region high availability architecture."""
return {
'pattern_name': 'Multi-Region High Availability',
'description': 'Global deployment with disaster recovery',
'use_case': 'Global applications, 99.99% uptime, compliance',
'services': {
'dns': {
'service': 'Route 53',
'purpose': 'Global traffic routing',
'configuration': {
'routing_policy': 'Geolocation or latency-based',
'health_checks': 'Active monitoring with failover',
'failover': 'Automatic to secondary region'
}
},
'cdn': {
'service': 'CloudFront',
'purpose': 'Edge caching and acceleration',
'configuration': {
'origins': 'Multiple regions (primary + secondary)',
'origin_failover': 'Automatic failover',
'edge_locations': 'Global (400+ locations)'
}
},
'compute': {
'service': 'Multi-region Lambda or ECS',
'purpose': 'Active-active deployment',
'configuration': {
'regions': 'us-east-1 (primary), eu-west-1 (secondary)',
'deployment': 'Blue/Green in each region',
'traffic_split': '70/30 or 50/50'
}
},
'database': {
'service': 'DynamoDB Global Tables or Aurora Global',
'purpose': 'Multi-region replication',
'configuration': {
'replication': 'Sub-second replication lag',
'read_locality': 'Read from nearest region',
'write_forwarding': 'Aurora Global write forwarding',
'conflict_resolution': 'Last writer wins'
}
},
'storage': {
'service': 'S3 Cross-Region Replication',
'purpose': 'Replicate data across regions',
'configuration': {
'replication': 'Async replication to secondary',
'versioning': 'Required for CRR',
'replication_time_control': '15 minutes SLA'
}
}
},
'estimated_cost': {
'monthly_usd': self._calculate_three_tier_cost() * 1.8,
'breakdown': {
'Route 53': '10-30 USD',
'CloudFront': '20-100 USD',
'Compute (2 regions)': '100-500 USD',
'Database (Global Tables)': '200-800 USD',
'Data transfer (cross-region)': '50-200 USD'
}
},
'pros': [
'Global low latency',
'High availability (99.99%+)',
'Disaster recovery built-in',
'Data sovereignty compliance',
'Automatic failover'
],
'cons': [
'1.5-2x costs vs single region',
'Complex deployment pipeline',
'Data consistency challenges',
'More operational overhead',
'Cross-region data transfer costs'
],
'scaling_characteristics': {
'users_supported': '100k - 100M',
'requests_per_second': '10,000 - 10,000,000',
'scaling_method': 'Per-region auto-scaling + global routing'
}
}
def _calculate_serverless_cost(self) -> float:
"""Estimate serverless architecture cost."""
requests_per_month = self.requests_per_second * 2_592_000 # 30 days
lambda_cost = (requests_per_month / 1_000_000) * 0.20 # $0.20 per 1M requests
api_gateway_cost = (requests_per_month / 1_000_000) * 3.50 # $3.50 per 1M requests
dynamodb_cost = max(5, self.data_size_gb * 0.25) # $0.25 per GB/month
cloudfront_cost = max(10, self.expected_users * 0.01)
total = lambda_cost + api_gateway_cost + dynamodb_cost + cloudfront_cost
return min(total, self.budget_monthly) # Cap at budget
def _calculate_three_tier_cost(self) -> float:
"""Estimate three-tier architecture cost."""
fargate_tasks = max(2, self.expected_users // 5000)
fargate_cost = fargate_tasks * 30 # ~$30 per task/month
rds_cost = 150 # db.t3.medium baseline
elasticache_cost = 40 # cache.t3.micro
alb_cost = 25
total = fargate_cost + rds_cost + elasticache_cost + alb_cost
return min(total, self.budget_monthly)
def _calculate_data_pipeline_cost(self) -> float:
"""Estimate data pipeline cost."""
shards = max(1, self.data_size_gb // 10)
kinesis_cost = shards * 15 # $15 per shard/month
s3_cost = self.data_size_gb * 0.023 # $0.023 per GB/month
lambda_cost = 20 # Processing
athena_cost = 15 # Queries
total = kinesis_cost + s3_cost + lambda_cost + athena_cost
return min(total, self.budget_monthly)
def generate_service_checklist(self) -> List[Dict[str, Any]]:
"""Generate implementation checklist for recommended architecture."""
architecture = self.recommend_architecture_pattern()
checklist = [
{
'phase': 'Planning',
'tasks': [
'Review architecture pattern and services',
'Estimate costs using AWS Pricing Calculator',
'Define environment strategy (dev, staging, prod)',
'Set up AWS Organization and accounts',
'Define tagging strategy for resources'
]
},
{
'phase': 'Foundation',
'tasks': [
'Create VPC with public/private subnets',
'Configure NAT Gateway or VPC endpoints',
'Set up IAM roles and policies',
'Enable CloudTrail for audit logging',
'Configure AWS Config for compliance'
]
},
{
'phase': 'Core Services',
'tasks': [
f"Deploy {service['service']}"
for service in architecture['services'].values()
]
},
{
'phase': 'Security',
'tasks': [
'Configure security groups and NACLs',
'Enable encryption (KMS) for all services',
'Set up AWS WAF rules',
'Configure Secrets Manager',
'Enable GuardDuty for threat detection'
]
},
{
'phase': 'Monitoring',
'tasks': [
'Create CloudWatch dashboards',
'Set up alarms for critical metrics',
'Configure SNS topics for notifications',
'Enable X-Ray for distributed tracing',
'Set up log aggregation and retention'
]
},
{
'phase': 'CI/CD',
'tasks': [
'Set up CodePipeline or GitHub Actions',
'Configure automated testing',
'Implement blue/green deployment',
'Set up rollback procedures',
'Document deployment process'
]
}
]
return checklist
"""
AWS cost optimization analyzer.
Provides cost-saving recommendations for startup budgets.
"""
from typing import Dict, List, Any, Optional
class CostOptimizer:
"""Analyze AWS costs and provide optimization recommendations."""
def __init__(self, current_resources: Dict[str, Any], monthly_spend: float):
"""
Initialize with current AWS resources and spending.
Args:
current_resources: Dictionary of current AWS resources
monthly_spend: Current monthly AWS spend in USD
"""
self.resources = current_resources
self.monthly_spend = monthly_spend
self.recommendations = []
def analyze_and_optimize(self) -> Dict[str, Any]:
"""
Analyze current setup and generate cost optimization recommendations.
Returns:
Dictionary with recommendations and potential savings
"""
self.recommendations = []
potential_savings = 0.0
# Analyze compute resources
compute_savings = self._analyze_compute()
potential_savings += compute_savings
# Analyze storage
storage_savings = self._analyze_storage()
potential_savings += storage_savings
# Analyze database
database_savings = self._analyze_database()
potential_savings += database_savings
# Analyze networking
network_savings = self._analyze_networking()
potential_savings += network_savings
# General AWS optimizations
general_savings = self._analyze_general_optimizations()
potential_savings += general_savings
return {
'current_monthly_spend': self.monthly_spend,
'potential_monthly_savings': round(potential_savings, 2),
'optimized_monthly_spend': round(self.monthly_spend - potential_savings, 2),
'savings_percentage': round((potential_savings / self.monthly_spend) * 100, 2) if self.monthly_spend > 0 else 0,
'recommendations': self.recommendations,
'priority_actions': self._prioritize_recommendations()
}
def _analyze_compute(self) -> float:
"""Analyze compute resources (EC2, Lambda, Fargate)."""
savings = 0.0
ec2_instances = self.resources.get('ec2_instances', [])
if ec2_instances:
# Check for idle instances
idle_count = sum(1 for inst in ec2_instances if inst.get('cpu_utilization', 100) < 10)
if idle_count > 0:
idle_cost = idle_count * 50 # Assume $50/month per idle instance
savings += idle_cost
self.recommendations.append({
'service': 'EC2',
'type': 'Idle Resources',
'issue': f'{idle_count} EC2 instances with <10% CPU utilization',
'recommendation': 'Stop or terminate idle instances, or downsize to smaller instance types',
'potential_savings': idle_cost,
'priority': 'high'
})
# Check for Savings Plans / Reserved Instances
on_demand_count = sum(1 for inst in ec2_instances if inst.get('pricing', 'on-demand') == 'on-demand')
if on_demand_count >= 2:
ri_savings = on_demand_count * 50 * 0.30 # 30% savings with RIs
savings += ri_savings
self.recommendations.append({
'service': 'EC2',
'type': 'Pricing Optimization',
'issue': f'{on_demand_count} instances on On-Demand pricing',
'recommendation': 'Purchase Compute Savings Plan or Reserved Instances for predictable workloads (1-year commitment)',
'potential_savings': ri_savings,
'priority': 'medium'
})
# Lambda optimization
lambda_functions = self.resources.get('lambda_functions', [])
if lambda_functions:
oversized = sum(1 for fn in lambda_functions if fn.get('memory_mb', 128) > 512 and fn.get('avg_memory_used_mb', 0) < 256)
if oversized > 0:
lambda_savings = oversized * 5 # Assume $5/month per oversized function
savings += lambda_savings
self.recommendations.append({
'service': 'Lambda',
'type': 'Right-sizing',
'issue': f'{oversized} Lambda functions over-provisioned (memory too high)',
'recommendation': 'Use AWS Lambda Power Tuning tool to optimize memory settings',
'potential_savings': lambda_savings,
'priority': 'low'
})
return savings
def _analyze_storage(self) -> float:
"""Analyze S3 and other storage resources."""
savings = 0.0
s3_buckets = self.resources.get('s3_buckets', [])
for bucket in s3_buckets:
size_gb = bucket.get('size_gb', 0)
storage_class = bucket.get('storage_class', 'STANDARD')
# Check for lifecycle policies
if not bucket.get('has_lifecycle_policy', False) and size_gb > 100:
lifecycle_savings = size_gb * 0.015 # $0.015/GB savings with IA transition
savings += lifecycle_savings
self.recommendations.append({
'service': 'S3',
'type': 'Lifecycle Policy',
'issue': f'Bucket {bucket.get("name", "unknown")} ({size_gb} GB) has no lifecycle policy',
'recommendation': 'Implement lifecycle policy: Transition to IA after 30 days, Glacier after 90 days',
'potential_savings': lifecycle_savings,
'priority': 'medium'
})
# Check for Intelligent-Tiering
if storage_class == 'STANDARD' and size_gb > 500:
tiering_savings = size_gb * 0.005
savings += tiering_savings
self.recommendations.append({
'service': 'S3',
'type': 'Storage Class',
'issue': f'Large bucket ({size_gb} GB) using STANDARD storage',
'recommendation': 'Enable S3 Intelligent-Tiering for automatic cost optimization',
'potential_savings': tiering_savings,
'priority': 'high'
})
return savings
def _analyze_database(self) -> float:
"""Analyze RDS, DynamoDB, and other database costs."""
savings = 0.0
rds_instances = self.resources.get('rds_instances', [])
for db in rds_instances:
# Check for idle databases
if db.get('connections_per_day', 1000) < 10:
db_cost = db.get('monthly_cost', 100)
savings += db_cost * 0.8 # Can save 80% by stopping
self.recommendations.append({
'service': 'RDS',
'type': 'Idle Resource',
'issue': f'Database {db.get("name", "unknown")} has <10 connections/day',
'recommendation': 'Stop database if not needed, or take final snapshot and delete',
'potential_savings': db_cost * 0.8,
'priority': 'high'
})
# Check for Aurora Serverless opportunity
if db.get('engine', '').startswith('aurora') and db.get('utilization', 100) < 30:
serverless_savings = db.get('monthly_cost', 200) * 0.40
savings += serverless_savings
self.recommendations.append({
'service': 'RDS Aurora',
'type': 'Serverless Migration',
'issue': f'Aurora instance {db.get("name", "unknown")} has low utilization (<30%)',
'recommendation': 'Migrate to Aurora Serverless v2 for auto-scaling and pay-per-use',
'potential_savings': serverless_savings,
'priority': 'medium'
})
# DynamoDB optimization
dynamodb_tables = self.resources.get('dynamodb_tables', [])
for table in dynamodb_tables:
if table.get('billing_mode', 'PROVISIONED') == 'PROVISIONED':
read_capacity = table.get('read_capacity_units', 0)
write_capacity = table.get('write_capacity_units', 0)
utilization = table.get('utilization_percentage', 100)
if utilization < 20:
on_demand_savings = (read_capacity * 0.00013 + write_capacity * 0.00065) * 730 * 0.3
savings += on_demand_savings
self.recommendations.append({
'service': 'DynamoDB',
'type': 'Billing Mode',
'issue': f'Table {table.get("name", "unknown")} has low utilization with provisioned capacity',
'recommendation': 'Switch to On-Demand billing mode for variable workloads',
'potential_savings': on_demand_savings,
'priority': 'medium'
})
return savings
def _analyze_networking(self) -> float:
"""Analyze networking costs (data transfer, NAT Gateway, etc.)."""
savings = 0.0
nat_gateways = self.resources.get('nat_gateways', [])
if len(nat_gateways) > 1:
multi_az = self.resources.get('multi_az_required', False)
if not multi_az:
nat_savings = (len(nat_gateways) - 1) * 45 # $45/month per NAT Gateway
savings += nat_savings
self.recommendations.append({
'service': 'NAT Gateway',
'type': 'Resource Consolidation',
'issue': f'{len(nat_gateways)} NAT Gateways deployed (multi-AZ not required)',
'recommendation': 'Use single NAT Gateway in dev/staging, or consider VPC endpoints for AWS services',
'potential_savings': nat_savings,
'priority': 'high'
})
# Check for VPC endpoints opportunity
if not self.resources.get('vpc_endpoints', []):
s3_data_transfer = self.resources.get('s3_data_transfer_gb', 0)
if s3_data_transfer > 100:
endpoint_savings = s3_data_transfer * 0.09 * 0.5 # Save 50% of data transfer costs
savings += endpoint_savings
self.recommendations.append({
'service': 'VPC',
'type': 'VPC Endpoints',
'issue': 'High S3 data transfer without VPC endpoints',
'recommendation': 'Create VPC endpoints for S3 and DynamoDB to avoid NAT Gateway costs',
'potential_savings': endpoint_savings,
'priority': 'medium'
})
return savings
def _analyze_general_optimizations(self) -> float:
"""General AWS cost optimizations."""
savings = 0.0
# Check for CloudWatch Logs retention
log_groups = self.resources.get('cloudwatch_log_groups', [])
for log in log_groups:
if log.get('retention_days', 1) == -1: # Never expire
log_size_gb = log.get('size_gb', 1)
retention_savings = log_size_gb * 0.50 * 0.7 # 70% savings with 7-day retention
savings += retention_savings
self.recommendations.append({
'service': 'CloudWatch Logs',
'type': 'Retention Policy',
'issue': f'Log group {log.get("name", "unknown")} has infinite retention',
'recommendation': 'Set retention to 7 days for non-compliance logs, 30 days for production',
'potential_savings': retention_savings,
'priority': 'low'
})
# Check for unused Elastic IPs
elastic_ips = self.resources.get('elastic_ips', [])
unattached = sum(1 for eip in elastic_ips if not eip.get('attached', True))
if unattached > 0:
eip_savings = unattached * 3.65 # $0.005/hour = $3.65/month
savings += eip_savings
self.recommendations.append({
'service': 'EC2',
'type': 'Unused Resources',
'issue': f'{unattached} unattached Elastic IPs',
'recommendation': 'Release unused Elastic IPs to avoid hourly charges',
'potential_savings': eip_savings,
'priority': 'high'
})
# Budget alerts
if not self.resources.get('has_budget_alerts', False):
self.recommendations.append({
'service': 'AWS Budgets',
'type': 'Cost Monitoring',
'issue': 'No budget alerts configured',
'recommendation': 'Set up AWS Budgets with alerts at 50%, 80%, 100% of monthly budget',
'potential_savings': 0,
'priority': 'high'
})
# Cost Explorer recommendations
if not self.resources.get('has_cost_explorer', False):
self.recommendations.append({
'service': 'Cost Management',
'type': 'Visibility',
'issue': 'Cost Explorer not enabled',
'recommendation': 'Enable AWS Cost Explorer to track spending patterns and identify anomalies',
'potential_savings': 0,
'priority': 'medium'
})
return savings
def _prioritize_recommendations(self) -> List[Dict[str, Any]]:
"""Get top priority recommendations."""
high_priority = [r for r in self.recommendations if r['priority'] == 'high']
high_priority.sort(key=lambda x: x.get('potential_savings', 0), reverse=True)
return high_priority[:5] # Top 5 high-priority recommendations
def generate_optimization_checklist(self) -> List[Dict[str, Any]]:
"""Generate actionable checklist for cost optimization."""
return [
{
'category': 'Immediate Actions (Today)',
'items': [
'Release unattached Elastic IPs',
'Stop idle EC2 instances',
'Delete unused EBS volumes',
'Set up budget alerts'
]
},
{
'category': 'This Week',
'items': [
'Implement S3 lifecycle policies',
'Consolidate NAT Gateways in non-prod',
'Set CloudWatch Logs retention to 7 days',
'Review and rightsize EC2/RDS instances'
]
},
{
'category': 'This Month',
'items': [
'Evaluate Savings Plans or Reserved Instances',
'Migrate to Aurora Serverless where applicable',
'Implement VPC endpoints for S3/DynamoDB',
'Switch DynamoDB tables to On-Demand if variable load'
]
},
{
'category': 'Ongoing',
'items': [
'Review Cost Explorer weekly',
'Tag all resources for cost allocation',
'Monitor Trusted Advisor recommendations',
'Conduct monthly cost review meetings'
]
}
]
"""
Serverless stack generator for AWS.
Creates CloudFormation/CDK templates for serverless applications.
"""
from typing import Dict, List, Any, Optional
class ServerlessStackGenerator:
"""Generate serverless application stacks."""
def __init__(self, app_name: str, requirements: Dict[str, Any]):
"""
Initialize with application requirements.
Args:
app_name: Application name (used for resource naming)
requirements: Dictionary with API, database, auth requirements
"""
self.app_name = app_name.lower().replace(' ', '-')
self.requirements = requirements
self.region = requirements.get('region', 'us-east-1')
def generate_cloudformation_template(self) -> str:
"""
Generate CloudFormation template for serverless stack.
Returns:
YAML CloudFormation template as string
"""
template = f"""AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless stack for {self.app_name}
Parameters:
Environment:
Type: String
Default: dev
AllowedValues:
- dev
- staging
- production
Description: Deployment environment
CorsAllowedOrigins:
Type: String
Default: '*'
Description: CORS allowed origins for API Gateway
Resources:
# DynamoDB Table
{self.app_name.replace('-', '')}Table:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Sub '${{Environment}}-{self.app_name}-data'
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: PK
AttributeType: S
- AttributeName: SK
AttributeType: S
KeySchema:
- AttributeName: PK
KeyType: HASH
- AttributeName: SK
KeyType: RANGE
PointInTimeRecoverySpecification:
PointInTimeRecoveryEnabled: true
SSESpecification:
SSEEnabled: true
StreamSpecification:
StreamViewType: NEW_AND_OLD_IMAGES
Tags:
- Key: Environment
Value: !Ref Environment
- Key: Application
Value: {self.app_name}
# Lambda Execution Role
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: DynamoDBAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
- dynamodb:Query
- dynamodb:Scan
Resource: !GetAtt {self.app_name.replace('-', '')}Table.Arn
# Lambda Function
ApiFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: !Sub '${{Environment}}-{self.app_name}-api'
Handler: index.handler
Runtime: nodejs18.x
CodeUri: ./src
MemorySize: 512
Timeout: 10
Role: !GetAtt LambdaExecutionRole.Arn
Environment:
Variables:
TABLE_NAME: !Ref {self.app_name.replace('-', '')}Table
ENVIRONMENT: !Ref Environment
Events:
ApiEvent:
Type: Api
Properties:
Path: /{{proxy+}}
Method: ANY
RestApiId: !Ref ApiGateway
Tags:
Environment: !Ref Environment
Application: {self.app_name}
# API Gateway
ApiGateway:
Type: AWS::Serverless::Api
Properties:
Name: !Sub '${{Environment}}-{self.app_name}-api'
StageName: !Ref Environment
Cors:
AllowMethods: "'GET,POST,PUT,DELETE,OPTIONS'"
AllowHeaders: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
AllowOrigin: !Sub "'${{CorsAllowedOrigins}}'"
Auth:
DefaultAuthorizer: CognitoAuthorizer
Authorizers:
CognitoAuthorizer:
UserPoolArn: !GetAtt UserPool.Arn
ThrottleSettings:
BurstLimit: 200
RateLimit: 100
Tags:
Environment: !Ref Environment
Application: {self.app_name}
# Cognito User Pool
UserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: !Sub '${{Environment}}-{self.app_name}-users'
UsernameAttributes:
- email
AutoVerifiedAttributes:
- email
Policies:
PasswordPolicy:
MinimumLength: 8
RequireUppercase: true
RequireLowercase: true
RequireNumbers: true
RequireSymbols: false
MfaConfiguration: OPTIONAL
EnabledMfas:
- SOFTWARE_TOKEN_MFA
UserAttributeUpdateSettings:
AttributesRequireVerificationBeforeUpdate:
- email
Schema:
- Name: email
Required: true
Mutable: true
# Cognito User Pool Client
UserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
ClientName: !Sub '${{Environment}}-{self.app_name}-client'
UserPoolId: !Ref UserPool
GenerateSecret: false
RefreshTokenValidity: 30
AccessTokenValidity: 1
IdTokenValidity: 1
TokenValidityUnits:
RefreshToken: days
AccessToken: hours
IdToken: hours
ExplicitAuthFlows:
- ALLOW_USER_SRP_AUTH
- ALLOW_REFRESH_TOKEN_AUTH
# CloudWatch Log Group
ApiLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${{Environment}}-{self.app_name}-api'
RetentionInDays: 7
Outputs:
ApiUrl:
Description: API Gateway endpoint URL
Value: !Sub 'https://${{ApiGateway}}.execute-api.${{AWS::Region}}.amazonaws.com/${{Environment}}'
Export:
Name: !Sub '${{Environment}}-{self.app_name}-ApiUrl'
UserPoolId:
Description: Cognito User Pool ID
Value: !Ref UserPool
Export:
Name: !Sub '${{Environment}}-{self.app_name}-UserPoolId'
UserPoolClientId:
Description: Cognito User Pool Client ID
Value: !Ref UserPoolClient
Export:
Name: !Sub '${{Environment}}-{self.app_name}-UserPoolClientId'
TableName:
Description: DynamoDB Table Name
Value: !Ref {self.app_name.replace('-', '')}Table
Export:
Name: !Sub '${{Environment}}-{self.app_name}-TableName'
"""
return template
def generate_cdk_stack(self) -> str:
"""
Generate AWS CDK stack in TypeScript.
Returns:
CDK stack code as string
"""
stack = f"""import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as cognito from 'aws-cdk-lib/aws-cognito';
import {{ Construct }} from 'constructs';
export class {self.app_name.replace('-', '').title()}Stack extends cdk.Stack {{
constructor(scope: Construct, id: string, props?: cdk.StackProps) {{
super(scope, id, props);
// DynamoDB Table
const table = new dynamodb.Table(this, '{self.app_name}Table', {{
tableName: `${{cdk.Stack.of(this).stackName}}-data`,
partitionKey: {{ name: 'PK', type: dynamodb.AttributeType.STRING }},
sortKey: {{ name: 'SK', type: dynamodb.AttributeType.STRING }},
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
encryption: dynamodb.TableEncryption.AWS_MANAGED,
pointInTimeRecovery: true,
stream: dynamodb.StreamViewType.NEW_AND_OLD_IMAGES,
removalPolicy: cdk.RemovalPolicy.RETAIN,
}});
// Cognito User Pool
const userPool = new cognito.UserPool(this, '{self.app_name}UserPool', {{
userPoolName: `${{cdk.Stack.of(this).stackName}}-users`,
selfSignUpEnabled: true,
signInAliases: {{ email: true }},
autoVerify: {{ email: true }},
passwordPolicy: {{
minLength: 8,
requireLowercase: true,
requireUppercase: true,
requireDigits: true,
requireSymbols: false,
}},
mfa: cognito.Mfa.OPTIONAL,
mfaSecondFactor: {{
sms: false,
otp: true,
}},
removalPolicy: cdk.RemovalPolicy.RETAIN,
}});
const userPoolClient = userPool.addClient('{self.app_name}Client', {{
authFlows: {{
userSrp: true,
}},
accessTokenValidity: cdk.Duration.hours(1),
refreshTokenValidity: cdk.Duration.days(30),
}});
// Lambda Function
const apiFunction = new lambda.Function(this, '{self.app_name}ApiFunction', {{
functionName: `${{cdk.Stack.of(this).stackName}}-api`,
runtime: lambda.Runtime.NODEJS_18_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('./src'),
memorySize: 512,
timeout: cdk.Duration.seconds(10),
environment: {{
TABLE_NAME: table.tableName,
USER_POOL_ID: userPool.userPoolId,
}},
logRetention: 7, // days
}});
// Grant Lambda permissions to DynamoDB
table.grantReadWriteData(apiFunction);
// API Gateway
const api = new apigateway.RestApi(this, '{self.app_name}Api', {{
restApiName: `${{cdk.Stack.of(this).stackName}}-api`,
description: 'API for {self.app_name}',
defaultCorsPreflightOptions: {{
allowOrigins: apigateway.Cors.ALL_ORIGINS,
allowMethods: apigateway.Cors.ALL_METHODS,
allowHeaders: ['Content-Type', 'Authorization'],
}},
deployOptions: {{
stageName: 'prod',
throttlingRateLimit: 100,
throttlingBurstLimit: 200,
metricsEnabled: true,
loggingLevel: apigateway.MethodLoggingLevel.INFO,
}},
}});
// Cognito Authorizer
const authorizer = new apigateway.CognitoUserPoolsAuthorizer(this, 'ApiAuthorizer', {{
cognitoUserPools: [userPool],
}});
// API Integration
const integration = new apigateway.LambdaIntegration(apiFunction);
// Add proxy resource (/{{proxy+}})
const proxyResource = api.root.addProxy({{
defaultIntegration: integration,
anyMethod: true,
defaultMethodOptions: {{
authorizer: authorizer,
authorizationType: apigateway.AuthorizationType.COGNITO,
}},
}});
// Outputs
new cdk.CfnOutput(this, 'ApiUrl', {{
value: api.url,
description: 'API Gateway URL',
}});
new cdk.CfnOutput(this, 'UserPoolId', {{
value: userPool.userPoolId,
description: 'Cognito User Pool ID',
}});
new cdk.CfnOutput(this, 'UserPoolClientId', {{
value: userPoolClient.userPoolClientId,
description: 'Cognito User Pool Client ID',
}});
new cdk.CfnOutput(this, 'TableName', {{
value: table.tableName,
description: 'DynamoDB Table Name',
}});
}}
}}
"""
return stack
def generate_terraform_configuration(self) -> str:
"""
Generate Terraform configuration for serverless stack.
Returns:
Terraform HCL configuration as string
"""
terraform = f"""terraform {{
required_version = ">= 1.0"
required_providers {{
aws = {{
source = "hashicorp/aws"
version = "~> 5.0"
}}
}}
}}
provider "aws" {{
region = var.aws_region
}}
variable "aws_region" {{
description = "AWS region"
type = string
default = "{self.region}"
}}
variable "environment" {{
description = "Environment name"
type = string
default = "dev"
}}
variable "app_name" {{
description = "Application name"
type = string
default = "{self.app_name}"
}}
# DynamoDB Table
resource "aws_dynamodb_table" "main" {{
name = "${{var.environment}}-${{var.app_name}}-data"
billing_mode = "PAY_PER_REQUEST"
hash_key = "PK"
range_key = "SK"
attribute {{
name = "PK"
type = "S"
}}
attribute {{
name = "SK"
type = "S"
}}
server_side_encryption {{
enabled = true
}}
point_in_time_recovery {{
enabled = true
}}
stream_enabled = true
stream_view_type = "NEW_AND_OLD_IMAGES"
tags = {{
Environment = var.environment
Application = var.app_name
}}
}}
# Cognito User Pool
resource "aws_cognito_user_pool" "main" {{
name = "${{var.environment}}-${{var.app_name}}-users"
username_attributes = ["email"]
auto_verified_attributes = ["email"]
password_policy {{
minimum_length = 8
require_lowercase = true
require_numbers = true
require_uppercase = true
require_symbols = false
}}
mfa_configuration = "OPTIONAL"
software_token_mfa_configuration {{
enabled = true
}}
schema {{
name = "email"
attribute_data_type = "String"
required = true
mutable = true
}}
tags = {{
Environment = var.environment
Application = var.app_name
}}
}}
resource "aws_cognito_user_pool_client" "main" {{
name = "${{var.environment}}-${{var.app_name}}-client"
user_pool_id = aws_cognito_user_pool.main.id
generate_secret = false
explicit_auth_flows = [
"ALLOW_USER_SRP_AUTH",
"ALLOW_REFRESH_TOKEN_AUTH"
]
refresh_token_validity = 30
access_token_validity = 1
id_token_validity = 1
token_validity_units {{
refresh_token = "days"
access_token = "hours"
id_token = "hours"
}}
}}
# IAM Role for Lambda
resource "aws_iam_role" "lambda" {{
name = "${{var.environment}}-${{var.app_name}}-lambda-role"
assume_role_policy = jsonencode({{
Version = "2012-10-17"
Statement = [{{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {{
Service = "lambda.amazonaws.com"
}}
}}]
}})
tags = {{
Environment = var.environment
Application = var.app_name
}}
}}
resource "aws_iam_role_policy_attachment" "lambda_basic" {{
role = aws_iam_role.lambda.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}}
resource "aws_iam_role_policy" "dynamodb" {{
name = "dynamodb-access"
role = aws_iam_role.lambda.id
policy = jsonencode({{
Version = "2012-10-17"
Statement = [{{
Effect = "Allow"
Action = [
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:Query",
"dynamodb:Scan"
]
Resource = aws_dynamodb_table.main.arn
}}]
}})
}}
# Lambda Function
resource "aws_lambda_function" "api" {{
filename = "lambda.zip"
function_name = "${{var.environment}}-${{var.app_name}}-api"
role = aws_iam_role.lambda.arn
handler = "index.handler"
runtime = "nodejs18.x"
memory_size = 512
timeout = 10
environment {{
variables = {{
TABLE_NAME = aws_dynamodb_table.main.name
USER_POOL_ID = aws_cognito_user_pool.main.id
ENVIRONMENT = var.environment
}}
}}
tags = {{
Environment = var.environment
Application = var.app_name
}}
}}
# CloudWatch Log Group
resource "aws_cloudwatch_log_group" "lambda" {{
name = "/aws/lambda/${{aws_lambda_function.api.function_name}}"
retention_in_days = 7
tags = {{
Environment = var.environment
Application = var.app_name
}}
}}
# API Gateway
resource "aws_api_gateway_rest_api" "main" {{
name = "${{var.environment}}-${{var.app_name}}-api"
description = "API for ${{var.app_name}}"
tags = {{
Environment = var.environment
Application = var.app_name
}}
}}
resource "aws_api_gateway_authorizer" "cognito" {{
name = "cognito-authorizer"
rest_api_id = aws_api_gateway_rest_api.main.id
type = "COGNITO_USER_POOLS"
provider_arns = [aws_cognito_user_pool.main.arn]
}}
resource "aws_api_gateway_resource" "proxy" {{
rest_api_id = aws_api_gateway_rest_api.main.id
parent_id = aws_api_gateway_rest_api.main.root_resource_id
path_part = "{{proxy+}}"
}}
resource "aws_api_gateway_method" "proxy" {{
rest_api_id = aws_api_gateway_rest_api.main.id
resource_id = aws_api_gateway_resource.proxy.id
http_method = "ANY"
authorization = "COGNITO_USER_POOLS"
authorizer_id = aws_api_gateway_authorizer.cognito.id
}}
resource "aws_api_gateway_integration" "lambda" {{
rest_api_id = aws_api_gateway_rest_api.main.id
resource_id = aws_api_gateway_resource.proxy.id
http_method = aws_api_gateway_method.proxy.http_method
integration_http_method = "POST"
type = "AWS_PROXY"
uri = aws_lambda_function.api.invoke_arn
}}
resource "aws_lambda_permission" "apigw" {{
statement_id = "AllowAPIGatewayInvoke"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.api.function_name
principal = "apigateway.amazonaws.com"
source_arn = "${{aws_api_gateway_rest_api.main.execution_arn}}/*/*"
}}
resource "aws_api_gateway_deployment" "main" {{
depends_on = [
aws_api_gateway_integration.lambda
]
rest_api_id = aws_api_gateway_rest_api.main.id
stage_name = var.environment
}}
# Outputs
output "api_url" {{
description = "API Gateway URL"
value = aws_api_gateway_deployment.main.invoke_url
}}
output "user_pool_id" {{
description = "Cognito User Pool ID"
value = aws_cognito_user_pool.main.id
}}
output "user_pool_client_id" {{
description = "Cognito User Pool Client ID"
value = aws_cognito_user_pool_client.main.id
}}
output "table_name" {{
description = "DynamoDB Table Name"
value = aws_dynamodb_table.main.name
}}
"""
return terraform
Related skills
How it compares
Use aws-solution-architect for full three-tier AWS blueprints; pick narrower DevOps skills for CI/CD or single-service tuning only.
FAQ
What does aws solution architect do?
Design AWS architectures for startups using serverless patterns and IaC templates. Use when asked to design serverless architecture, create CloudFormation templates, optimize AWS costs, set up CI/CD p
When should I invoke aws solution architect?
Design AWS architectures for startups using serverless patterns and IaC templates. Use when asked to design serverless architecture, create CloudFormation templates, optimize AWS costs, set up CI/CD p
What are key capabilities?
Application type (web app, mobile backend, data pipeline, SaaS)
Is Aws Solution Architect safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.