AWS Lambda Functions
Each entry under functions in serverless.yml is an AWS Lambda function: an exported handler that Lambda calls once per event or request. This page lists the settings a function takes, where each one can be set (per function, or service-wide under provider), and what the Framework creates in AWS for it. To run a standard HTTP server such as Express, Fastify, Hono or Next.js instead, use a web app (see Web apps or functions?).
The smallest service with one function:
# serverless.yml
service: my-service
provider:
name: aws
runtime: nodejs24.x
functions:
hello:
handler: handler.hello
// handler.mjs
export const hello = async (event) => {
return { message: 'Hello from Lambda' }
}
handler is the file path without its extension, a dot, and the exported function name: handler.hello runs the hello export of handler.mjs (or handler.js) next to serverless.yml. Run serverless deploy from the service directory to create the function; to trigger it from an AWS event source, add events.
Configuration
The basic function settings, with their defaults:
# serverless.yml
service: my-service
provider:
name: aws
runtime: nodejs24.x # default runtime for every function
memorySize: 512 # MB, default 1024
timeout: 10 # seconds, default 6
architecture: arm64 # default x86_64
functions:
hello:
handler: handler.hello # required unless the function uses `image`
name: ${sls:stage}-hello # deployed name, default <service>-<stage>-<function key>
description: Says hello # up to 256 characters
runtime: python3.14 # overrides provider.runtime
memorySize: 1024 # overrides provider.memorySize
timeout: 30 # overrides provider.timeout
| Key | Type | Default | Allowed values |
|---|---|---|---|
handler | string | Required (unless image) | <file path without extension>.<export> |
name | string | <service>-<stage>-<key> | Any valid Lambda function name |
description | string | None | Up to 256 characters |
runtime | string | provider.runtime, else nodejs20.x | A Lambda runtime identifier, or a customer-managed runtime alias ARN |
memorySize | integer | provider.memorySize, else 1024 | 128 to 10240 (MB) |
timeout | integer | provider.timeout, else 6 | 1 to 1800 (seconds) |
architecture | string | provider.architecture, else x86_64 | x86_64, arm64 |
For a setting that exists both on the function and under provider, the function's own value wins, and provider supplies the value for functions that don't set one. environment, tags and the logs keys are merged key by key instead (see Environment variables, Tags and Log format and log levels).
Runtime
provider.runtime sets the runtime for every function, and a function's own runtime overrides it. When neither is set, the function uses nodejs20.x, a runtime AWS has deprecated, so set a runtime explicitly. Every AWS Lambda managed runtime identifier is accepted, including the Amazon Linux 2023 Java runtimes java8.al2023, java11.al2023 and java17.al2023. To use a runtime your organization publishes, set runtime to its alias ARN: see Customer-managed runtimes.
When a function uses a runtime AWS has deprecated, serverless package and serverless deploy print a warning that names the functions, the deprecation date and the dates Lambda stops allowing new functions and updates on that runtime, with a link to the list of supported runtimes. The warning covers functions that get the default runtime too. Container image functions are not checked, because their runtime comes from the image.
Memory size limits
memorySize accepts 128 to 10240 MB. A function with capacityProvider (Lambda Managed Instances) defaults to 2048 MB instead of 1024, needs at least 2048 MB, and accepts up to 32768 MB; a value outside those ranges stops packaging with an error.
Timeout limits
timeout accepts 1 to 1800 seconds (30 minutes), the maximum Lambda allows for most functions. Lambda allows up to 5400 seconds for Managed Instances functions invoked asynchronously or through most event source mappings (Lambda quotas); the Framework's schema still warns above 1800. A caller can stop waiting sooner: an http or httpApi event answers the client within the API Gateway integration timeout, while the function keeps running until it returns or reaches its own timeout. A function with capacityProvider (Lambda Managed Instances) is not stopped at its timeout: Lambda fails the invocation, but the code keeps running, so check the remaining time in the invocation context and stop before it reaches zero (invoke timeouts).
Functions in separate files
functions also takes a list, which lets you keep functions in separate files. Each file holds function entries keyed by name:
# serverless.yml
functions:
- ${file(./foo-functions.yml)}
- ${file(./bar-functions.yml)}
# foo-functions.yml
getFoo:
handler: handler.getFoo
deleteFoo:
handler: handler.deleteFoo
Execution role permissions
Every Lambda function runs with an IAM execution role. By default, the Framework creates one role for the service and adds the permissions the function's own settings need (logs, event sources, VPC access, and the others named on this page). To let your code call other AWS services, add statements under provider.iam.role.statements:
provider:
name: aws
iam:
role:
statements:
- Effect: Allow
Action:
- dynamodb:GetItem
- dynamodb:PutItem
Resource:
Fn::GetAtt: [UsersTable, Arn]
resources:
Resources:
UsersTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
Statements are copied into the CloudFormation template, so Ref, Fn::GetAtt, Fn::Join and other intrinsics work in Resource.
To use an existing role instead, set provider.iam.role to its ARN, or set role on a function. The Framework doesn't change a role you supply: it must already grant everything the function needs, including the permissions this page says the Framework adds. Per-function roles, custom roles and the full list of added permissions are in IAM permissions for functions.
Reserved concurrency
A function's reservedConcurrency sets its reserved concurrency: the maximum number of concurrent executions, set aside from the account's unreserved concurrency. It takes an integer of 0 or more, and 0 stops every invocation of the function. Without it, the function draws on the account's unreserved pool. The setting applies to the function as a whole, so changing it doesn't publish a new version.
functions:
worker:
handler: handler.worker
reservedConcurrency: 5
Provisioned concurrency
A function's provisionedConcurrency keeps a number of execution environments initialized. Set it to an integer, or to an object with executions (required) and alias (default provisioned):
functions:
api:
handler: handler.api
provisionedConcurrency:
executions: 3
alias: live
The Framework publishes a version even when versioning is turned off, and creates an alias that holds the provisioned concurrency. The function's event sources and its function URL invoke that alias. provisionedConcurrency can't be combined with snapStart: packaging stops with an error.
Lambda function URLs
A Lambda function URL is an HTTPS endpoint for one function, without API Gateway. Set url: true on the function for a public URL without CORS:
functions:
api:
handler: handler.api
url: true
serverless deploy prints the URL, and the stack holds it in an output. Without authorizer, the URL accepts requests without AWS credentials, and the Framework adds the resource-based permissions a public URL needs. When the function has snapStart, provisionedConcurrency or durableConfig, the URL targets the alias those settings create.
The object form of url takes these keys:
| Key | Type | Default | Allowed values |
|---|---|---|---|
authorizer | string | None | aws_iam |
cors | boolean, object | No CORS | true, or an object (see Function URL CORS) |
invokeMode | string | BUFFERED | BUFFERED, RESPONSE_STREAM |
Function URL authorization
With authorizer: aws_iam, the URL accepts only requests signed with AWS credentials that allow both lambda:InvokeFunctionUrl and lambda:InvokeFunction on the function. A caller in another AWS account also needs both actions granted in the function's resource-based policy; see Using the AWS_IAM auth type.
functions:
api:
handler: handler.api
url:
authorizer: aws_iam
Function URL CORS
With cors: true, browsers on any origin can call the URL. The Framework sets these headers:
| Header | Value |
|---|---|
Access-Control-Allow-Origin | * |
Access-Control-Allow-Headers | Content-Type, X-Amz-Date, Authorization, X-Api-Key, X-Amz-Security-Token, X-Amzn-Trace-Id |
Access-Control-Allow-Methods | * |
To change them, set cors to an object. Keys you leave out keep the defaults in the preceding table; set allowedOrigins, allowedHeaders or allowedMethods to null to remove that header.
functions:
api:
handler: handler.api
url:
cors:
allowedOrigins:
- https://app.example.com
allowedHeaders:
- Content-Type
- Authorization
allowedMethods:
- GET
allowCredentials: true
exposedResponseHeaders:
- X-Request-Id
maxAge: 6000 # seconds
cors key | Header | Constraint |
|---|---|---|
allowedOrigins | Access-Control-Allow-Origin | 1 to 100 items |
allowedHeaders | Access-Control-Allow-Headers | 1 to 100 items |
allowedMethods | Access-Control-Allow-Methods | 1 to 6 items |
allowCredentials | Access-Control-Allow-Credentials | Boolean |
exposedResponseHeaders | Access-Control-Expose-Headers | 1 to 100 items |
maxAge | Access-Control-Max-Age | Integer, 0 or more |
Function URL response streaming
invokeMode: RESPONSE_STREAM streams the response; the value is case-insensitive.
functions:
api:
handler: handler.api
url:
invokeMode: RESPONSE_STREAM
Referencing container image as a target
A function can run a container image instead of a zip package. Set image instead of handler: setting both, or neither, stops packaging with an error. runtime and runtimeManagement are ignored for image functions, because the image carries the runtime.
image takes one of three forms:
- The key of an image under
provider.ecr.images. - An existing ECR image URI:
<account>.dkr.ecr.<region>.amazonaws.com/<repository>@<digest>or<account>.dkr.ecr.<region>.amazonaws.com/<repository>:<tag>. - An object with
name(a key underprovider.ecr.images) oruri, plus the optional overridesworkingDirectory(a string),commandandentryPoint(lists of strings in exec form).
provider:
name: aws
ecr:
images:
app:
path: ./ # Docker build context holding the Dockerfile
functions:
hello:
image: app
report:
image:
name: app
command:
- report.handler
existing:
image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo@sha256:6bb600b4d6e1d7cf521097177dd0c4e9ea373edb91984a505333be8ac9455d38
Image definitions under provider.ecr.images
Each entry under provider.ecr.images is either an object with uri (an existing image) or an object that the Framework builds with docker build and pushes:
| Key | Type | Description |
|---|---|---|
path | string | Docker build context, relative to the service directory. |
file | string | Dockerfile relative to path. Default Dockerfile. |
buildArgs | object | Passed as --build-arg KEY=value. |
buildOptions | list of strings | Extra options passed to docker build. |
cacheFrom | list of strings | Passed as --cache-from. |
platform | string | Passed as --platform, for example linux/amd64 or linux/arm64. Without it, Docker builds for the local machine. |
provenance | string | Passed as --provenance. |
An entry with uri can't also set path, buildArgs, buildOptions, cacheFrom, platform or provenance. Building needs Docker on the machine that runs serverless deploy.
Build the image for the function's architecture (x86_64 unless set). On an arm64 machine, such as an Apple silicon Mac, set platform: linux/amd64 for an x86_64 function.
provider:
name: aws
ecr:
scanOnPush: true
maxImages: 10
images:
app:
path: ./app
file: Dockerfile.prod
buildArgs:
STAGE: ${sls:stage}
cacheFrom:
- my-image:latest
platform: linux/amd64
The ECR repository for built images
The first deploy that builds an image with path creates an ECR repository named serverless-<service>-<stage> (lowercased) in the deployment account and Region; images referenced by uri need no repository. serverless deploy runs docker login against it when needed; depending on your Docker configuration, the login token may be stored unencrypted (see the credential store section of docker login). serverless remove deletes the repository.
provider.ecr.scanOnPush(boolean, defaultfalse) turns on image scanning. It applies only when the Framework creates the repository; changing it later doesn't update an existing repository.provider.ecr.maxImages(integer, 1 or more, no default) adds an ECR lifecycle policy that expires untagged, superseded images once their count passes the value. The current image of eachprovider.ecr.imagesentry stays tagged and is never expired. The policy is written each time an image is built whilemaxImagesis set; removingmaxImagesleaves the policy on the repository. Older Lambda versions still reference older image digests, so pick a value that covers the versions you might roll back to. The deploying identity needsecr:PutLifecyclePolicy.
Without maxImages, the repository keeps every pushed image.
Instruction set architecture
Lambda functions run on x86_64 processors unless you choose arm64 (AWS Graviton). Set architecture under provider for every function, or on one function:
provider:
name: aws
architecture: arm64
functions:
legacy:
handler: handler.legacy
architecture: x86_64 # overrides provider.architecture
Native dependencies and container images must be built for the architecture the function runs on.
Durable functions
Lambda durable functions coordinate multi-step work that can run for long periods. Turn one on with durableConfig:
functions:
orderWorkflow:
handler: handler.main
runtime: nodejs24.x
durableConfig:
executionTimeout: 3600 # required, seconds, 1 to 31622400 (366 days)
retentionPeriodInDays: 14 # optional, 1 to 90; Lambda's default is 14
- Supported runtimes: Node.js 22 and later, Python 3.13 and later, Java 17 and later, .NET 8 and later, OS-only runtimes from
provided.al2023(for example Go), customer-managed runtimes, and container images. Any other runtime stops packaging with an error. Node.js and Python runtimes include the durable execution SDK; for Java, .NET and Go, include it in your package (for Go, it is built into thebootstrapbinary). See supported runtimes. - Lambda rejects unqualified invocations of durable functions, so the Framework always versions the function and publishes an alias named
durable(or uses the SnapStart or provisioned concurrency alias when the function has one). Event sources and the function URL invoke that alias.versionFunction: falseon the same function stops packaging with an error. - On the execution roles the Framework creates, it attaches the
AWSLambdaBasicDurableExecutionRolePolicymanaged policy. A role you supply needs those permissions too. - Durability is fixed when Lambda creates the function: adding or removing
durableConfigon a deployed function needs a new function name, or removing the function, deploying, and adding it back. ChangingexecutionTimeoutorretentionPeriodInDaysupdates the function in place.
A Go function runs on provided.al2023 with a bootstrap binary that you build and zip before deploying:
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -tags lambda.norpc -o bootstrap main.go
mkdir -p bin && zip bin/orderWorkflow.zip bootstrap
package:
individually: true
functions:
orderWorkflow:
handler: bootstrap
runtime: provided.al2023
architecture: arm64
package:
artifact: bin/orderWorkflow.zip
durableConfig:
executionTimeout: 3600
To start a durable execution and read its ARN, see invoking durable functions.
Runtime management
Runtime management controls when Lambda moves a function to a new runtime version. Set runtimeManagement under provider for every function, or on one function:
auto(Lambda's default): Lambda updates the runtime automatically.onFunctionUpdate: Lambda updates the runtime when you deploy a change to the function.manual: the function stays on the runtime version you name. Only the object form takes it, witharnset to the runtime version ARN.
provider:
name: aws
runtimeManagement: onFunctionUpdate
functions:
pinned:
handler: handler.pinned
runtimeManagement:
mode: manual
arn: arn:aws:lambda:us-east-1::runtime:RUNTIME_VERSION_ID
Replace RUNTIME_VERSION_ID with the runtime version from the function's Lambda console page or from aws lambda get-runtime-management-config. The object form also accepts mode: auto and mode: onFunctionUpdate. Container image functions ignore runtimeManagement.
Customer-managed runtimes
A customer-managed runtime is a Lambda runtime that a team in your organization (or a third party) builds, publishes and updates, for example a Node.js runtime with your company's SDK and monitoring agent built in. Functions use it through a runtime alias and keep deploying .zip files; when the publisher moves the alias to a new runtime version, functions pick it up without a redeploy. To use one, set runtime to the runtime alias ARN the publisher gives you:
provider:
name: aws
region: us-east-1
runtime: arn:aws:lambda:us-east-1:123456789012:runtime/company-node24/alias/prod
functions:
api:
handler: index.handler # the handler format is defined by the runtime publisher
legacy:
handler: handler.main
runtime: nodejs26.x # a function's own runtime overrides provider.runtime
A runtime alias ARN has the form arn:aws:lambda:REGION:ACCOUNT_ID:runtime/RUNTIME_NAME/alias/ALIAS_NAME. The Framework deploys the function with the runtime and alias it names. The rules for the value:
- Use the alias ARN. A runtime ARN without
/alias/, a runtime version ARN, and a bare runtime name get a configuration warning, and the valuecustomstops packaging with an error unlessresourcessupplies the function'sRuntimeConfig. To pin a function to one runtime version, see Runtime updates for customer-managed runtimes. - The runtime must be in the Region the service deploys to. An alias ARN from another Region stops packaging with an error.
runtimealso accepts a CloudFormation intrinsic that returns an alias ARN, such as!Refon anAWS::Lambda::RuntimeAliasresource or!ImportValueof a stack output. Variables such as${cf:runtime-stack.AliasArn}and${ssm:/platform/runtime-alias-arn}work too.
The Lambda console and API also call these runtimes "custom", and Lambda reports such a function's runtime as custom. Runtimes that a function ships in its own package with a bootstrap file on provided.al2023 are a different feature, which AWS now calls bring your own language.
Permissions for customer-managed runtimes
- The principal that deploys the service (your credentials, or
provider.iam.deploymentRole) needslambda:AssociateRuntimeAliason the runtime alias ARN, andlambda:AssociateRuntimeVersionon the runtime version ARN when a function is pinned to a version. - A runtime in another AWS account must also be shared with your account: the runtime's resource-based policy allows
lambda:AssociateRuntimeAliason the alias for your account. The runtime publisher sets that up; see sharing and controlling access to customer-managed runtimes. Without it, the deploy fails withnot authorized to perform: lambda:AssociateRuntimeAlias … because no resource-based policy allows the lambda:AssociateRuntimeAlias action. - The function's execution role needs nothing new. The runtime runs with that role's permissions, so use runtimes only from publishers you trust.
When the alias does not exist, or the deploying principal may not use it, the deploy fails with a message from Lambda, followed by what to check. A deploy that updates an existing function gets a message that names the function instead of the alias:
✖ An error occurred: ApiLambdaFunction - Resource handler returned message: "Lambda function my-service-dev-api could not be found" (RequestToken: …, HandlerErrorCode: NotFound).
Function "api" uses a customer-managed runtime. Check that its runtime alias exists in this Region and that the deploying role has lambda:AssociateRuntimeAlias on it.
A deploy that creates the function gets Runtime Alias not found:
✖ An error occurred: ApiLambdaFunction - Resource handler returned message: "Runtime Alias not found (Service: Lambda, Status Code: 404, …)" (RequestToken: …, HandlerErrorCode: NotFound).
Function "api" uses a customer-managed runtime. Check that its runtime alias exists in this Region and that the deploying role has lambda:AssociateRuntimeAlias on it.
A function whose architecture the runtime does not support fails with The requested architecture arm64 is not supported by the runtime. Supported architectures: [x86_64].
Runtime updates for customer-managed runtimes
runtimeManagement controls when a function picks up a new version of its runtime alias:
auto(the default): at each cold start after the publisher moves the alias.onFunctionUpdate: when a deploy changes the function. An unchangedserverless deployreports "No changes to deploy" and keeps the function on the runtime version it has; a deploy that changes the function's code or configuration picks up the alias's new version.manual: never. Setarnto the runtime version ARN, for examplearn:aws:lambda:us-east-1:123456789012:runtime/company-node24/version/v24.1.3.
The alias in runtime names the runtime and the alias the function follows. A runtime version ARN in runtimeManagement pins the function to that version, whatever the alias points at. Lambda requires the alias even when the function is pinned, and the function follows it again once the pin is removed or the mode changes to auto.
functions:
api:
handler: index.handler
runtime: arn:aws:lambda:us-east-1:123456789012:runtime/company-node24/alias/prod
runtimeManagement:
mode: manual
arn: arn:aws:lambda:us-east-1:123456789012:runtime/company-node24/version/v24.1.3
The INIT_START line in the function's logs names the runtime version each new execution environment uses.
Publish a runtime in the same service
Most teams publish a runtime from its own stack and share it. A service can also define the runtime in resources and reference its alias with !Ref, which also makes CloudFormation create the functions after the alias:
functions:
api:
handler: index.handler
runtime: !Ref CompanyNodeStable
resources:
Resources:
CompanyNode:
Type: AWS::Lambda::Runtime
Properties:
Name: company-node24-${sls:stage}
CompanyNodeV1:
Type: AWS::Lambda::RuntimeVersion
Properties:
RuntimeName: !Select [1, !Split ['runtime/', !Ref CompanyNode]]
Name: v1
ImageUri: 123456789012.dkr.ecr.us-east-1.amazonaws.com/company-node24:v1
CompanyNodeStable:
Type: AWS::Lambda::RuntimeAlias
Properties:
RuntimeName: !Select [1, !Split ['runtime/', !Ref CompanyNode]]
Name: stable
RuntimeVersion: !Select [1, !Split ['version/', !Ref CompanyNodeV1]]
The runtime image must already be in Amazon ECR, in a repository whose policy lets Lambda read it (runtime versions). When serverless remove deletes the stack, Lambda keeps the runtime's name reserved for up to 30 days, and deploying a runtime with the same name fails until then; keep the stage in the runtime name, as above. A runtime waiting for deletion also counts against the account's runtime quota (100 per Region by default), so services that are removed and redeployed often, such as per-branch stages, belong on a shared runtime instead.
Packaging for customer-managed runtimes
The Framework cannot tell which language a customer-managed runtime runs, so it builds these functions only when you ask:
- esbuild bundles a function when the function sets
build: esbuildor the service setsbuild.esbuild. TypeScript handlers are not detected automatically, and no AWS SDK packages are left out of the bundle by default; usebuild.esbuild.externalfor packages the runtime provides. - Python requirements are not installed for these functions. Package dependencies yourself, or ask the runtime publisher which libraries the runtime includes.
Layers work as with other runtimes. A layer built for these functions can list custom in compatibleRuntimes.
Limitations of customer-managed runtimes
- SnapStart, Lambda@Edge (
cloudFrontevents) and container image functions cannot use a customer-managed runtime; each stops packaging with an error. serverless invoke localcannot run these functions; useserverless invoke --function NAMEafter deploying.serverless devkeeps these functions on their deployed code.serverless deploy functionupdates the runtime alias whenruntimeholds the alias ARN, including moving a function onto or off a customer-managed runtime. Whenruntimeis a CloudFormation intrinsic, it keeps the deployed runtime, and moving a function onto the runtime takesserverless deploy.
SnapStart
Lambda SnapStart reduces cold-start latency: when a version is published, Lambda runs the initialization code once, snapshots the initialized environment, and restores later environments from the snapshot. Turn it on per function with snapStart: true, for zip packages and for container images:
functions:
api:
handler: com.example.Handler
runtime: java21
snapStart: true
inference:
image: inference
snapStart: true
Supported runtimes and images
AWS supports SnapStart for Java 11 and later, Python 3.12 and later, and .NET 8 and later, as managed runtimes and as the matching AWS base images. Those functions need nothing beyond snapStart: true.
A container image on any other base (the AWS base images for Node.js, Ruby or provided.al2023, or a custom base) must declare that it is safe to snapshot, with this Dockerfile label or with the SnapStart runtime hooks:
LABEL com.amazonaws.lambda.feature.snapstart="Allow"
Before adding the label, make sure initialization doesn't create state that must be unique per environment, such as random seeds, unique IDs or cached credentials; see Handling uniqueness.
SnapStart deploy error for images without the label
When an image has neither the label nor the hooks, publishing the version fails during deployment and the deploy output includes:
Resource of type 'AWS::Lambda::Version' with identifier '...' did not stabilize. Status Reason is An error occurred during function initialization.
The same message appears when the function's own initialization code throws, so check the function's CloudWatch logs too. On a first deployment, the failed stack is rolled back together with its log group; to read the initialization logs, deploy once without snapStart.
How invocations reach the snapshot
SnapStart applies to published versions only, never to $LATEST. When a deploy changes the function's code, image or configuration, the Framework publishes a version and points an alias named snapstart at it; a deploy that changes nothing keeps the current version. Every event source on the function invokes that alias. Invoking the unqualified function name, for example with serverless invoke -f api, runs a regular cold start; invoke the snapstart alias or a version number to exercise the snapshot.
SnapStart limitations
AWS doesn't support SnapStart together with provisioned concurrency, Amazon EFS, S3 Files, or ephemeral storage above 512 MB. The Framework stops packaging when snapStart is combined with provisionedConcurrency or with ephemeralStorageSize above 512; AWS rejects the other combinations during deployment. SnapStart is not available in every AWS Region; see the AWS SnapStart documentation.
Cost of retained versions
For every runtime except the Java managed runtimes, AWS charges for caching each published version's snapshot for as long as the version exists, plus a charge per restore; see Lambda pricing. With versioning on (the default), each deploy that changes a SnapStart function keeps the previous version, and its snapshot. With provider.versionFunctions: false (or versionFunction: false on the function), the function is still versioned, and the superseded version is deleted on deploy. Deletion starts with the deploy after the one that applies the setting; versions kept before that stay until you delete them, for example with aws lambda delete-function --function-name FUNCTION_NAME:VERSION.
SnapStart examples
Recursive loop detection
Lambda detects and stops recursive invocation loops between supported AWS services. To let a function's loops run, set recursiveLoop: allow; terminate is Lambda's default. The value is case-insensitive.
functions:
hello:
handler: handler.hello
recursiveLoop: allow
VPC configuration
To run functions in a VPC, set vpc with securityGroupIds (up to 5) and subnetIds (up to 16), both required. Under provider, it applies to every function; a function's own securityGroupIds and subnetIds replace the provider's. ipv6AllowedForDualStack (boolean, default false) allows IPv6 outbound traffic on dual-stack subnets; a function that doesn't set it takes the provider value.
provider:
name: aws
vpc:
securityGroupIds:
- sg-0123456789abcdef0
subnetIds:
- subnet-0123456789abcdef0
- subnet-0fedcba9876543210
functions:
users: # uses provider.vpc
handler: handler.users
reports: # its own VPC settings
handler: handler.reports
vpc:
ipv6AllowedForDualStack: true
securityGroupIds:
- sg-0aaaaaaaaaaaaaaaa
subnetIds:
- subnet-0bbbbbbbbbbbbbbbb
public: # no VPC
handler: handler.public
vpc: ~
vpc: ~(null) on a function keeps it out of the provider VPC. The schema accepts only an object for a function'svpc, so use~rather thanfalse.- Functions with
capacityProvidernever get a VPC configuration of their own; the capacity provider sets their networking. - To create network interfaces, a function in a VPC needs the AWS managed policy
AWSLambdaVPCAccessExecutionRole. The Framework attaches it to the execution roles it creates. A role you supply throughprovider.iam.roleor a function'sroleisn't changed: add the policy to itsManagedPolicyArns. - A function in a VPC reaches the internet, and AWS services without a VPC endpoint, only through a NAT gateway: place the NAT gateway in a public subnet, and route internet-bound traffic from the function's private subnets to it. See Enable internet access for VPC-connected Lambda functions and VPC endpoints.
Environment variables
environment sets environment variables on a function. provider.environment sets them for every function, and the two are merged key by key: a function gets every provider variable, and its own value wins for a key both set. MCP servers, agents, sandboxes and web apps inherit provider.environment the same way.
provider:
name: aws
environment:
SYSTEM_NAME: mySystem
TABLE_NAME: tableName1
functions:
hello: # SYSTEM_NAME=mySystem, TABLE_NAME=tableName1
handler: handler.hello
users: # SYSTEM_NAME=mySystem, TABLE_NAME=tableName2
handler: handler.users
environment:
TABLE_NAME: tableName2
Variable names must match ^[A-Za-z_][a-zA-Z0-9_]*$. Values are strings or CloudFormation intrinsics. To copy a value from your machine's environment at deploy time, use an environment variable reference such as ${env:TABLE_NAME}. To encrypt the values with your own key, see KMS keys.
Tags
tags adds tags to a function. provider.tags tags every function, and the two are merged key by key, with the function's value winning:
provider:
name: aws
tags:
team: payments
environment: production
functions:
hello: # team=payments, environment=production
handler: handler.hello
users: # team=accounts, environment=production
handler: handler.users
tags:
team: accounts
Lambda layers
layers attaches Lambda layers to a function, as a list of layer version ARNs (Lambda allows at most 5 per function):
functions:
hello:
handler: handler.hello
layers:
- arn:aws:lambda:us-east-1:123456789012:layer:shared-utils:3
provider.layers sets layers for every function. A function's own layers replaces provider.layers for that function; the two lists are not merged. To publish layers from the same service and reference them, see AWS Lambda layers.
Log group resources
The Framework creates a CloudWatch Logs log group named /aws/lambda/<function name> for each function, so serverless remove deletes it with the stack and the execution role can be scoped to it. It creates none for a function when:
- the function sets
disableLogs: true, or logs.logGroupis set on the function, orprovider.logs.lambda.logGroupis set; that log group is yours to manage.
logRetentionInDays on a function, or provider.logRetentionInDays for every function, sets the retention. Allowed values are the CloudWatch Logs retention periods: 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 2192, 2557, 2922, 3288 and 3653 days. Without it, the log group keeps logs indefinitely.
A CloudWatch Logs account-level retention policy that covers the log group decides its retention instead of logRetentionInDays, whether the policy's period is shorter or longer, and also applies when logRetentionInDays isn't set. serverless deploy still sets logRetentionInDays on the log group without an error when a policy exists, so check for one with aws logs describe-account-policies --policy-type RETENTION_POLICY, run with the credentials and --region of the deploy. A new or changed policy takes effect 24 hours after you save it.
logDataProtectionPolicy on a function, or under provider, sets the log group's data protection policy; Name, Version and Statement are required.
functions:
quiet:
handler: handler.quiet
disableLogs: true
audited:
handler: handler.audited
logRetentionInDays: 14
logDataProtectionPolicy:
Name: data-protection-policy
Version: '2021-06-01'
Statement:
- Sid: audit-policy
DataIdentifier:
- arn:aws:dataprotection::aws:data-identifier/EmailAddress
Operation:
Audit:
FindingsDestination: {}
- Sid: redact-policy
DataIdentifier:
- arn:aws:dataprotection::aws:data-identifier/EmailAddress
Operation:
Deidentify:
MaskConfig: {}
Log format and log levels
A function's logs object, or provider.logs.lambda for every function, sets Lambda's advanced logging controls. Each key set on the function wins over the same key under provider.logs.lambda.
| Key | Allowed values | Notes |
|---|---|---|
logFormat | JSON, Text | Lambda's default is Text. |
applicationLogLevel | TRACE, DEBUG, INFO, WARN, ERROR, FATAL, any case | Applied only when the effective logFormat is JSON. |
systemLogLevel | DEBUG, INFO, WARN, any case | Applied only when the effective logFormat is JSON. |
logGroup | An existing log group name | The Framework then creates no log group for the function. |
logGroupClass | standard, infrequent_access, any case | See Infrequent Access log class. |
functions:
hello:
handler: handler.hello
logs:
logFormat: JSON
applicationLogLevel: INFO
systemLogLevel: WARN
Infrequent Access log class
logs.logGroupClass selects the CloudWatch Logs log group class: standard (default) or infrequent_access, in any case. Infrequent Access costs less per GB ingested and suits logs used for storage and on-demand troubleshooting rather than real-time queries or alarms. Set it on a function, or under provider.logs.lambda for every function; a function's value wins, so a function can opt back into standard.
provider:
name: aws
logs:
lambda:
logGroupClass: infrequent_access
functions:
archived:
handler: handler.archived # infrequent_access from provider
live:
handler: handler.live
logs:
logGroupClass: standard
For a function with infrequent_access, the Framework:
- keeps creating the standard log group
/aws/lambda/<function name>, so history there is preserved when you migrate an existing service; - creates a second log group
/aws/lambda/<function name>-iawith the Infrequent Access class andDeletionPolicy: Retain, so its data survivesserverless remove; - points the function's logging configuration at the
-ialog group.
Behaviour to plan for:
serverless logs -f <function>stops with the errorLOGS_INFREQUENT_ACCESS_NOT_SUPPORTEDfor such a function; read its logs with CloudWatch Logs Insights.- AWS doesn't change the class of an existing log group. When you remove
logGroupClassand deploy, the stack stops managing the-ialog group, andDeletionPolicy: Retainkeeps it and its logs in AWS. - Turning
infrequent_accessback on for the same function then fails withResourceAlreadyExistsException, because the retained log group still exists. Delete the retained log group (its history is lost), or import it into the stack, before deploying. logGroupClasscan't be combined withlogs.logGrouporprovider.logs.lambda.logGroup: packaging stops withFUNCTION_LOG_GROUP_CLASS_CUSTOM_LOG_GROUP_CONFLICT. Set the class on that log group yourself.
Review the AWS log class comparison for the CloudWatch Logs features Infrequent Access doesn't offer.
Versioning deployed functions
By default, the Framework publishes a new function version on each deploy that changes the function's code or configuration; a deploy that changes neither keeps the current version. The stack gets a version resource and an output with the latest version for each function, and you can invoke a version by its qualified ARN, for example arn:aws:lambda:us-east-1:123456789012:function:my-service-dev-hello:3.
To stop publishing versions for every function, set provider.versionFunctions: false. To override the provider setting for one function, set versionFunction (singular) on it:
provider:
name: aws
versionFunctions: false
functions:
hello:
handler: handler.hello
versionFunction: true
- Functions with
snapStart,provisionedConcurrencyordurableConfigare always versioned.durableConfigwithversionFunction: falsestops packaging with an error. - Superseded versions are kept: the Framework can't tell whether an older version is still invoked. Remove them with the
prunecommand orcustom.prune.automatic, which keep the number of versions you choose and every version an alias points to. - The exception is a
snapStartorprovisionedConcurrencyfunction with versioning turned off: it is still versioned, and its superseded version is deleted on deploy. For the snapshot cost of retained SnapStart versions, see Cost of retained versions.
Dead letter queue (DLQ)
Lambda retries failed asynchronous invocations and can then send the event to a dead-letter queue. A function's onError sets that target to an existing SNS topic:
functions:
hello:
handler: handler.hello
onError: arn:aws:sns:us-east-1:123456789012:failed-events
- A plain-string
onErrormust be an SNS topic ARN. A CloudFormation intrinsic (Ref,Fn::GetAtt,Fn::ImportValue,Fn::Join,Fn::Suband others) is passed through as it is. - For a plain-string ARN, the Framework adds
sns:Publishon the topic to the execution role it creates. For an intrinsic, the shared role gets no permission, so addsns:Publishyourself; per-function roles get it in both cases. A role you supply is never changed. - To send failed events to an SQS queue, use
destinations.onFailure, which accepts SQS queues.
KMS keys
Lambda encrypts environment variables at rest. To use your own AWS KMS key, set kmsKeyArn under provider for every function, or on one function, which overrides the provider value:
provider:
name: aws
kmsKeyArn: arn:aws:kms:us-east-1:123456789012:key/11111111-2222-3333-4444-555555555555
environment:
TABLE_NAME: tableName1
functions:
hello: # uses its own key
handler: handler.hello
kmsKeyArn: arn:aws:kms:us-east-1:123456789012:key/66666666-7777-8888-9999-000000000000
goodbye: # uses the provider key
handler: handler.goodbye
When kmsKeyArn is a plain-string ARN, the Framework adds kms:Decrypt on the key to the execution role it creates. For a CloudFormation intrinsic, or a role you supply, add the permission yourself. To keep secrets out of environment variables, see AWS's guidance on securing environment variables.
AWS X-Ray tracing
provider.tracing.lambda turns on AWS X-Ray tracing for every function. Both it and a function's tracing accept Active, PassThrough or a boolean, where true means Active. A function's Active, PassThrough or true overrides the provider setting, and its false keeps the provider setting. To stop Lambda from sampling one function's requests while the provider setting is on, set that function's tracing to PassThrough:
provider:
name: aws
tracing:
lambda: true
functions:
hello:
handler: handler.hello
tracing: PassThrough
When tracing is on, the Framework adds xray:PutTraceSegments and xray:PutTelemetryRecords to the execution role it creates; a role you supply needs them too. For API Gateway tracing, see provider.tracing.apiGateway in the REST API events page.
Asynchronous invocation
These settings apply when a function is invoked asynchronously, for example by Amazon S3, Amazon SNS or EventBridge.
Destinations
destinations sends the result of an asynchronous invocation to a destination: onSuccess and onFailure each take a target.
- A string that starts with
arn:is the ARN of a Lambda function, SQS queue, SNS topic or EventBridge event bus. - Any other string is the key of a function in this service.
- The object form takes
arnandtype(function,sns,sqsoreventBus); both are required.arntakes a CloudFormation intrinsic (Ref,Fn::GetAtt,Fn::ImportValue,Fn::Join,Fn::Sub,Fn::Base64orFn::ToJsonString), andtypetells the Framework which permission to add. For a plain ARN, use the string form.
functions:
asyncHello:
handler: handler.asyncHello
destinations:
onSuccess: otherFunctionInService
onFailure: arn:aws:sns:us-east-1:123456789012:failed-events
asyncGoodbye:
handler: handler.asyncGoodbye
destinations:
onFailure:
type: sqs
arn:
Fn::GetAtt: [FailedEventsQueue, Arn]
The Framework adds the permission to reach the target (lambda:InvokeFunction, sqs:SendMessage, sns:Publish or events:PutEvents) to the execution role it creates. A role you supply through provider.iam.role or a function's role isn't changed.
Maximum event age and maximum retry attempts
maximumEventAge (seconds, 60 to 21600) is how long Lambda keeps an event in the asynchronous queue. maximumRetryAttempts (0 to 2) is how many times Lambda retries after an error.
functions:
asyncHello:
handler: handler.asyncHello
maximumEventAge: 7200
maximumRetryAttempts: 1
File system configuration
fileSystemConfig mounts a file system in the function: Amazon EFS or Amazon S3 Files. It takes:
arn(required): the ARN of an existing EFS or S3 Files access point, or a CloudFormationFn::GetAtt,Fn::JoinorFn::ImportValue.localMountPath(required): where to mount it, matching/mnt/<name>.type:efsors3files. The Framework detects it from a plain-string ARN; a CloudFormation reference is treated asefsunless you settype: s3files.
The function needs a VPC (its own vpc or provider.vpc): without one, packaging stops with LAMBDA_FILE_SYSTEM_CONFIG_MISSING_VPC. fileSystemConfig can't be combined with capacityProvider.
functions:
efsReader:
handler: handler.efsReader
fileSystemConfig:
localMountPath: /mnt/data
arn: arn:aws:elasticfilesystem:us-east-1:123456789012:access-point/fsap-0d0d0d0d0d0d0d0d0
vpc:
securityGroupIds:
- sg-0123456789abcdef0
subnetIds:
- subnet-0123456789abcdef0
s3Reader:
handler: handler.s3Reader
fileSystemConfig:
localMountPath: /mnt/s3data
arn: !GetAtt MyS3FilesAccessPoint.AccessPointArn
type: s3files
vpc:
securityGroupIds:
- sg-0123456789abcdef0
subnetIds:
- subnet-0123456789abcdef0
The Framework adds the mount permissions to the execution role it creates: elasticfilesystem:ClientMount and elasticfilesystem:ClientWrite for EFS, s3files:ClientMount and s3files:ClientWrite for S3 Files. A role you supply needs them too. For the best S3 Files read performance on functions with 512 MB or more memory, also grant s3:GetObject and s3:GetObjectVersion on the bucket through provider.iam.role.statements.
Ephemeral storage
Lambda gives each function 512 MB of ephemeral storage in /tmp. To change it, set ephemeralStorageSize in MB, from 512 to 10240, or up to 32768 for GPU functions:
functions:
imageProcessor:
handler: handler.imageProcessor
ephemeralStorageSize: 1024
Tenant isolation
Lambda's tenant isolation mode runs separate execution environments for each tenant of a multi-tenant application. Set tenancy.mode to per_tenant (any case):
functions:
multiTenantFunction:
handler: handler.handler
tenancy:
mode: per_tenant
Lambda reads the tenant ID from the X-Amz-Tenant-Id header of each invocation. AWS restricts mapping that header in HTTP APIs, so pass it through a REST API (http event) with a request parameter mapping. X-Amz-Tenant-Id is required: false, because API Gateway fills it from the mapping:
functions:
restApiFunction:
handler: handler.handler
tenancy:
mode: per_tenant
events:
- http:
path: /api/resource
method: get
request:
parameters:
headers:
'My-Tenant-Id': true # the client sends this header
'X-Amz-Tenant-Id':
required: false
mappedValue: 'method.request.header.My-Tenant-Id'
mappedValue can name any API Gateway mapping source: headers, query strings, path parameters or context variables. To take the tenant ID from a Lambda authorizer, return it in the authorizer's context and map context.authorizer.tenantId:
functions:
authorizedFunction:
handler: handler.handler
tenancy:
mode: per_tenant
events:
- http:
path: /api/resource
method: get
authorizer:
name: tenantAuthorizer
resultTtlInSeconds: 0
identitySource: method.request.header.Authorization
request:
parameters:
headers:
'X-Amz-Tenant-Id':
required: false
mappedValue: 'context.authorizer.tenantId'
tenantAuthorizer:
handler: authorizer.handler
// authorizer.mjs
export const handler = async (event) => {
const tenantId = getTenantId(event.authorizationToken) // your token parsing
return {
principalId: 'user123',
policyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: 'execute-api:Invoke',
Effect: 'Allow',
Resource: event.methodArn,
},
],
},
context: { tenantId },
}
}
See Lambda authorizer output for the authorizer response format.
CloudFormation condition and dependencies
A function's condition names a CloudFormation condition that decides whether the function resource is created; define the condition under resources.Conditions. dependsOn takes a list of logical IDs the function resource depends on.
functions:
hello:
handler: handler.hello
condition: IsProduction
dependsOn:
- UsersTable
resources:
Conditions:
IsProduction:
Fn::Equals: ['${sls:stage}', 'prod']
Other function settings
These function keys are documented with the feature they belong to:
events: the event sources that invoke the function.roleandiam: a custom execution role, or a per-function IAM role.package: per-function packaging.build:falseto exclude the function from the esbuild build.capacityProvider: run the function on Lambda Managed Instances.httpApi.payload: the default payload format of the function's HTTP API events.awsKmsKeyArn: deprecated; usekmsKeyArn.
Lambda hashing algorithm migration
This section applies only to a service that still sets provider.lambdaHashingVersion: 20200924. The property is deprecated, and every package or deploy with that value prints a deprecation warning. Without it, the Framework computes version hashes with the current algorithm. Migrating changes every function's version hash, so plan two deploys per stage:
- Run
serverless deploy --enforce-hash-update. The flag sets a temporary description on every function, which forces a new version with the new hash. - Remove
provider.lambdaHashingVersionfromserverless.yml. - Run
serverless deploywithout the flag. The original descriptions come back.
This creates two extra versions per function. To avoid them, migrate in a deploy that changes every function's code anyway (for example a dependency upgrade, or a file added to every artifact), with provider.lambdaHashingVersion removed; or, for a stage you can recreate, run serverless remove, remove the property, and deploy again.
Related pages
- Events: connect functions to AWS event sources.
- IAM permissions for functions: execution roles and the permissions the Framework adds.
- Packaging and Building: what goes into a function's artifact.
- serverless.yml reference: every function key in one file.