Sub topic 3
Configuring Memory, Timeout and Environment Variables
This chapter covers the three settings that shape every Lambda function: how much memory it gets, how long it may run, and how it receives configuration. It assumes you can write a basic handler (the previous chapter), read JSON, and use the AWS console or CLI. It also assumes you have a general idea of what an IAM role is.
What the three settings control
| Setting | What it controls | Default | Limits |
|---|---|---|---|
| Memory | RAM, and CPU power in proportion to RAM | 128 MB | 128 MB to 10,240 MB, in 1 MB steps |
| Timeout | Maximum run time of one invocation | 3 seconds | 1 second to 900 seconds (15 minutes) |
| Environment variables | Key-value configuration passed to your code | none | 4 KB total for all keys and values |
These are per-function settings. They are fixed when you deploy and apply to every invocation of that function version. Changing them does not require a code change.
Memory is also your CPU dial
Lambda has no separate CPU setting. When you raise memory, Lambda gives the function proportionally more CPU, network bandwidth and disk throughput. At about 1,769 MB a function gets the equivalent of one vCPU. At 10,240 MB it gets up to six vCPUs.
For a CPU-bound function, more memory can shorten the run enough to cost the same or less, even though the price per millisecond rises. Billing is memory multiplied by duration, measured in GB-seconds. Duration is rounded up to the nearest millisecond.
The numbers below are illustrative. They show a typical pattern for a function that compresses a small payload.
| Memory | Duration | GB-seconds per invocation |
|---|---|---|
| 128 MB | 800 ms | 0.125 × 0.800 = 0.100 |
| 512 MB | 200 ms | 0.500 × 0.200 = 0.100 |
| 1,024 MB | 110 ms | 1.000 × 0.110 = 0.110 |
| 2,048 MB | 100 ms | 2.000 × 0.100 = 0.200 |
In this example 512 MB costs the same as 128 MB and runs four times faster. Beyond 1,024 MB the function stops using the extra CPU, so you pay more for no gain. Functions that spend their time waiting on a network call show a flat duration curve, and the cheapest setting is then the smallest one that avoids out-of-memory errors.
Two related settings are easy to confuse with memory:
- Ephemeral storage is the size of
/tmp. It ranges from 512 MB to 10,240 MB, and sizes above 512 MB are billed separately. - Architecture (x86_64 or arm64) changes the price per GB-second. Measure both, because the same code can run at a different speed on each.
Finding the right value
Every invocation writes a REPORT line to CloudWatch Logs:
REPORT RequestId: 3f1c0a1e-0000-0000-0000-000000000000 Duration: 112.31 ms Billed Duration: 113 ms Memory Size: 512 MB Max Memory Used: 95 MBMax Memory Used tells you how close you are to the limit. If it sits near Memory Size, raise memory. The AWS Lambda Power Tuning project, an open-source Step Functions state machine, automates the search. It runs your function at several memory sizes and plots cost against speed.
Timeout
The timeout is a hard limit. When it expires, Lambda stops the invocation and logs Task timed out after 3.00 seconds. The function does not get a chance to clean up. For a synchronous caller the result is an error, and for other invocation types the retry rules apply (covered in later chapters).
Set the timeout from what the function does, not to the maximum. A function that calls a database should time out shortly after the longest reasonable query. A 900-second timeout on a function whose dependency has hung makes you pay for 900 seconds of waiting.
The timeout also interacts with the service that triggers the function:
- API Gateway REST APIs have a default integration timeout of 29 seconds. HTTP APIs allow up to 30 seconds. A Lambda timeout longer than that cannot help a synchronous web request, because the client gets a 504 first.
- For SQS triggers, set the queue's visibility timeout to at least six times the function timeout, as AWS recommends. If the visibility timeout is shorter than the processing time, messages reappear and are processed twice.
- Your own SDK calls should have shorter timeouts than the function. Otherwise one slow call uses the whole budget.
Your code can see how much time is left. The context object provides get_remaining_time_in_millis() in Python, and you can use it to stop gracefully and return partial progress.
import os
TABLE_NAME = os.environ["TABLE_NAME"]
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")
SAFETY_MARGIN_MS = int(os.environ.get("SAFETY_MARGIN_MS", "2000"))
def handle_item(item):
# Placeholder for real work, such as a write to TABLE_NAME.
return item
def handler(event, context):
processed = []
for item in event.get("items", []):
if context.get_remaining_time_in_millis() < SAFETY_MARGIN_MS:
break # leave time to return a clean response
processed.append(handle_item(item))
return {
"processed": len(processed),
"remaining": len(event.get("items", [])) - len(processed),
"log_level": LOG_LEVEL,
"table": TABLE_NAME,
}The caller can inspect remaining and send the unfinished items again. This pattern is useful for batch jobs that approach the timeout.
Environment variables
Environment variables let one build of your code run in several environments with different settings, such as table names, feature flags and log levels. Lambda exposes them as ordinary process environment variables, so os.environ works in Python and process.env in Node.js.
Points to know:
- The total size of all keys and values is limited to 4 KB.
- Lambda encrypts them at rest with an AWS-managed KMS key by default. You can choose a customer-managed key. The values are still visible in plain text to anyone who can call
GetFunctionConfiguration, and in the console. - Do not store passwords or API keys in them. Keep a secret in AWS Secrets Manager or SSM Parameter Store, put its name in an environment variable, and fetch it during initialization.
- Some names are reserved and set by Lambda, such as
AWS_REGION,AWS_LAMBDA_FUNCTION_NAME,AWS_LAMBDA_FUNCTION_MEMORY_SIZEand_HANDLER. You cannot overwrite the reserved ones. Use your own prefix for application settings. - Variables are read from the environment, so values are always strings. Convert numbers and booleans yourself, as
SAFETY_MARGIN_MSis converted above. - A change to any variable creates new execution environments. Warm environments running the old values are retired.
Read variables at module level, outside the handler, when they do not change per request. A missing required variable then fails during initialization, and the error is clear and happens on the first invocation. In the example above, os.environ["TABLE_NAME"] raises KeyError immediately if the variable is absent, while os.environ.get(...) with a default is appropriate for optional settings.
Setting values in a SAM template
Defining these settings in a template makes them reviewable and repeatable. This template uses Globals for defaults shared by all functions, then overrides memory for one function.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
LogLevel:
Type: String
Default: INFO
AllowedValues: [DEBUG, INFO, WARNING, ERROR]
Globals:
Function:
Runtime: python3.12
Timeout: 10
MemorySize: 256
Resources:
BatchFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
CodeUri: src/
MemorySize: 512
Timeout: 60
EphemeralStorage:
Size: 1024
Environment:
Variables:
TABLE_NAME: !Ref BatchTable
LOG_LEVEL: !Ref LogLevel
SAFETY_MARGIN_MS: '3000'
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref BatchTable
BatchTable:
Type: AWS::Serverless::SimpleTableThe function's own MemorySize and Timeout override the global values. Environment variable values in a template should be written as strings, which is why '3000' is quoted.
You can also change a deployed function directly with the AWS CLI. This is handy for experiments, but the next deployment from your template overwrites it.
aws lambda update-function-configuration \
--function-name orders-function \
--memory-size 512 \
--timeout 15 \
--environment "Variables={TABLE_NAME=orders,LOG_LEVEL=DEBUG}"The --environment option replaces the whole set of variables. Any variable you leave out is deleted, so always include the full list.
Common errors and their causes
| Symptom | Likely cause | Fix |
|---|---|---|
| `Task timed out after 3.00 seconds` | The default timeout is too short for the work or a dependency | Raise the timeout after checking where time is spent |
| `Runtime.OutOfMemory` or the process exits abruptly, and `Max Memory Used` equals `Memory Size` | The function ran out of memory | Raise memory, or reduce the data held in memory |
| API Gateway returns 504 while Lambda reports success | The function ran longer than the gateway's integration limit | Shorten the work or make the call asynchronous |
| `KeyError: 'TABLE_NAME'` during init | The variable is missing from the deployed configuration | Add it to the template and redeploy |
| Messages processed more than once from SQS | Visibility timeout is shorter than the function timeout | Set visibility timeout to at least six times the function timeout |
| Variables disappear after a CLI update | `--environment` replaced the entire set | Send all variables every time |
| Slow function that does not speed up with memory | The time is spent waiting on I/O, not on CPU | Look at dependency latency, and keep memory small |
Initialization code, which runs before the handler on a new environment, counts against its own time limit and can add to billed time. Heavy imports and large downloads at module level slow cold starts, which a later chapter covers.
Exercise
A function shows "Duration: 900 ms, Memory Size: 128 MB, Max Memory Used: 120 MB" in its REPORT line, and it is CPU-bound. You test 512 MB and the duration drops to 210 ms. Compare the GB-seconds per invocation at both sizes, and say what you would do next.
Show answer
At 128 MB: 0.125 GB × 0.900 s = 0.1125 GB-seconds. At 512 MB: 0.5 GB × 0.210 s = 0.105 GB-seconds. The larger size is both faster and slightly cheaper. Next, test 1,024 MB and above, and stop where the duration no longer falls enough to offset the higher memory. Also note that 120 MB of 128 MB used was close to the limit, so the 128 MB setting was risky.
Exercise
A function behind an API Gateway HTTP API has a 60-second timeout, and users report 504 errors on slow requests. Why does raising the timeout not help, and what two designs would fix it?
Show answer
HTTP APIs cut off the integration at about 30 seconds, so the client receives a 504 before Lambda's 60-second timeout is reached. Either shorten the work (for example, optimize the slow dependency call), or return immediately and do the long work asynchronously, such as by putting a message on a queue that a second function processes while the client polls for the result.