Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
Production-ready serverless on AWS — Lambda, API Gateway, DynamoDB, SQS/SNS event-driven patterns, SAM/CDK deployment, and cold-start optimization. USE WHEN building, deploying, or tuning AWS serverless apps (Lambda handlers, event pipelines, DynamoDB access, cold starts).
cluster
devops-infra
version
1.0.0
origin
antigravity-awesome-skills (MIT)
risk
unknown
source
vibeship-spawner-skills (Apache 2.0)
date_added
"2026-02-27T00:00:00.000Z"
AWS Serverless
Specialized skill for building production-ready serverless applications on AWS.
Covers Lambda functions, API Gateway, DynamoDB, SQS/SNS event-driven patterns,
SAM/CDK deployment, and cold start optimization.
Principles
Right-size memory and timeout (measure before optimizing)
Minimize cold starts for latency-sensitive workloads
Use SnapStart for Java/.NET functions
Prefer HTTP API over REST API for simple use cases
Design for failure with DLQs and retries
Keep deployment packages small
Use environment variables for configuration
Implement structured logging with correlation IDs
Patterns
Lambda Handler Pattern
Proper Lambda function structure with error handling
When to use: Any Lambda function implementation,API handlers, event processors, scheduled tasks
Initialize clients outside handler (reused across warm invocations)
Always return proper API Gateway response format
Log with structured JSON for CloudWatch Insights
Include request ID in error logs for tracing
API Gateway Integration Pattern
REST API and HTTP API integration with Lambda
When to use: Building REST APIs backed by Lambda,Need HTTP endpoints for functions
# template.yaml (SAM)AWSTemplateFormatVersion:'2010-09-09'Transform:AWS::Serverless-2016-10-31Globals:Function:Runtime:nodejs20.xTimeout:30MemorySize:256Environment:Variables:TABLE_NAME:!RefItemsTableResources:# HTTP API (recommended for simple use cases)HttpApi:Type:AWS::Serverless::HttpApiProperties:StageName:prodCorsConfiguration:AllowOrigins:-"*"AllowMethods:-GET-POST-DELETEAllowHeaders:-"*"# Lambda FunctionsGetItemFunction:Type:AWS::Serverless::FunctionProperties:Handler:src/handlers/get.handlerEvents:GetItem:Type:HttpApiProperties:ApiId:!RefHttpApiPath:/items/{id}Method:GETPolicies:-DynamoDBReadPolicy:TableName:!RefItemsTableCreateItemFunction:Type:AWS::Serverless::FunctionProperties:Handler:src/handlers/create.handlerEvents:CreateItem:Type:HttpApiProperties:ApiId:!RefHttpApiPath:/itemsMethod:POSTPolicies:-DynamoDBCrudPolicy:TableName:!RefItemsTable# DynamoDB TableItemsTable:Type:AWS::DynamoDB::TableProperties:AttributeDefinitions:-AttributeName:idAttributeType:SKeySchema:-AttributeName:idKeyType:HASHBillingMode:PAY_PER_REQUESTOutputs:ApiUrl:Value:!Sub"https://${HttpApi}.execute-api.${AWS::Region}.amazonaws.com/prod"
# GOOD - Lazy initialization
_table = Nonedefget_table():
global _table
if _table isNone:
dynamodb = boto3.resource('dynamodb')
_table = dynamodb.Table(os.environ['TABLE_NAME'])
return _table
defhandler(event, context):
table = get_table() # Only initializes on first use# ...
Optimization_priority
1: Reduce package size (biggest impact)
2: Use SnapStart for Java/.NET
3: Increase memory for faster init
4: Delay heavy imports
5: Provisioned concurrency (last resort)
SAM Local Development Pattern
Local testing and debugging with SAM CLI
When to use: Local development and testing,Debugging Lambda functions,Testing API Gateway locally
# Install SAM CLI
pip install aws-sam-cli
# Initialize new project
sam init --runtime nodejs20.x --name my-api
# Build the project
sam build
# Run locally
sam local start-api
# Invoke single function
sam local invoke GetItemFunction --event events/get.json
# Local debugging (Node.js with VS Code)
sam local invoke --debug-port 5858 GetItemFunction
# Deploy
sam deploy --guided
// .vscode/launch.json (for debugging){"version":"0.2.0","configurations":[{"name":"Attach to SAM CLI","type":"node","request":"attach","address":"localhost","port":5858,"localRoot":"${workspaceRoot}/src","remoteRoot":"/var/task/src","protocol":"inspector"}]}
Commands
Sam_build: Build Lambda deployment packages
Sam_local_start_api: Start local API Gateway
Sam_local_invoke: Invoke single function
Sam_deploy: Deploy to AWS
Sam_logs: Tail CloudWatch logs
CDK Serverless Pattern
Infrastructure as code with AWS CDK
When to use: Complex infrastructure beyond Lambda,Prefer programming languages over YAML,Need reusable constructs
// lib/api-stack.tsimport * 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 { Construct } from'constructs';
exportclassApiStackextendscdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// DynamoDB Tableconst table = new dynamodb.Table(this, 'ItemsTable', {
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
removalPolicy: cdk.RemovalPolicy.DESTROY, // For dev only
});
// Lambda Functionconst getItemFn = new lambda.Function(this, 'GetItemFunction', {
runtime: lambda.Runtime.NODEJS_20_X,
handler: 'get.handler',
code: lambda.Code.fromAsset('src/handlers'),
environment: {
TABLE_NAME: table.tableName,
},
memorySize: 256,
timeout: cdk.Duration.seconds(30),
});
// Grant permissions
table.grantReadData(getItemFn);
// API Gatewayconst api = new apigateway.RestApi(this, 'ItemsApi', {
restApiName: 'Items Service',
defaultCorsPreflightOptions: {
allowOrigins: apigateway.Cors.ALL_ORIGINS,
allowMethods: apigateway.Cors.ALL_METHODS,
},
});
const items = api.root.addResource('items');
const item = items.addResource('{id}');
item.addMethod('GET', new apigateway.LambdaIntegration(getItemFn));
// Output API URLnew cdk.CfnOutput(this, 'ApiUrl', {
value: api.url,
});
}
}
Symptoms:
Unexplained increase in Lambda costs (10-50% higher).
Bill includes charges for function initialization.
Functions with heavy startup logic cost more than expected.
Why this breaks:
As of August 1, 2025, AWS bills the INIT phase the same way it bills
invocation duration. Previously, cold start initialization wasn't billed
for the full duration.
This affects functions with:
Heavy dependency loading (large packages)
Slow initialization code
Frequent cold starts (low traffic or poor concurrency)
Cold starts now directly impact your bill, not just latency.
Recommended fix:
Measure your INIT phase
# Check CloudWatch Logs for INIT_REPORT# Look for Init Duration in milliseconds# Example log line:# INIT_REPORT Init Duration: 423.45 ms
Reduce INIT duration
// 1. Minimize package size// Use tree shaking, exclude dev dependencies// npm prune --production// 2. Lazy load heavy dependencieslet heavyLib = null;
functiongetHeavyLib() {
if (!heavyLib) {
heavyLib = require('heavy-library');
}
return heavyLib;
}
// 3. Use AWS SDK v3 modular importsconst { S3Client } = require('@aws-sdk/client-s3');
// NOT: const AWS = require('aws-sdk');
Situation: Running Lambda functions, especially with external calls
Symptoms:
Function times out unexpectedly.
"Task timed out after X seconds" in logs.
Partial processing with no response.
Silent failures with no error caught.
Why this breaks:
Default Lambda timeout is only 3 seconds. Maximum is 15 minutes.
Common timeout causes:
Default timeout too short for workload
Downstream service taking longer than expected
Network issues in VPC
Infinite loops or blocking operations
S3 downloads larger than expected
Lambda terminates at timeout without graceful shutdown.
Recommended fix:
Set appropriate timeout
# template.yamlResources:MyFunction:Type:AWS::Serverless::FunctionProperties:Timeout:30# Seconds (max 900)# Set to expected duration + buffer
Implement timeout awareness
exports.handler = async (event, context) => {
// Get remaining timeconst remainingTime = context.getRemainingTimeInMillis();
// If running low on time, fail gracefullyif (remainingTime < 5000) {
console.warn('Running low on time, aborting');
thrownewError('Insufficient time remaining');
}
// For long operations, check periodicallyfor (const item of items) {
if (context.getRemainingTimeInMillis() < 10000) {
// Save progress and exit gracefullyawaitsaveProgress(processedItems);
thrownewError('Timeout approaching, saved progress');
}
awaitprocessItem(item);
}
};
Situation: Lambda functions in VPC accessing private resources
Symptoms:
Extremely slow cold starts (was 10+ seconds, now ~100ms).
Timeouts on first invocation after idle period.
Functions work in VPC but slow compared to non-VPC.
Why this breaks:
Lambda functions in VPC need Elastic Network Interfaces (ENIs).
AWS improved this significantly with Hyperplane ENIs, but:
# Avoid NAT Gateway for AWS service callsDynamoDBEndpoint:Type:AWS::EC2::VPCEndpointProperties:ServiceName:!Subcom.amazonaws.${AWS::Region}.dynamodbVpcId:!RefVPCRouteTableIds:-!RefPrivateRouteTableVpcEndpointType:GatewayS3Endpoint:Type:AWS::EC2::VPCEndpointProperties:ServiceName:!Subcom.amazonaws.${AWS::Region}.s3VpcId:!RefVPCVpcEndpointType:Gateway
Only use VPC when necessary
Don't attach Lambda to VPC unless you need:
Access to RDS/ElastiCache in VPC
Access to private EC2 instances
Compliance requirements
Most AWS services can be accessed without VPC.
Node.js Event Loop Not Cleared
Severity: MEDIUM
Situation: Node.js Lambda function with callbacks or timers
Symptoms:
Function takes full timeout duration to return.
"Task timed out" even though logic completed.
Extra billing for idle time.
Why this breaks:
By default, Lambda waits for the Node.js event loop to be empty
before returning. If you have:
Unresolved setTimeout/setInterval
Dangling database connections
Pending callbacks
Lambda waits until timeout, even if your response was ready.
Recommended fix:
Tell Lambda not to wait for event loop
exports.handler = async (event, context) => {
// Don't wait for event loop to clear
context.callbackWaitsForEmptyEventLoop = false;
// Your code hereconst result = awaitprocessRequest(event);
return {
statusCode: 200,
body: JSON.stringify(result)
};
};
Close connections properly
// For database connections, use connection pooling// or close connections explicitlyconst mysql = require('mysql2/promise');
exports.handler = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = false;
const connection = await mysql.createConnection({...});
try {
const [rows] = await connection.query('SELECT * FROM users');
return { statusCode: 200, body: JSON.stringify(rows) };
} finally {
await connection.end(); // Always close
}
};
API Gateway Payload Size Limits
Severity: MEDIUM
Situation: Returning large responses or receiving large requests
Symptoms:
"413 Request Entity Too Large" error
"Execution failed due to configuration error: Malformed Lambda proxy response"
Response truncated or failed
Why this breaks:
API Gateway has hard payload limits:
REST API: 10 MB request/response
HTTP API: 10 MB request/response
Lambda itself: 6 MB sync response, 256 KB async
Exceeding these causes failures that may not be obvious.
Symptoms:
Runaway costs.
Thousands of invocations in minutes.
CloudWatch logs show repeated invocations.
Lambda writing to source bucket/table that triggers it.
Why this breaks:
Lambda can accidentally trigger itself:
S3 trigger writes back to same bucket
DynamoDB trigger updates same table
SNS publishes to topic that triggers it
Step Functions with wrong error handling
Recommended fix:
Use different buckets/prefixes
# S3 trigger with prefix filterEvents:S3Event:Type:S3Properties:Bucket:!RefInputBucketEvents:s3:ObjectCreated:*Filter:S3Key:Rules:-Name:prefixValue:uploads/# Only trigger on uploads/# Output to different bucket or prefix# OutputBucket or processed/ prefix
Add idempotency checks
exports.handler = async (event) => {
for (const record of event.Records) {
const key = record.s3.object.key;
// Skip if this is a processed fileif (key.startsWith('processed/')) {
console.log('Skipping already processed file:', key);
continue;
}
// Process and write to different locationawaitprocessFile(key);
awaitwriteToS3(`processed/${key}`, result);
}
};
Set reserved concurrency as circuit breaker
Resources:RiskyFunction:Type:AWS::Serverless::FunctionProperties:ReservedConcurrentExecutions:10# Max 10 parallel# Limits blast radius of runaway invocations
Monitor with CloudWatch alarms
InvocationAlarm:Type:AWS::CloudWatch::AlarmProperties:MetricName:InvocationsNamespace:AWS/LambdaStatistic:SumPeriod:60EvaluationPeriods:1Threshold:1000# Alert if >1000 invocations/minComparisonOperator:GreaterThanThreshold
Validation Checks
Hardcoded AWS Credentials
Severity: ERROR
AWS credentials must never be hardcoded
Message: Hardcoded AWS access key detected. Use IAM roles or environment variables.
AWS Secret Key in Source Code
Severity: ERROR
Secret keys should use Secrets Manager or environment variables
Message: Hardcoded AWS secret key. Use IAM roles or Secrets Manager.
Overly Permissive IAM Policy
Severity: WARNING
Avoid wildcard permissions in Lambda IAM roles
Message: Overly permissive IAM policy. Use least privilege principle.
Lambda Handler Without Error Handling
Severity: WARNING
Lambda handlers should have try/catch for graceful errors
Message: Lambda handler without error handling. Add try/catch.
Missing callbackWaitsForEmptyEventLoop
Severity: INFO
Node.js handlers should set callbackWaitsForEmptyEventLoop