Concurrency, Scaling and Event Sources
Overview
Concurrency is the number of function instances running at the same moment. If requests arrive at 100 per second and each lasts 2 seconds, you need about 200 concurrent environments. Lambda scales out automatically, but accounts have a shared concurrency limit, and some event sources have their own scaling rules.
Think of a call centre. Concurrency is the number of agents on calls at once. Reserved concurrency guarantees a team of agents for one department (and caps it), while provisioned concurrency keeps agents sitting by the phone already trained so the first caller never waits.
Event sources decide how functions are invoked. Understanding sync, async and polling models, batching and failure handling is a staple of the exam.
Key Concepts
- Concurrency = requests per second x average duration (seconds).
- Reserved concurrency guarantees and limits a function's share of the account pool; setting it to 0 effectively disables the function.
- Provisioned concurrency pre-initialises environments for low latency and is billed even when idle; use Application Auto Scaling to schedule it.
- Exceeding concurrency causes throttling (HTTP 429 for sync; retries for async and polling sources).
- Event source mappings poll SQS, Kinesis, DynamoDB Streams, MSK, MQ and invoke with batches.
- SQS: configure batch size, batching window, maximum concurrency and ReportBatchItemFailures for partial failures.
- Streams (Kinesis/DynamoDB): one shard processed in order; a failing batch blocks the shard unless you use bisect on error, retry limits and an on-failure destination.
- Async invocations support retry attempts, maximum event age, DLQ and destinations (success and failure).
Detailed Notes
Concurrency controls
| Control | Purpose | Cost |
|---|---|---|
| Account limit | Default 1,000 concurrent per Region (soft limit) | none |
| Reserved concurrency | Guarantee and cap for a function | free |
| Provisioned concurrency | Warm environments, no cold starts | charged while provisioned |
| SQS maximum concurrency | Limit parallel pollers for an SQS mapping (min 2) | free |
Burst scaling: each function can add environments quickly (up to 1,000 new environments every 10 seconds per function), then continues until the account limit.
aws lambda put-function-concurrency \
--function-name OrdersFn --reserved-concurrent-executions 50
aws lambda put-provisioned-concurrency-config \
--function-name OrdersFn --qualifier prod \
--provisioned-concurrent-executions 20
Provisioned concurrency applies to a version or alias, not $LATEST.
Event source behaviours
| Source | Model | Failure handling |
|---|---|---|
| API Gateway / ALB / Function URL | Synchronous | Error returned to caller |
| S3, SNS, EventBridge | Asynchronous | 2 retries, then DLQ or destination |
| SQS | Polling | Message returns after visibility timeout; DLQ on the queue |
| Kinesis / DynamoDB Streams | Polling, ordered per shard | Retries until success or expiry; bisect, destinations |
SQS partial batch response
Without it, one bad message in a batch of 10 causes all 10 to return. Return only the failures:
def handler(event, context):
failures = []
for record in event["Records"]:
try:
process(record["body"])
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}
Events:
Queue:
Type: SQS
Properties:
Queue: !GetAtt JobsQueue.Arn
BatchSize: 10
MaximumBatchingWindowInSeconds: 5
FunctionResponseTypes: [ReportBatchItemFailures]
ScalingConfig:
MaximumConcurrency: 20
The queue's visibility timeout should be at least six times the function timeout, and the DLQ belongs on the queue, not the function, for SQS sources.
Stream processing settings
aws lambda create-event-source-mapping \
--function-name StreamFn \
--event-source-arn arn:aws:kinesis:eu-west-1:111122223333:stream/clicks \
--starting-position LATEST --batch-size 200 \
--bisect-batch-on-function-error \
--maximum-retry-attempts 3 \
--parallelization-factor 4 \
--destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:eu-west-1:111122223333:stream-dlq"}}'
ParallelizationFactor (1-10) processes multiple batches per shard concurrently while keeping order per partition key.
Destinations vs DLQ
A DLQ (SQS or SNS) only captures failures of async invocations. Destinations capture both success and failure and can target SQS, SNS, Lambda or EventBridge, including the original event and error details. Destinations are generally preferred.
Idempotent consumers
SQS standard and async invocations are at-least-once, so handlers must tolerate duplicates.
Troubleshooting throttles
Check the Throttles and ConcurrentExecutions CloudWatch metrics. If one function consumes the pool, apply reserved concurrency to protect critical functions and to protect downstream databases from being overwhelmed.
How Lambda scales
Each concurrent request needs its own execution environment. A function can add up to 1,000 new environments every 10 seconds until it reaches the account (default 1,000 per Region, raisable) or reserved limit. After that, synchronous callers get 429 TooManyRequestsException, asynchronous events are retried for up to six hours, and poll-based sources slow down.
| Event source | Who invokes | Scaling behaviour | Failure handling |
|---|---|---|---|
| API Gateway, ALB, function URL | Caller (sync) | One environment per concurrent request | Error returned to client |
| S3, SNS, EventBridge | Service (async) | Internal queue, scales with events | 2 retries, then DLQ/destination |
| SQS standard | Poller (Lambda) | Starts at 5 pollers, +300 per minute, up to 1,250 | Message returns after visibility timeout |
| Kinesis / DynamoDB Streams | Poller | One batch per shard (up to 10 with parallelization factor) | Blocks shard until success or expiry |
Filtering events before invocation
Event source mappings accept filter criteria, so Lambda only runs (and bills) for matching records.
aws lambda create-event-source-mapping --function-name orders-fn \
--event-source-arn arn:aws:sqs:eu-west-1:111122223333:orders \
--batch-size 10 --maximum-batching-window-in-seconds 5 \
--scaling-config MaximumConcurrency=20 \
--function-response-types ReportBatchItemFailures \
--filter-criteria '{"Filters":[{"Pattern":"{\"body\":{\"type\":[\"order\"]}}"}]}'
Messages that do not match are deleted from SQS without invoking the function, so use filters only when dropping them is intended. Remember the SQS queue visibility timeout must be at least six times the function timeout.
Real World Example
A payments platform processes card events from SQS. A marketing batch job in the same account saturated account concurrency, throttling the payment function. The team set reserved concurrency of 200 on the payments function and a maximum concurrency of 30 on the SQS mapping for the batch job, protecting the RDS database behind it. They also enabled partial batch responses, which stopped a single poison message from re-processing nine good ones.
Architecture Diagram
Lambda polls the queue, invokes batches, and failed messages move to a DLQ.
- 1Lambda's poller reads batches from the queue.
- 2It invokes function instances up to the concurrency limits.
- 3Successful messages are deleted; failed IDs return to the queue.
- 4After repeated failures messages move to the DLQ.
Best Practices
- ✓Use reserved concurrency to protect critical functions and downstream systems.
- ✓Return partial batch failures for SQS and stream sources.
- ✓Set the queue visibility timeout >= 6 x function timeout.
- ✓Prefer destinations over DLQs for async functions.
- ✓Make all handlers idempotent.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Throttled critical function -> reserved concurrency (or request a limit increase).
- Cold-start-sensitive API -> provisioned concurrency on an alias.
- SQS DLQ lives on the queue; async Lambda DLQ/destination lives on the function.
- Streams retry the failed batch until it succeeds or expires, blocking the shard.
Finished this lesson?
0 of 46 lessons done · 0% of the course

