AI
50 AI Prompts for AWS Lambda and Serverless Architecture
Developer-tested AI prompts for AWS Lambda function handlers, API Gateway, DynamoDB, S3, Cognito, AWS SAM, and cold start optimization. Build serverless applications faster with copy-paste prompts.
Why Serverless Developers Benefit from AI Prompts
Serverless development on AWS involves a large ecosystem of services — Lambda, API Gateway, DynamoDB, S3, Cognito, SQS, EventBridge — each with their own SDK patterns, IAM permission requirements, and deployment configurations. Writing boilerplate for every service from memory is slow and error-prone. AI prompts eliminate most of that friction.
The most common AI failure mode for serverless is generating SDK v2 code when you are using SDK v3, or generating incorrect IAM policies that are either too permissive or too restrictive. The prompts in this guide specify the SDK version, IAM scope, and event source in every template.
- Generate typed Lambda handler functions for API Gateway, SQS, S3, and EventBridge events
- Write DynamoDB queries, puts, and transactions using the Document Client v3
- Build AWS SAM templates with correct resource definitions and IAM policies
- Set up Cognito user pool triggers and custom authentication flows
- Optimize Lambda cold starts with bundling, provisioned concurrency, and lazy initialization
Lambda Function Handler Prompts
A Lambda handler is the entry point function that AWS calls with an event and a context object. The event shape differs for each trigger source — API Gateway v2 HTTP payloads look different from SQS events, which look different from S3 notifications. Specifying the event source in the prompt is the single most important detail for getting correct Lambda handler code.
These prompts generate typed Lambda handlers for the most common event sources. Each includes input validation, structured error handling, and the correct return format for the trigger type.
Act as an AWS Lambda TypeScript expert.
Task:
Write a Lambda function handler for an API Gateway v2 HTTP API.
Endpoint: POST /users
Request body: { name: string, email: string, role: 'admin' | 'user' }
Handler requirements:
1. Parse and validate the request body (return 400 if invalid)
2. Generate a UUID for the new user
3. Put the user item in DynamoDB (table name from environment variable USERS_TABLE)
4. Return 201 with the created user object
5. Return 500 with a safe error message on any unhandled error
6. Use AWS Lambda Powertools Logger for structured logging
Use: TypeScript, AWS SDK v3 DynamoDBDocumentClient, @aws-lambda-powertools/logger,
@types/aws-lambda for the APIGatewayProxyEventV2 typeDynamoDB Integration Prompts
DynamoDB is the most commonly paired database with AWS Lambda because both scale independently, both have no persistent connection overhead, and both fit the serverless billing model. The AWS SDK v3 DynamoDBDocumentClient simplifies working with DynamoDB by handling attribute type marshaling automatically.
DynamoDB query patterns depend heavily on the table design — specifically the partition key and sort key choice and any Global Secondary Indexes. These prompts assume a single-table design pattern and cover the most common access patterns: get by ID, query by partition key with sort key filters, and transactional writes.
Act as an AWS DynamoDB and TypeScript expert.
Task:
Write DynamoDB operations for a single-table design using SDK v3 DocumentClient.
Table design:
- Table name: app-table
- PK: pk (string), SK: sk (string)
- User items: PK=USER#userId, SK=PROFILE
- Order items: PK=USER#userId, SK=ORDER#orderId
- GSI: gsi1pk (status), gsi1sk (createdAt) for querying orders by status
Operations needed:
1. Get a user by userId
2. Get all orders for a user, sorted by createdAt descending
3. Create a user and their first order in a transaction
4. Update order status with a condition expression (only if current status is PENDING)
5. Query all orders with status PROCESSING using the GSI
Use: AWS SDK v3, DynamoDBDocumentClient, TypeScriptAPI Gateway and REST API Prompts
API Gateway exposes Lambda functions as HTTP endpoints. The two types most commonly used are REST API (API Gateway v1) and HTTP API (API Gateway v2). HTTP API is cheaper, faster, and simpler for most use cases. REST API is needed for features like request validation models, usage plans, and per-stage deployment.
These prompts generate API Gateway configurations including request/response models, authorizers, CORS settings, and throttling. Specify which API type you are using since the event structure and SAM resource types differ between v1 and v2.
Act as an AWS API Gateway and Lambda expert.
Task:
Set up a JWT authorizer for an API Gateway HTTP API (v2).
Requirements:
- Use AWS Cognito User Pool as the JWT issuer
- Protect all routes except GET /health and POST /auth/login
- Extract the userId claim from the JWT and pass it to Lambda via
requestContext.authorizer.jwt.claims
- Return 401 for missing token and 403 for invalid/expired token
Provide:
1. The AWS SAM template snippet for the JWT authorizer
2. How to read the userId in the Lambda handler
3. The IAM permission needed for the authorizer
Also provide a Lambda middleware wrapper that extracts userId from the
event and adds it to a typed context object for the handler to use.AWS SAM Infrastructure as Code Prompts
AWS SAM (Serverless Application Model) is a framework for defining serverless infrastructure as YAML. A SAM template defines Lambda functions, API Gateway routes, DynamoDB tables, S3 buckets, SQS queues, and their IAM policies in a single file. These prompts generate SAM templates for complete serverless applications.
Always specify the function runtime, memory size, timeout, and which environment variables to inject. For IAM policies, list the specific DynamoDB tables or S3 buckets the function needs to access so the prompt produces least-privilege policies rather than overly broad ones.
Act as an AWS SAM expert.
Task:
Write an AWS SAM template for a CRUD REST API with the following resources:
Lambda functions (Node.js 20.x, 256MB, 30s timeout):
- GetUsers: GET /users
- CreateUser: POST /users
- GetUser: GET /users/{userId}
- UpdateUser: PUT /users/{userId}
- DeleteUser: DELETE /users/{userId}
DynamoDB table:
- Name: UsersTable, PK: userId (String), BillingMode: PAY_PER_REQUEST
Requirements:
- HTTP API (v2) with CORS enabled for https://myapp.com
- Least-privilege IAM policies (each function only gets the actions it needs)
- Environment variable USERS_TABLE injected into all functions
- Parameters: Environment (dev, staging, prod) with conditional table naming
- Output: ApiUrl and TableName
Use: SAM template format 2010-09-09, AWS::Serverless transformCold Start Optimization and Performance Prompts
Lambda cold starts happen when a new execution environment is initialized. For Node.js functions, the main causes of slow cold starts are large deployment packages (more code to load), synchronous initialization of SDK clients outside the handler (runs on every cold start), and unoptimized bundling that includes unused modules.
These prompts help minimize cold start times through bundling configuration, lazy initialization patterns, and Provisioned Concurrency setup for latency-critical functions.
Act as an AWS Lambda performance expert.
Task:
My Node.js Lambda function has a 3-second cold start. Help me reduce it.
Current setup:
- Runtime: Node.js 20.x
- Memory: 128MB
- Package size: 45MB (unzipped)
- SDK clients initialized inside the handler on every invocation
- Using ts-node/register at runtime (not pre-compiled)
Provide fixes for:
1. Bundle the function with esbuild to reduce package size
(show the esbuild config and the SAM build configuration)
2. Move SDK client initialization outside the handler
(show the correct module-level pattern)
3. Increase memory to reduce cold start duration
(explain the memory-CPU relationship in Lambda)
4. Set up Provisioned Concurrency for the most critical endpoints
(show the SAM template addition)
Target: under 500ms cold start for an API Gateway endpointS3 Triggers and Event Processing Prompts
S3 event notifications trigger Lambda functions when objects are created, modified, or deleted. This pattern is commonly used for image processing (resize, convert, watermark), document parsing (extract text from PDFs and CSVs), data pipeline ingestion, and virus scanning.
These prompts generate S3 trigger Lambda functions with correct event parsing, error handling that prevents infinite loops from putting processed files back into the trigger bucket, and the SAM configuration to wire the trigger.
Act as an AWS Lambda and S3 expert.
Task:
Write a Lambda function that processes uploaded images from S3.
Trigger: S3 ObjectCreated event on bucket uploads-bucket, prefix images/
Processing steps:
1. Download the uploaded image from S3
2. Resize to three sizes: 1200px (large), 600px (medium), 200px (thumbnail)
3. Convert all sizes to WebP format
4. Upload all three sizes to a different bucket: processed-bucket
with prefix processed/[original-name]/
5. Write a record to DynamoDB with the original key, processed keys, and status
Use: TypeScript, AWS SDK v3, sharp for image processing
Avoid: putting output files back into uploads-bucket (would cause infinite loop)
Also provide the SAM template resource for this function.FAQ
What is the best way to use AI for AWS Lambda development?
Always specify the trigger event type (API Gateway v2, SQS, S3, EventBridge), the SDK version (v3 for all new projects), the runtime version (Node.js 20.x), and the specific AWS services the function needs to access. The event shape and return format differ per trigger, and AI produces correct code only when the trigger source is explicit.
Can AI write a Lambda function handler in TypeScript?
Yes. Specify the trigger event type, the request and response shapes, the AWS services to call, and whether to use AWS Lambda Powertools. The prompts in Section 2 cover the complete pattern for API Gateway HTTP API handlers with DynamoDB, validation, and structured logging.
How do I prompt AI for DynamoDB single-table design queries?
Include the table name, partition key, sort key, and any GSI definitions in the prompt. Describe each access pattern in plain language — AI maps them to the correct DynamoDB query or scan operations with the right key conditions. The prompt in Section 3 shows the full single-table design pattern.
How do I use AI to write AWS SAM templates?
List every resource needed (functions, tables, buckets, queues), the event source for each function, the environment variables, and the IAM permissions. Ask AI to use least-privilege policies so it generates specific action lists rather than wildcard permissions. The prompt in Section 5 shows a complete CRUD API SAM template.
Can AI help reduce Lambda cold start times?
Yes. Describe your current setup — runtime, memory, package size, whether clients are initialized inside or outside the handler. AI identifies the main cold start contributors and provides fixes: esbuild bundling to reduce package size, module-level client initialization, and Provisioned Concurrency configuration. The prompt in Section 6 covers all of these.
What is the difference between AWS Lambda and a traditional server?
Lambda functions run for a single request and then stop. There is no persistent process, no persistent in-memory state between requests, and no long-lived database connections. You pay only for execution time. A traditional server runs continuously, holds state in memory between requests, and maintains persistent connections. Lambda is better for spiky or unpredictable traffic; a server is better for consistent high-throughput workloads.
Can AI help set up Cognito authentication with Lambda?
Yes. Describe the Cognito user pool configuration, the triggers you need (pre-sign-up, post-confirmation, custom message), and the authentication flow (standard, custom, or hosted UI). AI generates both the Cognito Lambda trigger handler and the SAM template configuration. Specify the trigger event type since each Cognito trigger has a different event shape.
How do I avoid infinite loops with S3 Lambda triggers?
Never write the output of an S3-triggered Lambda back to the same bucket and prefix that triggered it. Use a separate destination bucket or a different prefix. The prompt in Section 7 shows the correct pattern: trigger on the uploads-bucket, write processed output to a separate processed-bucket.
Related free tools
If you want to turn this topic into action, use one of ShortIQ's free tools for campaign planning, UTM structure, or QR distribution.
Continue Reading
Explore more guides on link shortener SaaS strategy, Bitly alternatives, and white label link management.
Free newsletter
Get new guides in your inbox
We publish practical guides on dev tooling, prompt engineering, marketing workflows, and deployment. No fluff — straight to the point.
No spam. Unsubscribe any time.
Was this article helpful?
Tell us if this guide solved the problem or what was still missing. We use this to improve the blog and only follow up if you explicitly allow it.