Skip to main content

Configuring AWS Lambda for Production Workloads

Configure AWS Lambda for production with the right memory, concurrency limits, cold start fixes, VPC access and RDS Proxy, with a Terraform lab.

Overview and What You Will Learn

AWS Lambda runs your code in response to events without servers to manage, and bills per request and per millisecond of execution time. Making it production-ready comes down to a handful of settings: memory, timeout, concurrency, cold start behaviour, VPC networking, and how your function talks to a database.

In this guide you will learn:

  • When Lambda beats EC2 and when it does not
  • The three invocation models and how errors and retries differ in each
  • The Lambda limits that matter in production
  • How Lambda pricing works, with a worked example
  • How concurrency and throttling work, and how one function can starve the rest of your account
  • What causes cold starts and how to reduce them with code changes, SnapStart, and Provisioned Concurrency
  • How to reach private resources by placing Lambda in a VPC, and why RDS Proxy belongs in front of databases
  • When to use CloudFront Functions instead of Lambda@Edge

Why This Matters in Production

When a Swiggy-style order is placed, the notification to the restaurant does not need a server waiting around all day. It needs a function that runs for a couple of hundred milliseconds and stops. Payment gateways also deliver bursts of webhooks that must be accepted fast and processed reliably. Lambda fits these event-driven jobs well, but its defaults hide real traps: a spiky function can throttle your payment API, a cold start can break a latency target, and hundreds of concurrent functions can exhaust a database. The goal here is to configure it so none of that surprises you.

Core Principles

When to Use Lambda Instead of EC2

Use Lambda for short, event-driven work with uneven traffic, where paying only while code runs beats keeping a server idle. Use EC2 or containers for long-running or steady high-throughput work.

  • Lambda fits: tasks under 15 minutes, webhooks, file processing, scheduled jobs, API backends, workloads that are idle much of the time
  • Lambda does not fit: tasks longer than 15 minutes, persistent connections or background processes, GPU workloads, or very high sustained throughput where reserved instances cost less
How Lambda Is Invoked

Lambda runs only when something invokes it, and the invocation model decides who handles errors.

  • Synchronous: the caller waits for the result. API Gateway, ALB, and Lambda function URLs work this way. If Lambda throttles the request, the caller receives a 429 error and must handle retries.
  • Asynchronous: the caller hands off the event and moves on. S3, SNS, and EventBridge work this way. Lambda queues the event, retries function errors twice by default, and retries throttled events for up to 6 hours. Failed events can go to a dead-letter queue or an on-failure destination.
  • Polling (event source mapping): Lambda polls a source for you. SQS, Kinesis, DynamoDB Streams, and Kafka work this way. Lambda reads batches, and the retry behaviour depends on the source.

Because asynchronous and polling sources can deliver an event more than once, write handlers to be idempotent.

The Lambda Execution Environment Lifecycle

Lambda runs your code inside an isolated execution environment. A new environment must be created and initialised, which is a cold start. An existing idle environment is reused, which is a warm start.

flowchart TD E([Event arrives]) --> Q[Warm environment free?] Q -->|Yes| H[Run handler] Q -->|No| C[Cold start
download, start runtime, init code] C --> H H --> R([Response returned]) H -.->|Idle| Z[Environment frozen
then recycled] classDef evt fill:#475569,color:#ffffff classDef cold fill:#F97316,color:#ffffff classDef run fill:#10B981,color:#ffffff classDef idle fill:#F1F5F9,color:#1E293B class E,R evt class C cold class H run class Q,Z idle
Lambda Limits That Matter
Limit Value
Maximum execution time 900 seconds (15 minutes)
Memory 128 MB to 10,240 MB
Ephemeral storage in /tmp 512 MB by default, up to 10,240 MB
Environment variables 4 KB in total
Zip package 50 MB zipped, 250 MB unzipped including layers
Container image Up to 10 GB
Layers per function 5
Synchronous payload 6 MB request and 6 MB response
Default concurrency 1,000 per Region, but new accounts can start lower

Check Service Quotas in your own account, because the starting concurrency limit varies and can be raised on request.

Remember

Memory is the performance knob. CPU and network bandwidth scale with the memory you allocate, and there is no separate CPU setting. If a function is slow, try more memory before rewriting code, because faster execution can lower the duration bill.

How Lambda Pricing Works

You pay per request and per GB-second of duration, billed in 1 ms increments. Typical x86 rates are $0.20 per million requests and about $0.0000166667 per GB-second, with a monthly free tier of 1 million requests and 400,000 GB-seconds. Arm64 (Graviton) functions cost about 20 percent less per GB-second. Since August 2025, the initialisation phase is billed for all managed runtimes, so heavy init code now costs money as well as latency. Always confirm current prices for your Region.

GB-seconds are memory in GB multiplied by duration in seconds, so a 256 MB function running 200 ms uses 0.25 x 0.2 = 0.05 GB-seconds per call.

TEXT
Example: 1,000,000 invocations per day, 256 MB, 200 ms each, for 30 days
Requests: 30,000,000 - 1,000,000 free = 29,000,000 billable
29 x $0.20 = $5.80
Duration: 30,000,000 x 0.05 GB-s = 1,500,000 GB-s
1,500,000 - 400,000 free = 1,100,000 billable
1,100,000 x $0.0000166667 = $18.33
Total: about $24 per month (before logs and data transfer)

At roughly 12 requests per second sustained, that is similar to a small always-on instance. Lambda becomes dramatically cheaper when traffic is spiky or mostly idle, and EC2 or containers become cheaper when load is steady and high.

How Concurrency and Throttling Work

Concurrency is the number of function invocations running at the same moment. A rough estimate is requests per second multiplied by average duration in seconds, so 200 requests per second at 0.5 seconds needs about 100 concurrent environments. Each function can add up to 1,000 new environments every 10 seconds until it reaches your account limit.

The account limit is shared by every function in the Region. Without limits, one busy function can use all of it and throttle the rest, including your payment API.

  • Reserved concurrency sets both a guaranteed amount and a maximum for one function. Setting it to 0 stops the function completely, which is a quick way to disable it. Lambda requires that at least 100 concurrency stays unreserved.
  • Provisioned Concurrency is different. It keeps environments initialised and ready, which removes cold starts for those slots.
What Causes Cold Starts and How to Reduce Them

A cold start happens when a request needs a new environment: Lambda downloads your code, starts the runtime, and runs your initialisation code before the handler. Python and Node.js are typically a few hundred milliseconds, while Java and .NET can take seconds without mitigation. The most effective code-level fix is to do expensive setup once, outside the handler, so warm invocations reuse it.

Python
import json
import os
import boto3
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["TABLE_NAME"])
def lambda_handler(event, context):
# Runs on every invocation: keep this fast
item = table.get_item(Key=dict(order_id=event["orderId"])).get("Item")
return dict(statusCode=200, body=json.dumps(item, default=str))

Other levers, in order of effort:

  • Keep the package small and remove unused dependencies
  • Use arm64 and a recent runtime
  • Increase memory, which speeds up initialisation
  • Enable SnapStart on supported runtimes
  • Buy Provisioned Concurrency for latency-critical paths
What SnapStart Does

SnapStart takes a snapshot of an initialised execution environment when you publish a version, then restores from that snapshot instead of initialising from scratch. It supports Java, and also Python and .NET on newer runtimes, and can cut Java cold starts from seconds to well under a second. There is no extra charge for Java, while Python and .NET incur cache and restore charges. Because many environments restore from one snapshot, re-create network connections and avoid caching random values or unique IDs during initialisation.

When to Use Provisioned Concurrency

Use Provisioned Concurrency when a user-facing or payment path cannot tolerate cold start latency. It keeps a set number of environments initialised and you pay for them while they are allocated, even with no traffic. It applies to a published version or alias, not $LATEST, and you can schedule changes with Application Auto Scaling, for example more capacity in business hours and less overnight.

How to Run Lambda Inside a VPC

By default Lambda runs in an AWS-managed network and reaches public AWS endpoints, but not private resources such as an RDS instance in a private subnet. Attaching a VPC configuration gives the function network interfaces in your private subnets so it can reach private resources by private IP, controlled by security groups.

A function in a VPC has no internet access by default. Use VPC endpoints for AWS services (gateway endpoints for S3 and DynamoDB are free) and add a NAT Gateway only when the function must call public internet APIs.

Why Lambda Needs RDS Proxy

Each concurrent Lambda environment opens its own database connection, so 500 concurrent invocations can mean 500 connections, which can exhaust a database. RDS Proxy sits between Lambda and RDS or Aurora, keeps a small pool of real connections, and multiplexes requests across them. It also shortens failover recovery, and supports IAM authentication with credentials held in Secrets Manager.

flowchart TD L[Lambda, 500 concurrent
private subnets] -->|Few connections| P[(RDS Proxy)] P -->|Pooled connections| DB[(Aurora or RDS)] L -->|Via NAT Gateway| NET([Public APIs]) L -->|Gateway endpoint| S3[S3 and DynamoDB] classDef fn fill:#F97316,color:#ffffff classDef proxy fill:#8B5CF6,color:#ffffff classDef data fill:#326CE5,color:#ffffff classDef ext fill:#F1F5F9,color:#1E293B class L fn class P proxy class DB,S3 data class NET ext
CloudFront Functions vs Lambda@Edge

Both run code at CloudFront edge locations close to users. Use CloudFront Functions for small, fast request and response tweaks, and Lambda@Edge when you need more time, memory, or network access.

Feature CloudFront Functions Lambda@Edge
Language JavaScript Node.js and Python
Run time Sub-millisecond Up to 5 s (viewer), 30 s (origin)
Network access No Yes
Triggers Viewer request and response Viewer and origin, request and response
Created in CloudFront us-east-1, then replicated
  • Use CloudFront Functions for URL rewrites, header changes, cache key normalisation, and simple redirects
  • Use Lambda@Edge for authentication that calls another service, reading request bodies, and dynamic origin selection

Detailed Step-by-Step Practical Lab

You will deploy a function with Terraform, attach an S3 trigger, invoke it, observe cold and warm starts, and set reserved concurrency. You need Terraform 1.6 or later, the AWS CLI, and jq.

Step 1: Write the Function

Create lambda/handler.py. The module-level code runs on cold start only, and env_age_seconds proves when an environment is reused.

Python
import json
import os
import time
# Runs once per cold start and is reused by warm invocations
INIT_AT = time.time()
STAGE = os.environ.get("STAGE", "dev")
print("Cold start: initialising")
def lambda_handler(event, context):
order_id = event.get("orderId", "unknown")
city = event.get("city", "unknown")
print(f"Processing order {order_id} from {city}")
body = dict(
message=f"Order {order_id} processed",
city=city,
stage=STAGE,
env_age_seconds=round(time.time() - INIT_AT, 1),
)
return dict(statusCode=200, body=json.dumps(body))
Step 2: Define the Infrastructure in Terraform
HCL
# main.tf
terraform {
required_version = ">= 1.6.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
data "aws_caller_identity" "current" {}
data "archive_file" "lambda_zip" {
type = "zip"
source_file = "${path.module}/lambda/handler.py"
output_path = "${path.module}/build/handler.zip"
}
data "aws_iam_policy_document" "lambda_assume" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
}
}
resource "aws_iam_role" "lambda" {
name = "devops-lambda-role"
assume_role_policy = data.aws_iam_policy_document.lambda_assume.json
}
# Permission to write logs and nothing else
resource "aws_iam_role_policy_attachment" "logs" {
role = aws_iam_role.lambda.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
# Create the log group ourselves so retention is bounded
resource "aws_cloudwatch_log_group" "lambda" {
name = "/aws/lambda/devops-order-processor"
retention_in_days = 14
}
resource "aws_lambda_function" "order_processor" {
function_name = "devops-order-processor"
role = aws_iam_role.lambda.arn
runtime = "python3.13"
handler = "handler.lambda_handler"
architectures = ["arm64"] # cheaper per GB-second
memory_size = 256
timeout = 10 # keep it short: fail fast instead of hanging
filename = data.archive_file.lambda_zip.output_path
source_code_hash = data.archive_file.lambda_zip.output_base64sha256
publish = true # creates a numbered version
environment {
variables = {
STAGE = "dev"
}
}
depends_on = [aws_cloudwatch_log_group.lambda]
}
# S3 trigger: invoke the function for every uploaded object
resource "aws_s3_bucket" "orders" {
bucket = "devops-orders-lab-${data.aws_caller_identity.current.account_id}"
force_destroy = true
}
resource "aws_lambda_permission" "allow_s3" {
statement_id = "AllowS3Invoke"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.order_processor.function_name
principal = "s3.amazonaws.com"
source_arn = aws_s3_bucket.orders.arn
}
resource "aws_s3_bucket_notification" "orders_uploaded" {
bucket = aws_s3_bucket.orders.id
lambda_function {
lambda_function_arn = aws_lambda_function.order_processor.arn
events = ["s3:ObjectCreated:*"]
}
depends_on = [aws_lambda_permission.allow_s3]
}
output "orders_bucket" {
value = aws_s3_bucket.orders.id
}
Bash
terraform init
terraform apply
Step 3: Invoke the Function and See a Cold Start

Build the test event with jq, invoke twice, and compare the logs. The first call includes an initialisation line, and the second reuses the environment.

Bash
jq -n --arg orderId ORD-2026-001 --arg city Mumbai '$ARGS.named' > event.json
for run in 1 2; do
echo "Invocation $run"
aws lambda invoke \
--function-name devops-order-processor \
--payload fileb://event.json \
--log-type Tail \
--query 'LogResult' --output text \
out.json | base64 --decode
cat out.json && echo
done

Invocation 1 prints Cold start: initialising and a REPORT line containing Init Duration. Invocation 2 has neither, and env_age_seconds is larger, which shows the environment was reused.

Step 4: Fire the S3 Trigger
Bash
BUCKET=$(terraform output -raw orders_bucket)
echo "test order data" > order.txt
aws s3 cp order.txt "s3://$BUCKET/order.txt"
aws logs tail /aws/lambda/devops-order-processor --since 5m

You should see a new Processing order unknown from unknown entry, because the S3 event does not carry orderId or city. In real code you would parse the S3 event records.

Step 5: Find Cold Starts in the Logs
Bash
aws logs filter-log-events \
--log-group-name /aws/lambda/devops-order-processor \
--filter-pattern '"Init Duration"' \
--query 'events[].message' --output text

Every line returned is a cold start. Count them against total invocations to measure how often users hit one.

Step 6: Set Reserved Concurrency

Check your quota first. Lambda needs at least 100 unreserved concurrency, so a new account with a low limit may reject large reservations.

Bash
aws lambda get-account-settings --query 'AccountLimit'
aws lambda put-function-concurrency \
--function-name devops-order-processor \
--reserved-concurrent-executions 100
aws lambda get-function-concurrency --function-name devops-order-processor
Step 7: Add Provisioned Concurrency (Optional, Billed)

Create an alias on the published version and keep two environments warm. Remove it after the test because you pay while it is allocated.

HCL
resource "aws_lambda_alias" "live" {
name = "live"
function_name = aws_lambda_function.order_processor.function_name
function_version = aws_lambda_function.order_processor.version
}
resource "aws_lambda_provisioned_concurrency_config" "live" {
function_name = aws_lambda_function.order_processor.function_name
qualifier = aws_lambda_alias.live.name
provisioned_concurrent_executions = 2
}
Bash
terraform apply
aws lambda invoke --function-name devops-order-processor:live \
--payload fileb://event.json --log-type Tail \
--query 'LogResult' --output text out.json | base64 --decode

Invoke the live alias and the REPORT line has no Init Duration, because an initialised environment was waiting.

Step 8: Reach a Private Database Through RDS Proxy

When you have a private subnet and an Aurora or RDS instance, attach the function to your VPC and point it at an RDS Proxy endpoint instead of the database. The subnet and security group IDs below are examples.

HCL
resource "aws_security_group" "lambda" {
name = "devops-lambda-sg"
vpc_id = "vpc-0a1b2c3d4e5f67890"
}
resource "aws_iam_role_policy_attachment" "vpc" {
role = aws_iam_role.lambda.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
}
# Add this block inside aws_lambda_function.order_processor
# vpc_config {
# subnet_ids = ["subnet-0a1b2c3d4e5f6a7b8", "subnet-0f9e8d7c6b5a43210"]
# security_group_ids = [aws_security_group.lambda.id]
# }
#
# Add DB_HOST = "mumbai-prod-proxy.proxy-abc123.ap-south-1.rds.amazonaws.com"
# to the environment variables, then allow inbound port 5432 on the proxy
# security group from aws_security_group.lambda.
Step 9: Clean Up
Bash
terraform destroy
rm -f event.json out.json order.txt

Production Best Practices & Common Pitfalls

Common Mistake

Creating database connections or SDK clients inside the handler. Every invocation pays for the setup. Move initialisation outside the handler so it runs once per cold start and warm calls reuse it.

Common Mistake

Not setting reserved concurrency on critical functions. A spike in one function can consume the account limit and throttle everything else, including payments. Reserve concurrency for functions that have an SLA.

Common Mistake

Connecting Lambda directly to a database at scale. Ten concurrent invocations is fine, and five hundred can exhaust connections and cause an application-wide failure. Add RDS Proxy before you need it.

Tip

Use the open-source AWS Lambda Power Tuning tool to run your function at several memory sizes and plot cost against speed. Many functions are both faster and cheaper above the 128 MB default.

Security

Give each function its own least-privilege execution role, and keep secrets in Secrets Manager or Parameter Store rather than plaintext environment variables, which are visible to anyone who can read the function configuration.

  • Make handlers idempotent. Asynchronous and polling invocations can deliver an event more than once, so use an idempotency key or a conditional write.
  • Configure failure handling. Use on-failure destinations or a dead-letter queue for asynchronous events, and a redrive queue for SQS, so failed events are not lost.
  • Set timeouts deliberately. A function timeout should be shorter than the caller's timeout, and for SQS the queue visibility timeout should be at least six times the function timeout.
  • Avoid recursive loops. A function that writes to the bucket that triggers it can run forever and generate a huge bill. Use separate prefixes or buckets.
  • Bound log retention. Create log groups with Terraform and set retention, because the default is to keep logs forever.
  • Use arm64 and current runtimes. They are usually cheaper and receive security patches.

Quick Reference & Troubleshooting Commands

Command Description
aws lambda list-functions List functions in the Region
aws lambda invoke --function-name NAME out.json Invoke a function synchronously
aws lambda update-function-code --function-name NAME --zip-file fileb://app.zip Deploy new code
aws lambda publish-version --function-name NAME Publish an immutable version
aws lambda put-function-concurrency Set reserved concurrency
aws lambda put-provisioned-concurrency-config Set Provisioned Concurrency on an alias
aws lambda get-account-settings Show account concurrency limits
aws logs tail /aws/lambda/NAME --follow Stream function logs
Error or symptom Likely fix
Task timed out after N seconds Raise the timeout or memory, or find the slow call
TooManyRequestsException (429) Raise concurrency limits or reserve concurrency for the function
Cannot connect to RDS, hangs Check VPC config, security group rules, and subnets
Calls to public APIs hang in a VPC Add a NAT Gateway or the right VPC endpoint
Too many connections on the database Put RDS Proxy in front of the database
Slow first request Move init outside the handler, then use SnapStart or Provisioned Concurrency
Unzipped size over 262144000 bytes Trim dependencies, use layers, or deploy a container image
Reservation would drop unreserved concurrency below 100 Raise the account quota or reserve less

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS Compute and Auto Scaling

All 6 Topics

Frequently Asked Questions

Is Configuring AWS Lambda for Production Workloads free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring AWS Lambda for Production Workloads topic cover?

Configure AWS Lambda for production with the right memory, concurrency limits, cold start fixes, VPC access and RDS Proxy, with a Terraform lab.

Found a mistake, an outdated step or a broken link?