AI
50 AI Prompts for AWS Lambda and Serverless Development
50 AI prompts for building AWS Lambda functions and serverless architectures with Node.js and TypeScript. Covers function setup, API Gateway, event sources, cold starts, DynamoDB, SQS, SNS, Step Functions, and IaC with CDK.
Getting the Best Results from These Lambda Prompts
AWS Lambda is the leading serverless compute platform. These prompts cover the full serverless development lifecycle: function setup, API integration, event-driven triggers, data storage, workflow orchestration, infrastructure as code, and observability. All prompts assume Node.js 20 runtime and TypeScript.
When using these prompts, always specify your AWS region, your deployment tool (CDK, Serverless Framework, or SAM), and any existing infrastructure the function will interact with. Lambda function code is straightforward; the complexity is in the surrounding AWS service integration and IAM permissions.
Lambda Function Setup and API Gateway (Prompts 1-15)
Prompt 1: Write an AWS Lambda function in TypeScript (Node.js 20) that handles an API Gateway HTTP API event. The function validates the request body against a Zod schema, calls a downstream service, and returns a JSON response with the correct status code and CORS headers. Show the handler signature with the APIGatewayProxyEventV2 and APIGatewayProxyResultV2 types.
Prompt 2: Create an AWS CDK stack in TypeScript that defines an API Gateway HTTP API with three routes: POST /users, GET /users/{id}, and DELETE /users/{id}. Each route maps to a separate Lambda function. Configure CORS for a specific frontend domain, add request logging to CloudWatch, and add API key authentication for the DELETE route. Prompt 3: Write a Lambda function with request validation using API Gateway request validators. Define the request body JSON Schema in the CDK stack, configure the API Gateway to reject invalid requests before they reach the Lambda, and show the Lambda handler that can assume the body is already validated.
- Prompt 4: Create a Lambda authorizer function that validates a JWT token from the Authorization header and returns an IAM policy document. The policy allows access to the specific resource the request is for and includes the decoded userId in the authorizer context for downstream Lambda functions to read.
- Prompt 5: Write a Lambda function that handles a multi-part form data upload via API Gateway. Parse the base64-encoded body, extract the file buffer, validate the MIME type and file size, upload to S3 using the AWS SDK v3 PutObjectCommand, and return the S3 object URL.
- Prompt 6: Create a Lambda function with provisioned concurrency to eliminate cold starts. Configure the CDK provisioned concurrency setting, move all initialization code (SDK clients, database connections, config loading) outside the handler function so it runs once per container, and show the difference in cold start vs warm execution time.
- Prompt 7: Write a Lambda function that uses Lambda Layers to share common dependencies. Define a Layer CDK construct with the shared node_modules, attach it to three different Lambda functions, and show how the layer path is available in the /opt directory at runtime.
- Prompt 8: Create a Lambda function optimised for minimum cold start time using ESBuild bundling. Configure the CDK NodejsFunction construct with ESBuild bundling that tree-shakes unused imports, sets the target to node20, externalises the AWS SDK (available in the Lambda runtime), and produces a bundle under 1MB.
- Prompt 9: Write a Lambda function that handles pagination for a DynamoDB scan. The function accepts a page token in the request, passes it to DynamoDB as the ExclusiveStartKey, and returns the items plus the next page token encoded as a base64 string so it is safe to pass in a URL query parameter.
- Prompt 10: Create a Lambda function with structured logging using AWS Lambda Powertools for TypeScript. Use the Logger utility with correlation IDs automatically added to every log, annotate the function with @logger.injectLambdaContext, log the request and response at INFO level, and log errors with the full stack trace at ERROR level.
- Prompt 11: Write a Lambda function with distributed tracing using AWS X-Ray. Instrument outbound HTTP calls and DynamoDB calls with X-Ray subsegments, add custom annotations for userId and orderId, and show how to view the trace in the X-Ray service map.
- Prompt 12: Create a Lambda function with AWS Lambda Powertools Metrics. Emit a custom metric for each successful order processed, a metric for validation errors, and a metric for downstream service failures. Configure the CloudWatch namespace and add the function name as a dimension.
- Prompt 13: Write an API Gateway WebSocket API Lambda handler for a real-time chat application. Implement the $connect route that stores the connection ID in DynamoDB, the $disconnect route that removes it, and a custom sendMessage route that broadcasts a message to all connected clients using the API Gateway Management API.
- Prompt 14: Create a Lambda function that implements idempotency using AWS Lambda Powertools Idempotency. Configure the DynamoDB idempotency table, decorate the handler with @idempotent, use the request body hash as the idempotency key, and show how duplicate API calls within the TTL window return the cached response without re-executing the handler.
- Prompt 15: Write a Lambda function URL configuration (without API Gateway) for a simple webhook receiver. Configure the function URL in CDK with NONE authentication for public access, handle CORS in the function code, and show the URL format. Include a second function URL with AWS_IAM authentication for internal service-to-service calls.
Event Sources, Step Functions, and CDK (Prompts 16-50)
Prompt 16: Write a Lambda function triggered by SQS. Handle a batch of up to 10 messages, process each message, report partial batch failures using the SQS event source mapping with reportBatchItemFailures so successfully processed messages are not retried, and show the CDK event source configuration with dead letter queue.
Prompt 17: Create a Lambda function triggered by an SNS topic. Parse the SNS message envelope, extract the JSON body, process the event, and handle the case where the message body fails JSON parsing without crashing the function. Show the CDK SNS subscription setup. Prompt 18: Write a Lambda function triggered by DynamoDB Streams. Process INSERT and MODIFY events for a users table, ignore REMOVE events, extract the new image using the AWS DynamoDB UnmarshallCommand, and publish a UserUpdated event to an EventBridge bus. Prompt 19: Create a Lambda function triggered by S3 events. On ObjectCreated events for a specific bucket prefix, read the uploaded CSV file using the S3 GetObjectCommand, parse it line by line using a streaming parser, validate each row, insert valid rows to DynamoDB in batches of 25, and write a summary file back to S3.
- Prompt 20: Write a Step Functions state machine CDK definition for an order processing workflow. Define states: ValidateOrder (Lambda), CheckInventory (Lambda with choice state), ChargePayment (Lambda with retry and catch), FulfillOrder (Lambda), and SendConfirmationEmail (Lambda). Configure retry policies with exponential backoff on payment errors and a fallback to RefundPayment on catch.
- Prompt 21: Create a Lambda function that is part of a Step Functions workflow and returns structured output. The function receives the state machine input, processes it, and returns an object where successes and failures are separate keys so the Step Functions choice state can route appropriately.
- Prompt 22: Write an EventBridge rule CDK construct that triggers a Lambda function on a schedule (every 6 hours) and on a custom event pattern where source is myapp and detail-type is OrderPlaced. Show how to pass additional constants to the Lambda via the event target input transformer.
- Prompt 23: Create a CDK stack with a Lambda function that reads secrets from AWS Secrets Manager. Cache the secret value in a module-level variable with a 5-minute TTL to avoid calling Secrets Manager on every invocation, and show how to reference the secret ARN from an environment variable set by CDK.
- Prompt 24: Write an AWS CDK pipeline stack using CodePipeline and CodeBuild. The pipeline triggers on git push to main, runs npx cdk synth, runs Jest tests, runs a security scan with cdk-nag, and deploys the CDK stack to production. Configure CodeBuild with the Lambda function build environment.
- Prompt 25: Create a Jest test setup for AWS Lambda functions using aws-sdk-client-mock. Mock the DynamoDB DocumentClient, test a successful item creation, test the error path when DynamoDB returns a ConditionalCheckFailedException, and verify the correct DynamoDB command arguments were called.
FAQ
How do I reduce AWS Lambda cold start time?
Three main approaches: First, reduce bundle size by using ESBuild to tree-shake and remove unused code, and external the AWS SDK since it is available in the runtime. Second, move initialisation code (SDK clients, database connections, config) outside the handler so it runs once per container. Third, enable provisioned concurrency for latency-sensitive functions — this keeps containers warm and eliminates cold starts for that provisioned capacity.
What is the maximum timeout for an AWS Lambda function?
The maximum Lambda timeout is 15 minutes (900 seconds). For work that takes longer, use AWS Step Functions with Lambda as individual steps. Each step can run for up to 15 minutes, and Step Functions orchestrates the overall workflow duration up to one year. For streaming long-running responses, use Lambda response streaming with the streamifyResponse wrapper.
Should I use AWS Lambda or containers (ECS, Fargate) for my backend?
Lambda for event-driven, spiky, or infrequent workloads where the scale-to-zero cost saving matters. Lambda is also ideal for simple API endpoints, webhooks, scheduled jobs, and queue consumers. Use containers for long-running processes, WebSocket servers, streaming responses, workloads with sustained high traffic (containers are cheaper at high constant load), and applications that need more than 10GB memory or the Lambda 15-minute timeout.
What is the best way to manage Lambda function permissions?
Use IAM roles with least-privilege policies. Each Lambda function should have its own execution role that grants only the specific actions on the specific resources it needs. In CDK, grantRead() and grantWrite() methods on AWS resource constructs automatically add the correct IAM policy statements. Avoid sharing execution roles between functions — it makes it impossible to audit or tighten permissions per function.
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.