Explain it simply
Explain it simply
Picture a Lambda function as a kitchen. Each incoming order uses one stove, which Lambda calls an execution environment. One stove cooks one order at a time, so ten simultaneous orders need ten stoves. That number is concurrency.
Lighting a new stove takes time; that is a cold start. The owner caps the total number of stoves (the account limit), can set aside stoves for one kitchen (reserved concurrency), or keep some already lit (provisioned concurrency). You wrote a Lambda in AWS Fundamentals; this lesson is about what changes when real traffic arrives in production.
Problem → Why → Solution
The problem: whole-batch retries and exhausted concurrency
A payment worker Lambda reads batches of ten messages from SQS. One message has a negative amount and the handler raises an exception. By default Lambda treats the whole batch as failed, so all ten messages reappear on the queue, and the nine that already succeeded are charged again.
At the same time a marketing campaign builds a backlog, and the worker takes almost all of the account's concurrency. The customer-facing checkout API Lambda is throttled (429) and buyers cannot pay.
import json
def handler(event, context):
for record in event["Records"]:
payment = json.loads(record["body"])
if payment["amount"] <= 0:
# One bad message fails the WHOLE batch: every message is retried,
# including the ones already charged above.
raise ValueError("invalid amount")
print("charged", payment["paymentId"])
if __name__ == "__main__":
batch = {
"Records": [
{"body": json.dumps({"paymentId": "p-1", "amount": 40})},
{"body": json.dumps({"paymentId": "p-2", "amount": -5})},
{"body": json.dumps({"paymentId": "p-3", "amount": 10})},
]
}
try:
handler(batch, None)
except ValueError:
print("batch failed: all 3 messages return to the queue")Why this hurts
If a batch can only succeed or fail as a whole, duplicate processing is guaranteed. If concurrency is not partitioned per function, one background job can starve a critical API.
Core concept: concurrency and cold starts
- Concurrency
- The number of execution environments handling requests at the same moment. Roughly: requests per second × average duration in seconds.
For example, 200 requests per second at 0.5 seconds each needs 100 concurrency. Each region has an account concurrency quota (commonly 1,000, possibly lower for new accounts, and raisable on request), and every function shares that pool. One function scaling without limits throttles the others.
Reserved concurrency sets aside part of the pool for one function and is also its maximum, at no extra charge. Reserve 300 for the checkout API and 300 stays available for checkout however far the worker scales. Reserve 50 for the worker and it can never open more than 50 database connections at once. Reserved concurrency of 0 effectively switches a function off.
A cold start means downloading code for a new environment, starting the runtime, and running the init code outside the handler (imports, SDK clients, loading config). Large packages, many dependencies, heavy init work and low memory (and therefore low CPU) all lengthen it. Provisioned concurrency keeps environments initialized ahead of time for a version or alias, removing cold starts, but you pay for it for as long as it is configured.
There is also a limit on how fast one function can scale. According to current documentation, each function can add up to 1,000 concurrent environments every 10 seconds (re-check the number in the docs). Beyond the limit, a synchronous caller such as API Gateway gets a 429 throttling error, while async invocations and event source mappings are retried by Lambda itself. The impact of a throttle therefore depends on the invocation type.
ONE REGION, ONE CONCURRENCY POOL
--------------------------------
account concurrency quota (example: 1000)
+--------------------------------------------------------------+
| checkout-api reserved 300 [PC 100 pre-warmed][200 on-demand]|
| payments-wrk reserved 50 (also its hard ceiling) |
| unreserved pool 650 shared by every other function |
+--------------------------------------------------------------+
request beyond a function's ceiling -> throttled (429 / retried)- One request = one environment
- New environment = cold start
- Reserved = guaranteed slice + ceiling
- Provisioned = pre-initialized
One environment serves many requests in sequence, so clients and caches created outside the handler are free on warm invocations.
Setting concurrency
aws lambda get-account-settings --query AccountLimit
# Guarantee 300 for checkout and cap the worker at 50
aws lambda put-function-concurrency --function-name checkout-api \
--reserved-concurrent-executions 300
aws lambda put-function-concurrency --function-name payments-worker \
--reserved-concurrent-executions 50
# Provisioned concurrency always targets a version or alias, never $LATEST
VERSION=$(aws lambda publish-version --function-name checkout-api \
--query Version --output text)
aws lambda update-alias --function-name checkout-api --name live \
--function-version "$VERSION"
aws lambda put-provisioned-concurrency-config --function-name checkout-api \
--qualifier live --provisioned-concurrent-executions 100Reserved concurrency applies to the whole function; provisioned concurrency applies to one version or alias. Callers must invoke the alias (live); invoking $LATEST does not use the pre-initialized environments.
Worked example: a worker with partial batch response and idempotency
This handler processes each record of an SQS batch with the Powertools BatchProcessor and returns only the failed records in batchItemFailures. The charge function is wrapped with idempotent_function, so when a message with the same paymentId arrives twice, the result stored in DynamoDB is returned instead of charging again. The batch holds one good, one invalid and one duplicate message.
import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
process_partial_response,
)
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
logger = Logger(service="payments")
tracer = Tracer(service="payments")
processor = BatchProcessor(event_type=EventType.SQS)
persistence = DynamoDBPersistenceLayer(table_name="payments-idempotency")
config = IdempotencyConfig(event_key_jmespath="paymentId", expires_after_seconds=3600)
CHARGED = [] # stands in for the real payment provider call
@idempotent_function(
data_keyword_argument="payment", persistence_store=persistence, config=config
)
def charge(payment: dict) -> dict:
if payment["amount"] <= 0:
raise ValueError(f"invalid amount for {payment['paymentId']}")
CHARGED.append(payment["paymentId"])
return {"paymentId": payment["paymentId"], "status": "CHARGED"}
@tracer.capture_method
def record_handler(record) -> dict:
payment = json.loads(record.body)
result = charge(payment=payment)
logger.info("payment processed", extra=result)
return result
@logger.inject_lambda_context
@tracer.capture_lambda_handler
def lambda_handler(event, context):
config.register_lambda_context(context)
return process_partial_response(
event=event,
record_handler=record_handler,
processor=processor,
context=context,
)
if __name__ == "__main__":
class FakeContext:
function_name = "payments-worker"
memory_limit_in_mb = 512
invoked_function_arn = (
"arn:aws:lambda:us-east-1:111122223333:function:payments-worker"
)
aws_request_id = "req-1"
def get_remaining_time_in_millis(self) -> int:
return 30000
def sqs_record(message_id: str, body: dict) -> dict:
return {
"messageId": message_id,
"receiptHandle": "rh-" + message_id,
"body": json.dumps(body),
"attributes": {"ApproximateReceiveCount": "1"},
"messageAttributes": {},
"md5OfBody": "",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:us-east-1:111122223333:payments",
"awsRegion": "us-east-1",
}
logger.setLevel("ERROR") # keep the local demo output short
event = {
"Records": [
sqs_record("m1", {"paymentId": "p-100", "amount": 40}),
sqs_record("m2", {"paymentId": "p-101", "amount": -5}),
sqs_record("m3", {"paymentId": "p-100", "amount": 40}),
]
}
print(json.dumps(lambda_handler(event, FakeContext())))
print("charged:", CHARGED)Not runnable in the browser
This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.
Code breakdown
- Module scope
persistence = DynamoDBPersistenceLayer(table_name="payments-idempotency")The Logger, Tracer, processor and boto3 clients are built outside the handler, so they are created once per cold start and reused by every warm invocation.
- Idempotency
config = IdempotencyConfig(event_key_jmespath="paymentId", ...)paymentId is the idempotency key. The first call writes an IN_PROGRESS record to DynamoDB, then stores COMPLETED with the result. When m3 repeats p-100, the stored result is returned, so p-100 appears in CHARGED only once.
- Partial batch response
return process_partial_response(...)Only m2, whose record_handler raised, goes into batchItemFailures. With ReportBatchItemFailures enabled on the event source mapping, Lambda deletes m1 and m3 from the queue and makes only m2 visible again.
- register_lambda_context
Registering the context tells Powertools how much time remains, so an IN_PROGRESS record left behind by a timeout does not block the next retry forever.
{"batchItemFailures": [{"itemIdentifier": "m2"}]}
charged: ['p-100']- ESM polls a batch
- Handler processes each record
- Returns IDs of failed records
- ESM deletes the successful ones
Record succeeds
Deleted from queue
Record fails
Visible again -> DLQ after maxReceiveCount
Tuning event source mappings
For poll-based sources such as SQS, Kinesis, DynamoDB Streams and Kafka, the Lambda service itself polls through an event source mapping (ESM) and invokes your function with batches. BatchSize is the maximum records per batch; MaximumBatchingWindowInSeconds is how long to wait to fill a batch. Bigger batches and longer windows cut invocations (and cost) but add latency.
For SQS, AWS recommends a queue visibility timeout of about six times the function timeout; otherwise messages still being processed become visible again. ScalingConfig's MaximumConcurrency caps the concurrency one ESM can drive. Kinesis and DynamoDB Streams process each shard in order, and BisectBatchOnFunctionError, MaximumRetryAttempts and an on-failure destination stop a 'poison record' from blocking a whole shard.
aws lambda create-event-source-mapping --function-name payments-worker \
--event-source-arn arn:aws:sqs:us-east-1:111122223333:payments \
--batch-size 10 \
--maximum-batching-window-in-seconds 5 \
--function-response-types ReportBatchItemFailures \
--scaling-config MaximumConcurrency=20Async invocation: retries and destinations
Services such as S3, SNS and EventBridge invoke Lambda asynchronously. Lambda puts the event on an internal queue and, on a function error, retries twice more by default, keeping the event for up to six hours. Those retries are why idempotency matters for async functions too.
Destinations send the invocation result to SQS, SNS, Lambda or EventBridge, with separate on-success and on-failure targets. Compared with the older DLQ setting, a destination record carries more context, such as the request payload, the error message and the retry count, which makes debugging easier.
cat > destinations.json <<'JSON'
{"OnFailure": {"Destination": "arn:aws:sqs:us-east-1:111122223333:thumb-failed"}}
JSON
aws lambda put-function-event-invoke-config --function-name thumbnailer \
--maximum-retry-attempts 1 \
--maximum-event-age-in-seconds 3600 \
--destination-config file://destinations.jsonMemory, CPU and SnapStart
You cannot pick CPU directly in Lambda; it is allocated in proportion to memory (128 MB to 10,240 MB). Around 1,769 MB you get one full vCPU, and at the maximum up to six vCPUs. Pricing is per GB-second, so doubling memory on a CPU-bound function often halves its duration, making it faster for about the same cost. Measure with the open-source AWS Lambda Power Tuning tool.
SnapStart takes a snapshot of an initialized environment for a published version and, on a cold start, resumes from it instead of initializing from scratch. It launched for Java runtimes and was later extended to some Python and .NET runtimes (such as Python 3.12+); check the documentation for the current runtime list and for the caching and restore charges that can apply to non-Java runtimes. Every environment resumed from a snapshot shares the same init state, so be careful with random seeds, unique IDs and network connections created during init. It cannot be combined with provisioned concurrency.
Powertools Logger and Tracer
Logger emits every log line as structured JSON with fields such as service, cold_start and function_request_id, which makes CloudWatch Logs Insights queries easy. Tracer adds X-Ray subsegments through decorators and records cold starts as an annotation. Traces only appear when active tracing is enabled on the function.
In production
In production
Teams usually split functions into customer-facing and background ones. Customer-facing APIs get reserved concurrency plus provisioned concurrency that Application Auto Scaling raises on a schedule during business hours, while background workers are capped with reserved concurrency at what the downstream database can handle.
- Every SQS worker enables ReportBatchItemFailures, and the queue has a DLQ with a maxReceiveCount.
- Side effects such as payments and emails are protected with Powertools idempotency.
- Alarms on Throttles, ConcurrentExecutions and, for streams, IteratorAge.
- Each deploy publishes a new version and CodeDeploy shifts the alias to it gradually.
Most cold start problems can be solved before buying provisioned concurrency: shrink the package, drop unused imports and cut network calls during init. Add provisioned concurrency only when cold starts genuinely hurt p99 latency, and measure that first with the Init Duration field in each REPORT log line.
Common mistakes
Common mistakes
Mistake 1: not enabling ReportBatchItemFailures on the ESM
If the handler returns batchItemFailures but the event source mapping does not have FunctionResponseTypes set to ReportBatchItemFailures, Lambda ignores the response and treats the whole batch as successful, so the failed messages silently disappear. You need both the code and the ESM setting.
Mistake 2: setting reserved concurrency without thinking
Reserved concurrency is also a ceiling, so a small value like 5 throttles the function itself when traffic rises. Conversely, reserving for many functions shrinks the unreserved pool and throttles the functions without a reservation. For SQS workers prefer the ESM's MaximumConcurrency; capping with a tiny reserved concurrency causes throttled messages that can land in the DLQ unnecessarily.
Mistake 3: trusting init state too much
Globals outside the handler survive between warm invocations. Storing one request's user data in a global can leak it into the next request. With SnapStart, a random value generated during init can end up shared by every environment.
💰 Cost & Cleanup
Lambda is billed per request and per GB-second (memory × duration), with a monthly free tier. Provisioned concurrency is billed for every hour it is configured, even with zero invocations, so delete it right after the lab. Reserved concurrency is free. The DynamoDB idempotency table (on-demand), SQS requests, X-Ray traces and CloudWatch Logs add small amounts. SnapStart for Python and .NET can carry cache and restore charges; check the pricing page.
Clean up when you are done
aws lambda delete-provisioned-concurrency-config --function-name checkout-api \
--qualifier live
aws lambda delete-function-concurrency --function-name checkout-api
aws lambda delete-event-source-mapping --uuid "$ESM_UUID"
aws lambda delete-function-event-invoke-config --function-name thumbnailer
aws lambda delete-function --function-name payments-worker
aws dynamodb delete-table --table-name payments-idempotency
aws sqs delete-queue --queue-url "$PAYMENTS_QUEUE_URL"Mini challenge
Mini challenge: change the idempotency key
Suppose the payment provider allows retries with the same paymentId but a different amount. Change the worker so a message is a duplicate only when both paymentId and amount match.
- Change event_key_jmespath in IdempotencyConfig to combine both fields
- In one batch, p-100/40 and p-100/45 must both be charged
- Sending p-100/40 again must not charge again
Expected: CHARGED becomes ['p-100', 'p-100'] (the two different amounts) and the third message gets the cached result.
Show hint
A JMESPath multiselect list such as "[paymentId, amount]" hashes both fields into one key.
Show solution
from aws_lambda_powertools.utilities.idempotency import IdempotencyConfig
# Both fields form the key: same id + same amount = duplicate
config = IdempotencyConfig(
event_key_jmespath="[paymentId, amount]",
expires_after_seconds=3600,
)
print("key expression:", config.event_key_jmespath)Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Concurrency ≈ request rate × duration, and every function in a region shares one pool.
- Reserved = free guarantee plus ceiling; provisioned = paid, pre-initialized environments.
- Always pair partial batch responses with idempotency in SQS workers.
- Tune async retries and add an on-failure destination.
- Memory also sets CPU, so choose it by measuring.
Lambda function scaling and concurrency — AWS Documentation
Using Lambda with Amazon SQS — AWS Documentation
Powertools for AWS Lambda (Python) — AWS Documentation