Sub topic 3
Configuring memory, timeout and environment variables
This chapter assumes you can write a basic handler and deploy it with the console or the AWS CLI. It covers three settings that change how a function runs: memory, timeout and environment variables.
Memory sets CPU and cost
You choose memory from 128 MB to 10,240 MB in 1 MB steps. There is no separate CPU setting. Lambda allocates CPU in proportion to memory, and a function with about 1,769 MB gets the equivalent of one vCPU.
Billing is duration multiplied by memory, measured in GB-seconds. A higher setting costs more per millisecond. For CPU-bound code, the extra CPU can shorten the run enough to cost the same or less. For code that mostly waits on network calls, extra memory usually only raises the cost.
To find the right value, run a representative workload at several settings and compare the "Max Memory Used" and "Billed Duration" fields in the REPORT line that Lambda writes to CloudWatch Logs. The open-source AWS Lambda Power Tuning tool automates this comparison.
Timeout bounds a single invocation
The timeout is the longest an invocation may run. The default is 3 seconds and the maximum is 900 seconds (15 minutes). When the limit is reached, Lambda stops the invocation and reports an error. You are billed for the time used.
Set the timeout from the caller's side:
- An API Gateway HTTP API waits at most 30 seconds, so a longer function timeout does not help a synchronous web request.
- For an SQS trigger, set the queue's visibility timeout to at least six times the function timeout. Otherwise messages can become visible again while they are still being processed.
Environment variables carry configuration
Environment variables are key-value strings available to your code. They let you keep names such as a table or bucket out of the source. The total size of all variables is limited to 4 KB.
import os
TABLE_NAME = os.environ["TABLE_NAME"]
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")
def handler(event, context):
print(f"Writing to {TABLE_NAME} at level {LOG_LEVEL}")
return {"statusCode": 200}Use os.environ[...] for required values so a missing one fails at startup. Use .get with a default for optional ones.
Lambda encrypts variables at rest, but they are visible to anyone who can read the function configuration. Do not put passwords or API keys in them. Store secrets in AWS Secrets Manager or SSM Parameter Store, and keep only the secret's name in a variable. Fetch the value outside the handler so warm invocations reuse it.
Setting values
With the AWS CLI:
aws lambda update-function-configuration \
--function-name orders-function \
--memory-size 512 \
--timeout 15 \
--environment "Variables={TABLE_NAME=orders,LOG_LEVEL=DEBUG}"Note that --environment replaces the whole set of variables. Include every variable you want to keep.
With SAM, the same settings go under the function's properties:
OrdersFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
CodeUri: src/
MemorySize: 512
Timeout: 15
Environment:
Variables:
TABLE_NAME: orders
LOG_LEVEL: DEBUGA configuration change applies to new execution environments. Existing warm environments are replaced, so the first invocations after the update are cold starts.
Limits at a glance
| Setting | Default | Range |
|---|---|---|
| Memory | 128 MB | 128 to 10,240 MB |
| Timeout | 3 seconds | 1 to 900 seconds |
| Environment variables | none | 4 KB total |
| Ephemeral storage (`/tmp`) | 512 MB | 512 to 10,240 MB |
Common errors
- Task timed out after 3.00 seconds. The default timeout is too low for the work. Raise it, or check whether a slow dependency is the cause.
- Runtime exited with error: signal: killed. The function ran out of memory. Increase memory and compare it with "Max Memory Used".
- KeyError on an environment variable. The variable was never set, or a CLI update overwrote the set without it.
Exercise
A function that resizes images takes 8 seconds at 512 MB and is CPU-bound. What would you test, and why might the cost not rise?
Show answer
Test higher memory settings such as 1024 MB and 2048 MB. More memory brings proportionally more CPU, so the run may fall to roughly 4 seconds or less. The price per millisecond doubles, but the billed duration halves, so the GB-seconds can stay about the same while latency improves.