Amazon Aws Lambda-Dg PDF
Amazon Aws Lambda-Dg PDF
Developer Guide
AWS Lambda Developer Guide
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not
Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or
discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may
or may not be affiliated with, connected to, or sponsored by Amazon.
AWS Lambda Developer Guide
Table of Contents
What is AWS Lambda? ........................................................................................................................ 1
When should I use AWS Lambda? ................................................................................................ 1
Are you a first-time user of AWS Lambda? .................................................................................... 1
Getting started .................................................................................................................................. 3
Create a function ....................................................................................................................... 4
Use the designer ................................................................................................................ 4
Invoke the Lambda function ................................................................................................ 4
Clean up ........................................................................................................................... 6
Code editor ............................................................................................................................... 8
Working with files and folders ............................................................................................. 8
Working with code ........................................................................................................... 10
Working in fullscreen mode ............................................................................................... 13
Working with preferences .................................................................................................. 13
AWS CLI .................................................................................................................................. 14
Prerequisites .................................................................................................................... 14
Create the execution role .................................................................................................. 14
Create the function .......................................................................................................... 15
List the Lambda functions in your account .......................................................................... 17
Retrieve a Lambda function ............................................................................................... 18
Clean up ......................................................................................................................... 18
Concepts ................................................................................................................................. 20
Function .......................................................................................................................... 20
Runtime .......................................................................................................................... 20
Event .............................................................................................................................. 20
Concurrency ..................................................................................................................... 21
Trigger ............................................................................................................................ 21
Features .................................................................................................................................. 22
Programming model ......................................................................................................... 22
Deployment package ........................................................................................................ 24
Layers ............................................................................................................................. 24
Scaling ............................................................................................................................ 24
Concurrency controls ........................................................................................................ 25
Asynchronous invocation ................................................................................................... 27
Event source mappings ..................................................................................................... 28
Destinations ..................................................................................................................... 29
Function blueprints ........................................................................................................... 30
Application templates ....................................................................................................... 31
Tools ....................................................................................................................................... 32
AWS Command Line Interface ............................................................................................ 32
AWS Serverless Application Model ...................................................................................... 32
SAM CLI .......................................................................................................................... 32
Code authoring tools ........................................................................................................ 32
Limits ..................................................................................................................................... 34
Permissions ..................................................................................................................................... 36
Execution role .......................................................................................................................... 37
Creating an execution role in the IAM console ...................................................................... 38
Managing roles with the IAM API ....................................................................................... 38
Managed policies for Lambda features ................................................................................ 39
Resource-based policies ............................................................................................................. 41
Granting function access to AWS services ............................................................................ 42
Granting function access to other accounts .......................................................................... 43
Granting layer access to other accounts .............................................................................. 44
Cleaning up resource-based policies .................................................................................... 44
User policies ............................................................................................................................ 46
iii
AWS Lambda Developer Guide
iv
AWS Lambda Developer Guide
v
AWS Lambda Developer Guide
vi
AWS Lambda Developer Guide
vii
AWS Lambda Developer Guide
viii
AWS Lambda Developer Guide
ix
AWS Lambda Developer Guide
x
AWS Lambda Developer Guide
xi
AWS Lambda Developer Guide
When should I use AWS Lambda?
You can use AWS Lambda to run your code in response to events, such as changes to data in an Amazon
S3 bucket or an Amazon DynamoDB table; to run your code in response to HTTP requests using Amazon
API Gateway; or invoke your code using API calls made using AWS SDKs. With these capabilities, you
can use Lambda to easily build data processing triggers for AWS services like Amazon S3 and Amazon
DynamoDB, process streaming data stored in Kinesis, or create your own back end that operates at AWS
scale, performance, and security.
You can also build serverless applications composed of functions that are triggered by events and
automatically deploy them using CodePipeline and AWS CodeBuild. For more information, see AWS
Lambda applications (p. 145).
When using AWS Lambda, you are responsible only for your code. AWS Lambda manages the compute
fleet that offers a balance of memory, CPU, network, and other resources. This is in exchange for
flexibility, which means you cannot log in to compute instances, or customize the operating system on
provided runtimes. These constraints enable AWS Lambda to perform operational and administrative
activities on your behalf, including provisioning capacity, monitoring fleet health, applying security
patches, deploying your code, and monitoring and logging your Lambda functions.
If you need to manage your own compute resources, Amazon Web Services also offers other compute
services to meet your needs.
• Amazon Elastic Compute Cloud (Amazon EC2) service offers flexibility and a wide range of EC2
instance types to choose from. It gives you the option to customize operating systems, network and
security settings, and the entire software stack, but you are responsible for provisioning capacity,
monitoring fleet health and performance, and using Availability Zones for fault tolerance.
• Elastic Beanstalk offers an easy-to-use service for deploying and scaling applications onto Amazon EC2
in which you retain ownership and full control over the underlying EC2 instances.
Lambda is a highly available service. For more information, see the AWS Lambda service level agreement.
1
AWS Lambda Developer Guide
Are you a first-time user of AWS Lambda?
1. Read the product overview and watch the introductory video to understand sample use cases.
These resources are available on the AWS Lambda webpage.
2. Try the console-based getting started exercise. The exercise provides instructions for you to create
and test your first Lambda function using the console. You also learn about the programming model
and other Lambda concepts. For more information, see Getting started with AWS Lambda (p. 3).
3. Read the deploying applications with AWS Lambda (p. 145) section of this guide. This section
introduces various AWS Lambda components you work with to create an end-to-end experience.
Beyond the Getting Started exercise, you can explore the various use cases, each of which is provided
with a tutorial that walks you through an example scenario. Depending on your application needs (for
example, whether you want event driven Lambda function invocation or on-demand invocation), you
can follow specific tutorials that meet your specific needs. For more information, see Using AWS Lambda
with other services (p. 166).
2
AWS Lambda Developer Guide
You can author functions in the Lambda console—or with an IDE toolkit, command line tools, or SDKs.
The Lambda console provides a code editor (p. 8) for noncompiled languages that lets you modify
and test code quickly. The AWS CLI (p. 14) gives you direct access to the Lambda API for advanced
configuration and automation use cases.
Topics
• Create a Lambda function with the console (p. 4)
• Creating functions using the AWS Lambda console editor (p. 8)
• Using AWS Lambda with the AWS Command Line Interface (p. 14)
• AWS Lambda concepts (p. 20)
• AWS Lambda features (p. 22)
• Tools for working with AWS Lambda (p. 32)
• AWS Lambda limits (p. 34)
3
AWS Lambda Developer Guide
Create a function
Lambda creates a [Link] function and an execution role that grants the function permission to upload
logs. Lambda assumes the execution role when you invoke your function, and uses it to create credentials
for the AWS SDK and to read data from event sources.
Choose my-function in the designer to return to the function's code and configuration. For scripting
languages, Lambda includes sample code that returns a success response. You can edit your function
code with the embedded AWS Cloud9 editor as long as your source code doesn't exceed the 3 MB limit.
4
AWS Lambda Developer Guide
Invoke the Lambda function
To invoke a function
{
"key3": "value3",
"key2": "value2",
"key1": "value1"
}
You can change key and values in the sample JSON, but don't change the event structure. If you do
change any keys and values, you must update the sample code accordingly.
3. Choose Create and then choose Test. Each user can create up to 10 test events per function. Those
test events are not available to other users.
4. AWS Lambda executes your function on your behalf. The handler in your Lambda function receives
and then processes the sample event.
5. Upon successful execution, view results in the console.
• The Execution result section shows the execution status as succeeded and also shows the
function execution results, returned by the return statement.
• The Summary section shows the key information reported in the Log output section (the REPORT
line in the execution log).
• The Log output section shows the log AWS Lambda generates for each execution. These are the
logs written to CloudWatch by the Lambda function. The AWS Lambda console shows these logs
for your convenience.
Note that the Click here link shows logs in the CloudWatch console. The function then adds logs to
Amazon CloudWatch in the log group that corresponds to the Lambda function.
6. Run the Lambda function a few times to gather some metrics that you can view in the next step.
7. Choose Monitoring. This page shows graphs for the metrics that Lambda sends to CloudWatch.
5
AWS Lambda Developer Guide
Clean up
For more information on these graphs, see Monitoring functions in the AWS Lambda
console (p. 477).
Clean up
If you are done working with the example function, delete it. You can also delete the execution role that
the console created, and the log group that stores the function's logs.
6
AWS Lambda Developer Guide
Clean up
1. Open the Roles page of the AWS Identity and Access Management console.
2. Choose the function's role (my-function-role-31exxmpl)
3. Choose Delete role.
4. Choose Yes, delete.
You can automate the creation and cleanup of functions, roles, and log groups with AWS
CloudFormation and the AWS CLI. For fully functional sample applications, see Lambda sample
applications (p. 318).
7
AWS Lambda Developer Guide
Code editor
The code editor includes the menu bar, windows, and the editor pane.
For a list of what the commands do, see the Menu commands reference in the AWS Cloud9 User Guide.
Note that some of the commands listed in that reference are not available in the code editor.
Topics
• Working with files and folders (p. 8)
• Working with code (p. 10)
• Working in fullscreen mode (p. 13)
• Working with preferences (p. 13)
To show or hide the Environment window, choose the Environment button. If the Environment button
is not visible, choose Window, Environment on the menu bar.
8
AWS Lambda Developer Guide
Working with files and folders
To open a single file and show its contents in the editor pane, double-click the file in the Environment
window.
To open multiple files and show their contents in the editor pane, choose the files in the Environment
window. Right-click the selection, and then choose Open.
• In the Environment window, right-click the folder where you want the new file to go, and then choose
New File. Type the file's name and extension, and then press Enter.
• Choose File, New File on the menu bar. When you're ready to save the file, choose File, Save or File,
Save As on the menu bar. Then use the Save As dialog box that displays to name the file and choose
where to save it.
• In the tab buttons bar in the editor pane, choose the + button, and then choose New File. When you're
ready to save the file, choose File, Save or File, Save As on the menu bar. Then use the Save As dialog
box that displays to name the file and choose where to save it.
To create a new folder, right-click the folder in the Environment window where you want the new
folder to go, and then choose New Folder. Type the folder's name, and then press Enter.
To save a file, with the file open and its contents visible in the editor pane, choose File, Save on the
menu bar.
To rename a file or folder, right-click the file or folder in the Environment window. Type the
replacement name, and then press Enter.
To delete files or folders, choose the files or folders in the Environment window. Right-click the
selection, and then choose Delete. Then confirm the deletion by choosing Yes (for a single selection) or
Yes to All.
To cut, copy, paste, or duplicate files or folders, choose the files or folders in the Environment window.
Right-click the selection, and then choose Cut, Copy, Paste, or Duplicate, respectively.
To collapse folders, choose the gear icon in the Environment window, and then choose Collapse All
Folders.
9
AWS Lambda Developer Guide
Working with code
To show or hide hidden files, choose the gear icon in the Environment window, and then choose Show
Hidden Files.
10
AWS Lambda Developer Guide
Working with code
To close multiple open files, choose the drop-down menu in the tab buttons bar, and then choose Close
All Tabs in All Panes or Close All But Current Tab as needed.
To create a new file, choose the + button in the tab buttons bar, and then choose New File. When you're
ready to save the file, choose File, Save or File, Save As on the menu bar. Then use the Save As dialog
box that displays to name the file and choose where to save it.
To move quickly to a line in the active file, choose the line selector, type the line number to go to, and
then press Enter.
11
AWS Lambda Developer Guide
Working with code
To change the code color scheme in the active file, choose the code color scheme selector, and then
choose the new code color scheme.
To change in the active file whether soft tabs or spaces are used, the tab size, or whether to convert
to spaces or tabs, choose the spaces and tabs selector, and then choose the new settings.
To change for all files whether to show or hide invisible characters or the gutter, auto-pair brackets
or quotes, wrap lines, or the font size, choose the gear icon, and then choose the new settings.
12
AWS Lambda Developer Guide
Working in fullscreen mode
To expand the code editor to the edges of the web browser window, choose the Toggle fullscreen
button in the menu bar.
To shrink the code editor to its original size, choose the Toggle fullscreen button again.
In fullscreen mode, additional options are displayed on the menu bar: Save and Test. Choosing Save
saves the function code. Choosing Test or Configure Events enables you to create or edit the function's
test events.
To change code editor settings, choose the Preferences gear icon in the menu bar.
For a list of what the settings do, see the following references in the AWS Cloud9 User Guide.
Note that some of the settings listed in those references are not available in the code editor.
13
AWS Lambda Developer Guide
AWS CLI
In this tutorial, you manage and invoke Lambda functions with the AWS CLI.
Prerequisites
This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda
console. If you haven't already, follow the instructions in Getting started with AWS Lambda (p. 3) to
create your first Lambda function.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate:
For long commands, an escape character (\) is used to split a command over multiple lines.
On Linux and macOS, use your preferred shell and package manager. On Windows 10, you can install the
Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
This tutorial uses the AWS Command Line Interface (AWS CLI) to call service API operations. To install the
AWS CLI, see Installing the AWS CLI in the AWS Command Line Interface User Guide.
14
AWS Lambda Developer Guide
Create the function
]
}
}
}
The [Link] file is a JSON file in the current directory that defines the trust policy for
the role. This trust policy allows Lambda to use the role's permissions by giving the service principal
[Link] permission to call the AWS Security Token Service AssumeRole action.
Example [Link]
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "[Link]"
},
"Action": "sts:AssumeRole"
}
]
}
You can also specify the trust policy inline. Requirements for escaping quotes in the JSON string vary
depending on your shell.
To add permissions to the role, use the attach-policy-to-role command. Start by adding the
AWSLambdaBasicExecutionRole managed policy.
The AWSLambdaBasicExecutionRole policy has the permissions that the function needs to write logs to
CloudWatch Logs.
Example [Link]
15
AWS Lambda Developer Guide
Create the function
3. Create a Lambda function with the create-function command. Replace the highlighted text in
the role ARN with your account ID.
To get logs for an invocation from the command line, use the --log-type option. The response
includes a LogResult field that contains up to 4 KB of base64-encoded logs from the invocation.
The base64 utility is available on Linux, macOS, and Ubuntu on Windows. For macOS, the command is
base64 -D.
To get full log events from the command line, you can include the log stream name in the output of your
function, as shown in the preceding example. The following example script invokes a function named
my-function and downloads the last five log events.
#!/bin/bash
aws lambda invoke --function-name my-function --payload '{"key": "value"}' out
16
AWS Lambda Developer Guide
List the Lambda functions in your account
The script uses sed to remove quotes from the output file, and sleeps for 15 seconds to allow time for
the logs to be available. The output includes the response from Lambda and the output from the get-
log-events command.
$ ./[Link]
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
{
"events": [
{
"timestamp": 1559763003171,
"message": "START RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf Version:
$LATEST\n",
"ingestionTime": 1559763003309
},
{
"timestamp": 1559763003173,
"message": "2019-06-05T[Link].173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf
\tINFO\tENVIRONMENT VARIABLES\r{\r \"AWS_LAMBDA_FUNCTION_VERSION\": \"$LATEST\",\r ...",
"ingestionTime": 1559763018353
},
{
"timestamp": 1559763003173,
"message": "2019-06-05T[Link].173Z\t4ce9340a-b765-490f-ad8a-02ab3415e2bf
\tINFO\tEVENT\r{\r \"key\": \"value\"\r}\n",
"ingestionTime": 1559763018353
},
{
"timestamp": 1559763003218,
"message": "END RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\n",
"ingestionTime": 1559763018353
},
{
"timestamp": 1559763003218,
"message": "REPORT RequestId: 4ce9340a-b765-490f-ad8a-02ab3415e2bf\tDuration:
26.73 ms\tBilled Duration: 100 ms \tMemory Size: 128 MB\tMax Memory Used: 75 MB\t\n",
"ingestionTime": 1559763018353
}
],
"nextForwardToken": "f/34783877304859518393868359594929986069206639495374241795",
"nextBackwardToken": "b/34783877303811383369537420289090800615709599058929582080"
}
17
AWS Lambda Developer Guide
Retrieve a Lambda function
"Role": "arn:aws:iam::123456789012:role/lambda-ex",
"Handler": "[Link]",
...
},
{
"FunctionName": "random-error",
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:random-error",
"Runtime": "nodejs12.x",
"Role": "arn:aws:iam::123456789012:role/lambda-role",
"Handler": "[Link]",
...
},
...
],
"NextToken": "eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxMH0="
}
In response, Lambda returns a list of up to 10 functions. If there are more functions you can retrieve,
NextToken provides a marker you can use in the next list-functions request. The following list-
functions AWS CLI command is an example that shows the --starting-token parameter.
Clean up
Execute the following delete-function command to delete the my-function function.
18
AWS Lambda Developer Guide
Clean up
Delete the IAM role you created in the IAM console. For information about deleting a role, see Deleting
roles or instance profiles in the IAM User Guide.
19
AWS Lambda Developer Guide
Concepts
Concepts
• Function (p. 20)
• Runtime (p. 20)
• Event (p. 20)
• Concurrency (p. 21)
• Trigger (p. 21)
Function
A function is a resource that you can invoke to run your code in AWS Lambda. A function has code that
processes events, and a runtime that passes requests and responses between Lambda and the function
code. You provide the code, and you can use the provided runtimes or create your own.
For more information, see Managing AWS Lambda functions (p. 57).
Runtime
Lambda runtimes allow functions in different languages to run in the same base execution environment.
You configure your function to use a runtime that matches your programming language. The runtime sits
in between the Lambda service and your function code, relaying invocation events, context information,
and responses between the two. You can use runtimes provided by Lambda, or build your own.
Event
An event is a JSON formatted document that contains data for a function to process. The Lambda
runtime converts the event to an object and passes it to your function code. When you invoke a function,
you determine the structure and contents of the event.
{
"TemperatureK": 281,
"WindKmh": -3,
"HumidityPct": 0.55,
"PressureHPa": 1020
}
When an AWS service invokes your function, the service defines the shape of the event.
{
"Records": [
{
"Sns": {
"Timestamp": "2019-01-02T[Link].000Z",
20
AWS Lambda Developer Guide
Concurrency
"Signature": "tcc6faL2yUC6dgZdmrwh1Y4cGa/ebXEkAi6RibDsvpi+tE/1+82j...65r==",
"MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
"Message": "Hello from SNS!",
...
For details on events from AWS services, see Using AWS Lambda with other services (p. 166).
Concurrency
Concurrency is the number of requests that your function is serving at any given time. When your
function is invoked, Lambda provisions an instance of it to process the event. When the function code
finishes running, it can handle another request. If the function is invoked again while a request is still
being processed, another instance is provisioned, increasing the function's concurrency.
Concurrency is subject to limits at the region level. You can also configure individual functions to limit
their concurrency, or to ensure that they can reach a specific level of concurrency. For more information,
see Managing concurrency for a Lambda function (p. 67).
Trigger
A trigger is a resource or configuration that invokes a Lambda function. This includes AWS services that
can be configured to invoke a function, applications that you develop, and event source mappings. An
event source mapping is a resource in Lambda that reads items from a stream or queue and invokes a
function.
For more information, see Invoking AWS Lambda functions (p. 98) and Using AWS Lambda with other
services (p. 166).
21
AWS Lambda Developer Guide
Features
Features
• Programming model (p. 22)
• Deployment package (p. 24)
• Layers (p. 24)
• Scaling (p. 24)
• Concurrency controls (p. 25)
• Asynchronous invocation (p. 27)
• Event source mappings (p. 28)
• Destinations (p. 29)
• Function blueprints (p. 30)
• Application templates (p. 31)
Programming model
Authoring specifics vary between runtimes, but all runtimes share a common programming model that
defines the interface between your code and the runtime code. You tell the runtime which method to
run by defining a handler in the function configuration, and the runtime runs that method. The runtime
passes in objects to the handler that contain the invocation event and the context, such as the function
name and request ID.
When the handler finishes processing the first event, the runtime sends it another. The function's
class stays in memory, so clients and variables that are declared outside of the handler method in
initialization code can be reused. To save processing time on subsequent events, create reusable
resources like AWS SDK clients during initialization. Once initialized, each instance of your function can
process thousands of requests.
Initialization is billed as part of the duration for the first invocation processed by an instance of your
function. When X-Ray tracing (p. 314) is enabled, the runtime records separate subsegments for
initialization and execution.
22
AWS Lambda Developer Guide
Programming model
Your function also has access to local storage in the /tmp directory. Instances of your function that are
serving requests remain active for a few hours before being recycled.
The runtime captures logging output from your function and sends it to Amazon CloudWatch Logs. In
addition to logging your function's output, the runtime also logs entries when execution starts and ends.
This includes a report log with the request ID, billed duration, initialization duration, and other details. If
your function throws an error, the runtime returns that error to the invoker.
Note
Logging is subject to CloudWatch Logs limits. Log data can be lost due to throttling or, in some
cases, when an instance of your function is stopped.
For a hands-on introduction to the programming model in your preferred programming language, see
the following chapters.
Lambda scales your function by running additional instances of it as demand increases, and by stopping
instances as demand decreases. Unless noted otherwise, incoming requests might be processed out
of order or concurrently. Store your application's state in other services, and don't rely on instances of
your function being long lived. Use local storage and class-level objects to increase performance, but
23
AWS Lambda Developer Guide
Deployment package
keep the size of your deployment package and the amount of data that you transfer onto the execution
environment to a minimum.
Deployment package
Your function's code consists of scripts or compiled programs and their dependencies. When you author
functions in the Lambda console or a toolkit, the client creates a ZIP archive of your code called a
deployment package. The client then sends the package to the Lambda service. When you manage
functions with the Lambda API, command line tools, or SDKs, you create the deployment package. You
also need to create a deployment package manually for compiled languages and to add dependencies to
your function.
Layers
Lambda layers are a distribution mechanism for libraries, custom runtimes, and other function
dependencies. Layers let you manage your in-development function code independently from the
unchanging code and resources that it uses. You can configure your function to use layers that you
create, layers provided by AWS, or layers from other AWS customers.
Scaling
Lambda manages the infrastructure that runs your code, and scales automatically in response to
incoming requests. When your function is invoked more quickly than a single instance of your function
can process events, Lambda scales up by running additional instances. When traffic subsides, inactive
instances are frozen or stopped. You only pay for the time that your function is initializing or processing
events.
24
AWS Lambda Developer Guide
Concurrency controls
For more information, see AWS Lambda function scaling (p. 114).
Concurrency controls
Use concurrency settings to ensure that your production applications are highly available and highly
responsive. To prevent a function from using too much concurrency, and to reserve a portion of your
account's available concurrency for a function, use reserved concurrency. Reserved concurrency splits the
pool of available concurrency into subsets. A function with reserved concurrency only uses concurrency
from its dedicated pool.
25
AWS Lambda Developer Guide
Concurrency controls
To enable functions to scale without fluctuations in latency, use provisioned concurrency. For functions
that take a long time to initialize, or require extremely low latency for all invocations, provisioned
concurrency enables you to pre-initialize instances of your function and keep them running at all times.
Lambda integrates with Application Auto Scaling to support autoscaling for provisioned concurrency
based on utilization.
26
AWS Lambda Developer Guide
Asynchronous invocation
For more information, see Managing concurrency for a Lambda function (p. 67).
Asynchronous invocation
When you invoke a function, you can choose to invoke it synchronously or asynchronously. With
synchronous invocation (p. 99), you wait for the function to process the event and return a response.
With asynchronous invocation, Lambda queues the event for processing and returns a response
immediately.
27
AWS Lambda Developer Guide
Event source mappings
For asynchronous invocations, Lambda handles retries if the function returns an error or is throttled. To
customize this behavior, you can configure error handling settings on a function, version, or alias. You
can also configure Lambda to send events that failed processing to a dead-letter queue, or to send a
record of any invocation to a destination (p. 29).
28
AWS Lambda Developer Guide
Destinations
Event source mappings maintain a local queue of unprocessed items, and handle retries if the function
returns an error or is throttled. You can configure an event source mapping to customize batching
behavior and error handling, or to send a record of items that fail processing to a destination (p. 29).
For more information, see AWS Lambda event source mappings (p. 109).
Destinations
A destination is an AWS resource that receives invocation records for a function. For asynchronous
invocation (p. 27), you can configure Lambda to send invocation records to a queue, topic, function,
or event bus. You can configure separate destinations for successful invocations and events that failed
processing. The invocation record contains details about the event, the function's response, and the
reason that the record was sent.
29
AWS Lambda Developer Guide
Function blueprints
For event source mappings (p. 28) that read from streams, you can configure Lambda to send a record
of batches that failed processing to a queue or topic. A failure record for an event source mapping
contains metadata about the batch, and it points to the items in the stream.
For more information, see Configuring destinations for asynchronous invocation (p. 103) and the error
handling sections of Using AWS Lambda with Amazon DynamoDB (p. 223) and Using AWS Lambda
with Amazon Kinesis (p. 257).
Function blueprints
When you create a function in the Lambda console, you can choose to start from scratch, use a blueprint,
or deploy an application from the AWS Serverless Application Repository. A blueprint provides sample
code that shows how to use Lambda with an AWS service or a popular third-party application. Blueprints
include sample code and function configuration presets for [Link] and Python runtimes.
Blueprints are provided for use under the Creative Commons Zero license. They are only available in the
Lambda console.
30
AWS Lambda Developer Guide
Application templates
Application templates
You can use the Lambda console to create an application with a continuous delivery pipeline. Application
templates in the Lambda console include code for one or more functions, an application template that
defines functions and supporting AWS resources, and an infrastructure template that defines an AWS
CodePipeline pipeline. The pipeline has build and deploy stages that run every time you push changes to
the included Git repository.
Application templates are provided for use under the MIT No Attribution license. They are only available
in the Lambda console.
For more information, see Creating an application with continuous delivery in the Lambda
console (p. 149).
31
AWS Lambda Developer Guide
Tools
Tools
• AWS Command Line Interface (p. 32)
• AWS Serverless Application Model (p. 32)
• SAM CLI (p. 32)
• Code authoring tools (p. 32)
To set up the AWS CLI, see the following topics in the AWS Command Line Interface User Guide.
To verify that the AWS CLI is configured correctly, run the list-functions command to see a list of
your Lambda functions in the current region.
For more information about AWS SAM templates, see AWS SAM template basics in the AWS Serverless
Application Model Developer Guide.
SAM CLI
The AWS SAM CLI is a separate command line tool that you can use to manage and test AWS SAM
applications. In addition to commands for uploading artifacts and launching AWS CloudFormation
stacks that are also available in the AWS CLI, the SAM CLI provides additional commands for validating
templates and running applications locally in a Docker container.
To set up the AWS SAM CLI, see Installing the AWS SAM CLI in the AWS Serverless Application Model
Developer Guide.
32
AWS Lambda Developer Guide
Code authoring tools
such as the AWS Lambda console, Eclipse IDE, and Visual Studio IDE. But the available tools and options
depend on the following:
The following table lists languages, and the available tools and options that you can use.
Java • Eclipse, with AWS Toolkit for Eclipse (see Using AWS Lambda with
the AWS Toolkit for Eclipse)
• IntelliJ, with the AWS Toolkit for IntelliJ
• Your own authoring environment
33
AWS Lambda Developer Guide
Limits
For details on concurrency and how Lambda scales your function concurrency in response to traffic, see
AWS Lambda function scaling (p. 114).
The following limits apply to function configuration, deployments, and execution. They cannot be
changed.
Resource Limit
Function burst concurrency (p. 114) 500 - 3000 (varies per region (p. 114))
Invocation frequency per Region (requests per second) 10 x concurrent executions limit
(synchronous (p. 99) – all sources)
256 KB (asynchronous)
34
AWS Lambda Developer Guide
Limits
Resource Limit
3 MB (console editor)
Limits for other services, such as AWS Identity and Access Management, Amazon CloudFront
(Lambda@Edge), and Amazon Virtual Private Cloud, can impact your Lambda functions. For more
information, see AWS service limits and Using AWS Lambda with other services (p. 166).
35
AWS Lambda Developer Guide
A Lambda function also has a policy, called an execution role (p. 37), that grants it permission to
access AWS services and resources. At a minimum, your function needs access to Amazon CloudWatch
Logs for log streaming. If you use AWS X-Ray to trace your function (p. 314), or your function accesses
services with the AWS SDK, you grant it permission to call them in the execution role. Lambda also
uses the execution role to get permission to read from event sources when you use an event source
mapping (p. 109) to trigger your function.
Note
If your function needs network access to a resource like a relational database that isn't
accessible through AWS APIs or the internet, configure it to connect to your VPC (p. 88).
Use resource-based policies (p. 41) to give other accounts and AWS services permission to use your
Lambda resources. Lambda resources include functions, versions, aliases, and layer versions. Each of
these resources has a permissions policy that applies when the resource is accessed, in addition to any
policies that apply to the user. When an AWS service like Amazon S3 calls your Lambda function, the
resource-based policy gives it access.
To manage permissions for users and applications in your accounts, use the managed policies that
Lambda provides (p. 46), or write your own. The Lambda console uses multiple services to get
information about your function's configuration and triggers. You can use the managed policies as-is, or
as a starting point for more restrictive policies.
You can restrict user permissions by the resource an action affects and, in some cases, by additional
conditions. For example, you can specify a pattern for the Amazon Resource Name (ARN) of a function
that requires a user to include their user name in the name of functions that they create. Additionally,
you can add a condition that requires that the user configure functions to use a specific layer to, for
example, pull in logging software. For the resources and conditions that are supported by each action,
see Resources and Conditions (p. 51).
For more information about IAM, see What is IAM? in the IAM User Guide.
Topics
• AWS Lambda execution role (p. 37)
• Using resource-based policies for AWS Lambda (p. 41)
• Identity-based IAM policies for AWS Lambda (p. 46)
• Resources and conditions for Lambda actions (p. 51)
• Using permissions boundaries for AWS Lambda applications (p. 55)
36
AWS Lambda Developer Guide
Execution role
5. Choose a service from the drop-down menu to see permissions related to that service.
37
AWS Lambda Developer Guide
Creating an execution role in the IAM console
You can add or remove permissions from a function's execution role at any time, or configure your
function to use a different role. Add permissions for any services that your function calls with the AWS
SDK, and for services that Lambda uses to enable optional features.
When you add permissions to your function, make an update to its code or configuration as well. This
forces running instances of your function, which have out-of-date credentials, to stop and be replaced.
For detailed instructions, see Creating a role in the IAM User Guide.
38
AWS Lambda Developer Guide
Managed policies for Lambda features
The [Link] file is a JSON file in the current directory that defines the trust policy for
the role. This trust policy allows Lambda to use the role's permissions by giving the service principal
[Link] permission to call the AWS Security Token Service AssumeRole action.
Example [Link]
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "[Link]"
},
"Action": "sts:AssumeRole"
}
]
}
You can also specify the trust policy inline. Requirements for escaping quotes in the JSON string vary
depending on your shell.
To add permissions to the role, use the attach-policy-to-role command. Start by adding the
AWSLambdaBasicExecutionRole managed policy.
For some features, the Lambda console attempts to add missing permissions to your execution role in a
customer managed policy. These policies can become numerous. Add the relevant managed policies to
your execution role before enabling features to avoid creating extra policies.
When you use an event source mapping (p. 109) to invoke your function, Lambda uses the execution
role to read event data. For example, an event source mapping for Amazon Kinesis reads events from a
data stream and sends them to your function in batches. You can use event source mappings with the
following services:
39
AWS Lambda Developer Guide
Managed policies for Lambda features
In addition to the managed policies, the Lambda console provides templates for creating a custom policy
that has the permissions related to additional use cases. When you create a function in the Lambda
console, you can choose to create a new execution role with permissions from one or more templates.
These templates are also applied automatically when you create a function from a blueprint, or when
you configure options that require access to other services. Example templates are available in this
guide's GitHub repository.
40
AWS Lambda Developer Guide
Resource-based policies
For Lambda functions, you can grant an account permission (p. 43) to invoke or manage a function.
You can add multiple statements to grant access to multiple accounts, or let any account invoke your
function. For functions that another AWS service invokes in response to activity in your account, you use
the policy to grant invoke permission to the service (p. 42).
41
AWS Lambda Developer Guide
Granting function access to AWS services
For Lambda layers, you use a resource-based policy on a version of the layer to let other accounts use it.
In addition to policies that grant permission to a single account or all accounts, for layers, you can also
grant permission to all accounts in an organization.
Note
You can only update resource-based policies for Lambda resources within the scope of the
AddPermission (p. 517) and AddLayerVersionPermission (p. 514) API actions. You can't
author policies for your Lambda resources in JSON, or use conditions that don't map to
parameters for those actions.
Resource-based policies apply to a single function, version, alias, or layer version. They grant permission
to one or more services and accounts. For trusted accounts that you want to have access to multiple
resources, or to use API actions that resource-based policies don't support, you can use cross-account
roles (p. 46).
Topics
• Granting function access to AWS services (p. 42)
• Granting function access to other accounts (p. 43)
• Granting layer access to other accounts (p. 44)
• Cleaning up resource-based policies (p. 44)
Add a statement with the add-permission command. The simplest resource-based policy statement
allows a service to invoke a function. The following command grants Amazon SNS permission to invoke a
function named my-function.
This lets Amazon SNS invoke the function, but it doesn't restrict the Amazon SNS topic that triggers
the invocation. To ensure that your function is only invoked by a specific resource, specify the Amazon
Resource Name (ARN) of the resource with the source-arn option. The following command only allows
Amazon SNS to invoke the function for subscriptions to a topic named my-topic.
Some services can invoke functions in other accounts. If you specify a source ARN that has your account
ID in it, that isn't an issue. For Amazon S3, however, the source is a bucket whose ARN doesn't have an
account ID in it. It's possible that you could delete the bucket and another account could create a bucket
42
AWS Lambda Developer Guide
Granting function access to other accounts
with the same name. Use the account-id option to ensure that only resources in your account can
invoke the function.
The resource-based policy grants permission for the other account to access the function, but doesn't
allow users in that account to exceed their permissions. Users in the other account must have the
corresponding user permissions (p. 46) to use the Lambda API.
To limit access to a user, group, or role in another account, specify the full ARN of the identity as the
principal. For example, arn:aws:iam::123456789012:user/developer.
The alias (p. 79) limits which version the other account can invoke. It requires the other account to
include the alias in the function ARN.
You can then update the alias to point to new versions as needed. When you update the alias, the other
account doesn't need to change its code to use the new version, and it only has permission to invoke the
version that you choose.
You can grant cross-account access for most API actions that operate on an existing function (p. 52).
For example, you could grant access to lambda:ListAliases to let an account get a list of aliases, or
lambda:GetFunction to let them download your function code. Add each permission separately, or
use lambda:* to grant access to all actions for the specified function.
Cross-account APIs
43
AWS Lambda Developer Guide
Granting layer access to other accounts
To grant other accounts permission for multiple functions, or for actions that don't operate on a
function, use roles (p. 46).
Permissions only apply to a single version of a layer. Repeat the procedure each time you create a new
layer version.
To grant permission to all accounts in an organization, use the organization-id option. The following
example grants all accounts in an organization permission to use version 3 of a layer.
To grant permission to all AWS accounts, use * for the principal, and omit the organization ID. For
multiple accounts or organizations, add multiple statements.
44
AWS Lambda Developer Guide
Cleaning up resource-based policies
east-2:123456789012:function:my-function","Condition":{"ArnLike":
{"AWS:SourceArn":"arn:aws:sns:us-east-2:123456789012:lambda*"}}}]} 7c681fc9-b791-4e91-
acdf-eb847fdaa0f0
For versions and aliases, append the version number or alias to the function name.
Use the get-layer-version-policy command to view the permissions on a layer. Use remove-
layer-version-permission to remove statements from the policy.
45
AWS Lambda Developer Guide
User policies
Lambda provides managed policies that grant access to Lambda API actions and, in some cases, access to
other services used to develop and manage Lambda resources. Lambda updates the managed policies as
needed, to ensure that your users have access to new features when they're released.
• AWSLambdaFullAccess – Grants full access to AWS Lambda actions and other services used to develop
and maintain Lambda resources.
• AWSLambdaReadOnlyAccess – Grants read-only access to AWS Lambda resources.
• AWSLambdaRole – Grants permissions to invoke Lambda functions.
Managed policies grant permission to API actions without restricting the functions or layers that a user
can modify. For finer-grained control, you can create your own policies that limit the scope of a user's
permissions.
Sections
• Function development (p. 46)
• Layer development and use (p. 49)
• Cross-account roles (p. 50)
Function development
The following shows an example of a permissions policy with limited scope. It allows a user to create and
manage Lambda functions named with a designated prefix (intern-), and configured with a designated
execution role.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadOnlyPermissions",
"Effect": "Allow",
"Action": [
"lambda:GetAccountSettings",
"lambda:ListFunctions",
"lambda:ListTags",
"lambda:GetEventSourceMapping",
"lambda:ListEventSourceMappings",
"iam:ListRoles"
],
"Resource": "*"
},
{
"Sid": "DevelopFunctions",
"Effect": "Allow",
"NotAction": [
"lambda:AddPermission",
"lambda:PutFunctionConcurrency"
],
46
AWS Lambda Developer Guide
Function development
"Resource": "arn:aws:lambda:*:*:function:intern-*"
},
{
"Sid": "DevelopEventSourceMappings",
"Effect": "Allow",
"Action": [
"lambda:DeleteEventSourceMapping",
"lambda:UpdateEventSourceMapping",
"lambda:CreateEventSourceMapping"
],
"Resource": "*",
"Condition": {
"StringLike": {
"lambda:FunctionArn": "arn:aws:lambda:*:*:function:intern-*"
}
}
},
{
"Sid": "PassExecutionRole",
"Effect": "Allow",
"Action": [
"iam:ListRolePolicies",
"iam:ListAttachedRolePolicies",
"iam:GetRole",
"iam:GetRolePolicy",
"iam:PassRole",
"iam:SimulatePrincipalPolicy"
],
"Resource": "arn:aws:iam::*:role/intern-lambda-execution-role"
},
{
"Sid": "ViewExecutionRolePolicies",
"Effect": "Allow",
"Action": [
"iam:GetPolicy",
"iam:GetPolicyVersion"
],
"Resource": "arn:aws:iam::aws:policy/*"
},
{
"Sid": "ViewLogs",
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:log-group:/aws/lambda/intern-*"
}
]
}
The permissions in the policy are organized into statements based on the resources and
conditions (p. 51) that they support.
• ReadOnlyPermissions – The Lambda console uses these permissions when you browse and view
functions. They don't support resource patterns or conditions.
"Action": [
"lambda:GetAccountSettings",
"lambda:ListFunctions",
"lambda:ListTags",
"lambda:GetEventSourceMapping",
"lambda:ListEventSourceMappings",
"iam:ListRoles"
47
AWS Lambda Developer Guide
Function development
],
"Resource": "*"
• DevelopFunctions – Use any Lambda action that operates on functions prefixed with intern-,
except AddPermission and PutFunctionConcurrency. AddPermission modifies the resource-
based policy (p. 41) on the function and can have security implications. PutFunctionConcurrency
reserves scaling capacity for a function and can take capacity away from other functions.
"NotAction": [
"lambda:AddPermission",
"lambda:PutFunctionConcurrency"
],
"Resource": "arn:aws:lambda:*:*:function:intern-*"
"Action": [
"lambda:DeleteEventSourceMapping",
"lambda:UpdateEventSourceMapping",
"lambda:CreateEventSourceMapping"
],
"Resource": "*",
"Condition": {
"StringLike": {
"lambda:FunctionArn": "arn:aws:lambda:*:*:function:intern-*"
}
}
"Action": [
"iam:ListRolePolicies",
"iam:ListAttachedRolePolicies",
"iam:GetRole",
"iam:GetRolePolicy",
"iam:PassRole",
"iam:SimulatePrincipalPolicy"
],
"Resource": "arn:aws:iam::*:role/intern-lambda-execution-role"
"Action": [
"iam:GetPolicy",
"iam:GetPolicyVersion"
],
"Resource": "arn:aws:iam::aws:policy/*"
• ViewLogs – Use CloudWatch Logs to view logs for functions that are prefixed with intern-.
48
AWS Lambda Developer Guide
Layer development and use
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:log-group:/aws/lambda/intern-*"
This policy allows a user to get started with Lambda, without putting other users' resources at risk. It
doesn't allow a user to configure a function to be triggered by or call other AWS services, which requires
broader IAM permissions. It also doesn't include permission to services that don't support limited-scope
policies, like CloudWatch and X-Ray. Use the read-only policies for these services to give the user access
to metrics and trace data.
When you configure triggers for your function, you need access to use the AWS service that invokes your
function. For example, to configure an Amazon S3 trigger, you need permission to Amazon S3 actions
to manage bucket notifications. Many of these permissions are included in the AWSLambdaFullAccess
managed policy. Example policies are available in this guide's GitHub repository.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublishLayers",
"Effect": "Allow",
"Action": [
"lambda:PublishLayerVersion"
],
"Resource": "arn:aws:lambda:*:*:layer:test-*"
},
{
"Sid": "ManageLayerVersions",
"Effect": "Allow",
"Action": [
"lambda:GetLayerVersion",
"lambda:DeleteLayerVersion"
],
"Resource": "arn:aws:lambda:*:*:layer:test-*:*"
}
]
}
You can also enforce layer use during function creation and configuration with the lambda:Layer
condition. For example, you can prevent users from using layers published by other accounts. The
following policy adds a condition to the CreateFunction and UpdateFunctionConfiguration
actions to require that any layers specified come from account 123456789012.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ConfigureFunctions",
"Effect": "Allow",
"Action": [
49
AWS Lambda Developer Guide
Cross-account roles
"lambda:CreateFunction",
"lambda:UpdateFunctionConfiguration"
],
"Resource": "*",
"Condition": {
"ForAllValues:StringLike": {
"lambda:Layer": [
"arn:aws:lambda:*:123456789012:layer:*:*"
]
}
}
}
]
}
To ensure that the condition applies, verify that no other statements grant the user permission to these
actions.
Cross-account roles
You can apply any of the preceding policies and statements to a role, which you can then share with
another account to give it access to your Lambda resources. Unlike an IAM user, a role doesn't have
credentials for authentication. Instead, it has a trust policy that specifies who can assume the role and
use its permissions.
You can use cross-account roles to give accounts that you trust access to Lambda actions and
resources. If you just want to grant permission to invoke a function or use a layer, use resource-based
policies (p. 41) instead.
For more information, see IAM roles in the IAM User Guide.
50
AWS Lambda Developer Guide
Resources and conditions
Every IAM policy statement grants permission to an action that's performed on a resource. When the
action doesn't act on a named resource, or when you grant permission to perform the action on all
resources, the value of the resource in the policy is a wildcard (*). For many API actions, you can restrict
the resources that a user can modify by specifying the Amazon Resource Name (ARN) of a resource, or an
ARN pattern that matches multiple resources.
• Function – arn:aws:lambda:us-west-2:123456789012:function:my-function
• Function version – arn:aws:lambda:us-west-2:123456789012:function:my-function:1
• Function alias – arn:aws:lambda:us-west-2:123456789012:function:my-function:TEST
• Event source mapping – arn:aws:lambda:us-west-2:123456789012:event-source-
mapping:fa123456-14a1-4fd2-9fec-83de64ad683de6d47
• Layer – arn:aws:lambda:us-west-2:123456789012:layer:my-layer
• Layer version – arn:aws:lambda:us-west-2:123456789012:layer:my-layer:1
For example, the following policy allows a user in account 123456789012 to invoke a function named
my-function in the US West (Oregon) Region.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Invoke",
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": "arn:aws:lambda:us-west-2:123456789012:function:my-function"
}
]
}
This is a special case where the action identifier (lambda:InvokeFunction) differs from the API
operation (Invoke (p. 592)). For other actions, the action identifier is the operation name prefixed by
lambda:.
Conditions are an optional policy element that applies additional logic to determine if an action is
allowed. In addition to common conditions supported by all actions, Lambda defines condition types
that you can use to restrict the values of additional parameters on some actions.
For example, the lambda:Principal condition lets you restrict the service or account that a user can
grant invocation access to on a function's resource-based policy. The following policy lets a user grant
permission to SNS topics to invoke a function named test.
51
AWS Lambda Developer Guide
Functions
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ManageFunctionPolicy",
"Effect": "Allow",
"Action": [
"lambda:AddPermission",
"lambda:RemovePermission"
],
"Resource": "arn:aws:lambda:us-west-2:123456789012:function:test:*",
"Condition": {
"StringEquals": {
"lambda:Principal": "[Link]"
}
}
}
]
}
The condition requires that the principal is Amazon SNS and not another service or account. The resource
pattern requires that the function name is test and includes a version number or alias. For example,
test:v1.
For more information on resources and conditions for Lambda and other AWS services, see Actions,
resources, and condition keys in the IAM User Guide.
Sections
• Functions (p. 52)
• Event source mappings (p. 53)
• Layers (p. 54)
Functions
Actions that operate on a function can be restricted to a specific function by function, version, or alias
ARN, as described in the following table. Actions that don't support resource restrictions can only be
granted for all resources (*).
Functions
Function alias
Function alias
52
AWS Lambda Developer Guide
Event source mappings
For these actions, the resource is the event source mapping, so Lambda provides a condition that lets you
restrict permission based on the function that the event source mapping invokes.
53
AWS Lambda Developer Guide
Layers
Layers
Layer actions let you restrict the layers that a user can manage or use with a function. Actions related
to layer use and permissions act on a version of a layer, while PublishLayerVersion acts on a layer
name. You can use either with wildcards to restrict the layers that a user can work with by name.
Layers
54
AWS Lambda Developer Guide
Permissions boundaries
The application templates in the Lambda console include a global property that applies a permissions
boundary to all functions that they create.
Globals:
Function:
PermissionsBoundary: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/
${AppId}-${AWS::Region}-PermissionsBoundary'
The boundary limits the permissions of the functions' roles. You can add permissions to a function's
execution role in the template, but that permission is only effective if it's also allowed by the permissions
boundary. The role that AWS CloudFormation assumes to deploy the application enforces the use of the
permissions boundary. That role only has permission to create and pass roles that have the application's
permissions boundary attached.
By default, an application's permissions boundary enables functions to perform actions on the resources
in the application. For example, if the application includes an Amazon DynamoDB table, the boundary
allows access to any API action that can be restricted to operate on specific tables with resource-level
permissions. You can only use actions that don't support resource-level permissions if they're specifically
permitted in the boundary. These include Amazon CloudWatch Logs and AWS X-Ray API actions for
logging and tracing.
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"*"
],
"Resource": [
"arn:aws:lambda:us-east-2:123456789012:function:my-app-getAllItemsFunction-
*",
"arn:aws:lambda:us-east-2:123456789012:function:my-app-getByIdFunction-*",
"arn:aws:lambda:us-east-2:123456789012:function:my-app-putItemFunction-*",
"arn:aws:dynamodb:us-east-1:123456789012:table/my-app-SampleTable-*"
],
"Effect": "Allow",
"Sid": "StackResources"
},
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:DescribeLogGroups",
"logs:PutLogEvents",
"xray:Put*"
],
"Resource": "*",
55
AWS Lambda Developer Guide
Permissions boundaries
"Effect": "Allow",
"Sid": "StaticPermissions"
},
...
]
}
To access other resources or API actions, you or an administrator must expand the permissions boundary
to include those resources. You might also need to update the execution role or deployment role of an
application to allow the use of additional actions.
• Permissions boundary – Extend the application's permissions boundary when you add resources to
your application, or the execution role needs access to more actions. In IAM, add resources to the
boundary to allow the use of API actions that support resource-level permissions on that resource's
type. For actions that don't support resource-level permissions, add them in a statement that isn't
scoped to any resource.
• Execution role – Extend a function's execution role when it needs to use additional actions. In the
application template, add policies to the execution role. The intersection of permissions in the
boundary and execution role is granted to the function.
• Deployment role – Extend the application's deployment role when it needs additional permissions
to create or configure resources. In IAM, add policies to the application's deployment role. The
deployment role needs the same user permissions that you need to deploy or update an application in
AWS CloudFormation.
For a tutorial that walks through adding resources to an application and extending its permissions, see
??? (p. 149).
For more information, see Permissions boundaries for IAM entities in the IAM User Guide.
56
AWS Lambda Developer Guide
To keep secrets out of your function code, store them in the function's configuration and read them from
the execution environment during initialization. Environment variables (p. 61) are always encrypted
at rest, and can be encrypted client-side as well. Use environment variables to make your function code
portable by removing connection strings, passwords, and endpoints for external resources.
Versions and aliases (p. 76) are secondary resources that you can create to manage function
deployment and invocation. Publish versions (p. 76) of your function to store its code and
configuration as a separate resource that cannot be changed, and create an alias (p. 79) that points
to a specific version. Then you can configure your clients to invoke a function alias, and update the alias
when you want to point the client to a new version, instead of updating the client.
As you add libraries and other dependencies to your function, creating and uploading a deployment
package can slow down development. Use layers (p. 83) to manage your function's dependencies
independently and keep your deployment package small. You can also use layers to share your own
libraries with other customers and use publicly available layers with your functions.
To use your Lambda function with AWS resources in an Amazon VPC, configure it with security groups
and subnets to create a VPC connection (p. 88). Connecting your function to a VPC lets you access
resources in a private subnet such as relational databases and caches. You can also create a database
proxy (p. 91) for MySQL and Aurora DB instances. A database proxy enables a function to reach high
concurrency levels without exhausting database connections.
Topics
• Configuring functions in the AWS Lambda console (p. 58)
• Using AWS Lambda environment variables (p. 61)
• Managing concurrency for a Lambda function (p. 67)
• AWS Lambda function versions (p. 76)
• AWS Lambda function aliases (p. 79)
• AWS Lambda layers (p. 83)
• Configuring a Lambda function to access resources in a VPC (p. 88)
• Configuring database access for a Lambda function (p. 91)
• Tagging Lambda Functions (p. 95)
57
AWS Lambda Developer Guide
Configuration console
To manage a function, open the Lambda console Functions page and choose a function. The function
designer is at the top of the configuration page.
The designer shows an overview of your function and its upstream and downstream resources. You can
use it to configure triggers, layers, and destinations.
• Triggers – Triggers are services and resources that you have configured to invoke your function.
Choose Add trigger to create a Lambda event source mapping (p. 109) or to configure a trigger in
another service that the Lambda console integrates with. For details about these services and others,
see Using AWS Lambda with other services (p. 166).
• Layers – Choose the Layers node to add layers (p. 83) to your application. A layer is a ZIP archive
that contains libraries, a custom runtime, or other dependencies.
• Destinations – Add a destination to your function to send details about invocation results to another
service. You can send invocation records when your function is invoked asynchronously (p. 101), or by
an event source mapping (p. 109) that reads from a stream.
With the function node selected in the designer, you can modify the following settings.
Function settings
• Code – The code and dependencies of your function. For scripting languages, you can edit your
function code in the embedded editor (p. 8). To add libraries, or for languages that the editor doesn't
support, upload a deployment package (p. 24). If your deployment package is larger than 50 MB,
choose Upload a file from Amazon S3.
• Runtime – The Lambda runtime (p. 129) that executes your function.
• Handler – The method that the runtime executes when your function is invoked, such as
[Link]. The first value is the name of the file or module. The second value is the name of
the method.
58
AWS Lambda Developer Guide
Configuration console
• Environment variables – Key-value pairs that Lambda sets in the execution environment. Use
environment variables (p. 61) to extend your function's configuration outside of code.
• Tags – Key-value pairs that Lambda attaches to your function resource. Use tags (p. 95) to organize
Lambda functions into groups for cost reporting and filtering in the Lambda console.
Tags apply to the entire function, including all versions and aliases.
• Execution role – The IAM role (p. 37) that AWS Lambda assumes when it executes your function.
• Description – A description of the function.
• Memory– The amount of memory available to the function during execution. Choose an amount
between 128 MB and 3,008 MB (p. 34) in 64-MB increments.
Lambda allocates CPU power linearly in proportion to the amount of memory configured. At 1,792
MB, a function has the equivalent of one full vCPU (one vCPU-second of credits per second).
• Timeout – The amount of time that Lambda allows a function to run before stopping it. The default is
3 seconds. The maximum allowed value is 900 seconds.
• Virtual private cloud (VPC) – If your function needs network access to resources that are not available
over the internet, configure it to connect to a VPC (p. 88).
• Database proxies – Create a database proxy (p. 91) for functions that use an Amazon RDS DB
instance or cluster.
• Active tracing – Sample incoming requests and trace sampled requests with AWS X-Ray (p. 314).
• Concurrency – Reserve concurrency for a function (p. 67) to set the maximum number of
simultaneous executions for a function. Provision concurrency to ensure that a function can scale
without fluctuations in latency.
Reserved concurrency applies to the entire function, including all versions and aliases.
• Asynchronous invocation – Configure error handling behavior (p. 101) to reduce the number of
retries that Lambda attempts, or the amount of time that unprocessed events stay queued before
Lambda discards them. Configure a dead-letter queue (p. 106) to retain discarded events.
Except as noted in the preceding list, you can only change function settings on the unpublished version
of a function. When you publish a version, code and most settings are locked to ensure a consistent
experience for users of that version. Use aliases (p. 79) to propagate configuration changes in a
controlled manner.
To configure functions with the Lambda API, use the following actions:
For example, to update a function's memory setting with the AWS CLI, use the update-function-
configuration command.
59
AWS Lambda Developer Guide
Configuration console
For function configuration best practices, see Function Configuration (p. 164).
60
AWS Lambda Developer Guide
Environment variables
You set environment variables on the unpublished version of your function by specifying a key and value.
When you publish a version, the environment variables are locked for that version along with other
version-specific configuration (p. 58).
Requirements
Use environment variables to pass environment-specific settings to your code. For example, you can have
two functions with the same code but different configuration. One function connects to a test database,
and the other connects to a production database. In this situation, you use environment variables to
tell the function the hostname and other connection details for the database. You might also set an
environment variable to configure your test environment to use more verbose logging or more detailed
tracing.
To retrieve environment variables in your function code, use the standard method for your programming
language.
[Link]
61
AWS Lambda Developer Guide
Runtime environment variables
Python
import os
region = [Link]['AWS_REGION']
Ruby
region = ENV["AWS_REGION"]
Java
Go
C#
PowerShell
$region = $env:AWS_REGION
Lambda stores environment variables securely by encrypting them at rest. You can configure Lambda to
use a different encryption key (p. 63), encrypt environment variable values on the client side, or set
environment variables in an AWS CloudFormation template with AWS Secrets Manager.
Sections
• Runtime environment variables (p. 62)
• Securing environment variables (p. 63)
• Configuring environment variables with the Lambda API (p. 65)
• Sample code and templates (p. 66)
62
AWS Lambda Developer Guide
Securing environment variables
The following additional environment variables aren't reserved and can be extended in your function
configuration.
The sample values shown reflect the latest runtimes. The presence of specific variables or their values
can vary on earlier runtimes.
When you provide the key, only users in your account with access to the key can view or manage
environment variables on the function. Your organization might also have internal or external
requirements to manage keys that are used for encryption and to control when they're rotated.
63
AWS Lambda Developer Guide
Securing environment variables
No AWS KMS permissions are required for your user or the function's execution role to use the default
encryption key. To use a customer managed CMK, you need permission to use the key. Lambda uses your
permissions to create a grant on the key. This allows Lambda to use it for encryption.
You can get these permissions from your user account or from a key's resource-based permissions policy.
ListAliases is provided by the managed policies for Lambda (p. 46). Key policies grant the remaining
permissions to users in the Key users group.
Users without Decrypt permissions can still manage functions, but they can't view environment
variables or manage them in the Lambda console. To prevent a user from viewing environment variables,
add a statement to the user's permissions that denies access to the default key, a customer managed key,
or all keys.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Deny",
"Action": [
"kms:Decrypt"
],
"Resource": "arn:aws:kms:us-east-2:123456789012:key/3be10e2d-xmpl-4be4-
bc9d-0405a71945cc"
}
]
}
For details on managing key permissions, see Using key policies in AWS KMS.
You can also encrypt environment variable values on the client side before sending them to Lambda, and
decrypt them in your function code. This obscures secret values in the Lambda console and API output,
even for users who have permission to use the key. In your code, you retrieve the encrypted value from
the environment and decrypt it by using the AWS KMS API.
64
AWS Lambda Developer Guide
Configuring environment variables with the Lambda API
To view sample code for your function's language, choose Code next to an environment variable. The
sample code shows how to retrieve an environment variable in a function and decrypt its value.
Another option is to store passwords in AWS Secrets Manager secrets. You can reference the secret in
your AWS CloudFormation templates to set passwords on databases. You can also set the value of an
environment variable on the Lambda function. For an example, see the next section.
The following example sets two environment variables on a function named my-function.
When you apply environment variables with the update-function-configuration command, the
entire contents of the Variables structure is replaced. To retain existing environment variables when
you add a new one, include all existing values in your request.
65
AWS Lambda Developer Guide
Sample code and templates
To ensure that the values don't change between when you read the configuration and when you update
it, you can pass the revision ID from the output of get-function-configuration as a parameter to
update-function-configuration.
Sample applications
• Blank function (p. 320) – Create a function and an Amazon SNS topic in the same template. Pass
the name of the topic to the function in an environment variable. Read environment variables in code
(multiple languages).
• RDS MySQL – Create a VPC and an Amazon RDS DB instance in one template, with a password stored
in Secrets Manager. In the application template, import database details from the VPC stack, read the
password from Secrets Manager, and pass all connection configuration to the function in environment
variables.
66
AWS Lambda Developer Guide
Concurrency
Concurrency is subject to a Regional limit (p. 34) that is shared by all functions in a Region. To ensure
that a function can always reach a certain level of concurrency, you can configure the function with
reserved concurrency (p. 67). When a function has reserved concurrency, no other function can use
that concurrency. Reserved concurrency also limits the maximum concurrency for the function, and
applies to the function as a whole, including versions and aliases.
When Lambda allocates an instance of your function, the runtime (p. 129) loads your function's code
and runs initialization code that you define outside of the handler. If your code and dependencies are
large, or you create SDK clients during initialization, this process can take some time. As your function
scales up (p. 114), this causes the portion of requests that are served by new instances to have higher
latency than the rest.
To enable your function to scale without fluctuations in latency, use provisioned concurrency (p. 69).
By allocating provisioned concurrency before an increase in invocations, you can ensure that all requests
are served by initialized instances with very low latency. You can configure provisioned concurrency on a
version of a function, or on an alias.
Lambda also integrates with Application Auto Scaling. You can configure Application Auto Scaling
to manage provisioned concurrency on a schedule or based on utilization. Use scheduled scaling to
increase provisioned concurrency in anticipation of peak traffic. To increase provisioned concurrency
automatically as needed, use the Application Auto Scaling API (p. 72) to register a target and create a
scaling policy.
Provisioned concurrency counts towards a function's reserved concurrency and Regional limits. If
the amount of provisioned concurrency on a function's versions and aliases adds up to the function's
reserved concurrency, all invocations run on provisioned concurrency. This configuration also has the
effect of throttling the unpublished version of the function ($LATEST), which prevents it from executing.
Sections
• Configuring reserved concurrency (p. 67)
• Configuring provisioned concurrency (p. 69)
• Configuring concurrency with the Lambda API (p. 72)
67
AWS Lambda Developer Guide
Configuring reserved concurrency
You can reserve up to the Unreserved account concurrency value that is shown, minus 100 for functions
that don't have reserved concurrency. To throttle a function, set the reserved concurrency to zero. This
stops any events from being processed until you remove the limit.
The following example shows two functions with pools of reserved concurrency, and the unreserved
concurrency pool used by other functions. Throttling errors occur when all of the concurrency in a pool is
in use.
Legend
• Function concurrency
• Reserved concurrency
• Unreserved concurrency
• Throttling
68
AWS Lambda Developer Guide
Configuring provisioned concurrency
• Other functions can't prevent your function from scaling – All of your account's functions in the
same Region without reserved concurrency share the pool of unreserved concurrency. Without
reserved concurrency, other functions can use up all of the available concurrency. This prevents your
function from scaling up when needed.
• Your function can't scale out of control – Reserved concurrency also limits your function from
using concurrency from the unreserved pool, which caps its maximum concurrency. You can reserve
concurrency to prevent your function from using all the available concurrency in the Region, or from
overloading downstream resources.
Setting per-function concurrency can impact the concurrency pool that is available to other functions.
To avoid issues, limit the number of users who can use the PutFunctionConcurrency and
DeleteFunctionConcurrency API operations.
You can manage provisioned concurrency for all aliases and versions from the function configuration
page. The list of provisioned concurrency configurations shows the allocation progress of each
configuration. Provisioned concurrency settings are also available on the configuration page for each
version and alias.
In the following example, the my-function-DEV and my-function-PROD functions are configured
with both reserved and provisioned concurrency. For my-function-DEV, the full pool of reserved
concurrency is also provisioned concurrency. In this case, all invocations either run on provisioned
concurrency or are throttled. For my-function-PROD, a portion of the reserved concurrency pool
is standard concurrency. When all provisioned concurrency is in use, the function scales on standard
concurrency to serve any additional requests.
69
AWS Lambda Developer Guide
Configuring provisioned concurrency
Legend
• Function concurrency
• Reserved concurrency
• Provisioned concurrency
• Unreserved concurrency
• Throttling
Provisioned concurrency does not come online immediately after you configure it. Lambda starts
allocating provisioned concurrency after a minute or two of preparation. Similar to how functions scale
under load (p. 114), up to 3000 instances of the function can be initialized at once, depending on the
Region. After the initial burst, instances are allocated at a steady rate of 500 per minute until the request
is fulfilled. When you request provisioned concurrency for multiple functions or versions of a function in
the same Region, scaling limits apply across all requests.
70
AWS Lambda Developer Guide
Configuring provisioned concurrency
Legend
• Function instances
• Open requests
• Provisioned concurrency
• Standard concurrency
Your function's initialization code (p. 22) runs during allocation and every few hours, as running instances
of your function are recycled. You can see the initialization time in logs and traces (p. 314) after
an instance processes a request. However, initialization is billed even if the instance never processes
a request. Provisioned concurrency runs continually and is billed separately from initialization and
invocation costs. For details, see AWS Lambda pricing.
Each version of a function can only have one provisioned concurrency configuration. This can be directly
on the version itself, or on an alias that points to the version. Two aliases can't allocate provisioned
71
AWS Lambda Developer Guide
Configuring concurrency with the Lambda API
concurrency for the same version. Also, you can't allocate provisioned concurrency on an alias that points
to the unpublished version ($LATEST).
When you change the version that an alias points to, provisioned concurrency is deallocated from the old
version and then allocated to the new version. You can add a routing configuration to an alias that has
provisioned concurrency. However, you can't manage provisioned concurrency settings on the alias while
the routing configuration is in place.
• ProvisionedConcurrentExecutions
• ProvisionedConcurrencyInvocations
• ProvisionedConcurrencySpilloverInvocations
• ProvisionedConcurrencyUtilization
For details, see Working with AWS Lambda function metrics (p. 478).
To configure reserved concurrency with the AWS CLI, use the put-function-concurrency command.
The following command reserves a concurrency of 100 for a function named my-function:
72
AWS Lambda Developer Guide
Configuring concurrency with the Lambda API
{
"Requested ProvisionedConcurrentExecutions": 100,
"Allocated ProvisionedConcurrentExecutions": 0,
"Status": "IN_PROGRESS",
"LastModified": "2019-11-21T[Link]+0000"
}
To configure Application Auto Scaling to manage provisioned concurrency, use the Application Auto
Scaling to configure target tracking scaling. First, register a function's alias as a scaling target. The
following example registers the BLUE alias of a function named my-function:
Next, apply a scaling policy to the target. The following example configures Application Auto Scaling to
adjust the provisioned concurrency configuration for an alias to keep utilization near 70 percent:
Application Auto Scaling creates two alarms in CloudWatch. The first alarm triggers when the utilization
of provisioned concurrency consistently exceeds 70 percent. When this happens, Application Auto
Scaling allocates more provisioned concurrency to reduce utilization. The second alarm triggers when
utilization is consistently less than 63 percent (90 percent of the 70 percent target). When this happens,
Application Auto Scaling reduces the alias's provisioned concurrency.
In the following example, a function scales between a minimum and maximum amount of provisioned
concurrency based on utilization. When the number of open requests increases, Application Auto
Scaling increases provisioned concurrency in large steps until it reaches the configured maximum. The
function continues to scale on standard concurrency until utilization starts to drop. When utilization is
consistently low, Application Auto Scaling decreases provisioned concurrency in smaller periodic steps.
73
AWS Lambda Developer Guide
Configuring concurrency with the Lambda API
Legend
• Function instances
• Open requests
• Provisioned concurrency
• Standard concurrency
74
AWS Lambda Developer Guide
Configuring concurrency with the Lambda API
"CodeSizeZipped": 52428800,
"ConcurrentExecutions": 1000,
"UnreservedConcurrentExecutions": 900
},
"AccountUsage": {
"TotalCodeSize": 174913095,
"FunctionCount": 52
}
}
75
AWS Lambda Developer Guide
Versions
The system creates a new version of your Lambda function each time that you publish the function.
The new version is a copy of the unpublished version of the function. The function version includes the
following information:
You can change the function code and settings only on the unpublished version of a function. When
you publish a version, the code and most of the settings are locked to ensure a consistent experience
for users of that version. For more information about configuring function settings, see Configuring
functions in the AWS Lambda console (p. 58).
After you publish the first version of a function, the Lambda console displays a drop-down menu of the
available versions. The Designer panel displays a version qualifier at the end of the function name.
76
AWS Lambda Developer Guide
Managing versions with the Lambda API
To view the current versions of the function, choose a function, and then choose Qualifiers. In the
expanded Qualifiers menu, choose the Versions tab. The Versions panel displays the list of versions for
the selected function. If you haven't published a version of the selected function, the Versions panel lists
only the $LATEST version.
The following example publishes a new version of a function. The response returns configuration
information about the new version, including the version number and the function ARN with the version
suffix.
Using versions
You reference your Lambda function using its ARN. There are two ARNs associated with this initial
version:
77
AWS Lambda Developer Guide
Resource policies
arn:aws:lambda:aws-region:acct-id:function:helloworld:$LATEST
arn:aws:lambda:aws-region:acct-id:function:helloworld
You can use this unqualified ARN in all relevant operations. However, you can't use it to create an alias.
If you decide not to publish function versions, you can use either the qualified or unqualified ARN in your
event source mapping to invoke the function.
Lambda only publishes a new function version if the code has never been published or if the code has
changed compared to the most recently published version. If there is no change, the function version
remains at the most recently published version.
Each Lambda function version has a unique ARN. After you publish a version, you can't change the ARN
or the function code.
Resource policies
When you use a resource-based policy (p. 41) to give a service, resource, or account access to your
function, the scope of that permission depends on whether you applied it to a function or to one version
of a function:
• If you use a qualified function name (such as helloworld:1), the permission is valid for invoking
the helloworld function version 1 only using its qualified ARN. Using any other ARNs results in a
permission error.
• If you use an unqualified function name (such as helloworld), the permission is valid only for
invoking the helloworld function using the unqualified function ARN. Using any other ARNs,
including $LATEST, results in a permission error.
• If you use the $LATEST qualified function name (such as helloworld:$LATEST), the permission is
valid for invoking the helloworld function only using its qualified ARN. Using an unqualified ARN
results in a permission error.
You can simplify the management of event sources and resource policies by using function aliases. For
more information, see AWS Lambda function aliases (p. 79).
78
AWS Lambda Developer Guide
Aliases
To create an alias
4. In the Create a new alias form, enter a name for the alias and an optional description. Choose the
function version for this alias.
To view the aliases that are currently defined for a function, choose Qualifiers, and choose the Aliases
tab.
To change an alias to point a new version of the function, use the update-alias command.
The AWS CLI commands in the preceding steps correspond to the following AWS Lambda APIs:
79
AWS Lambda Developer Guide
Using aliases
Using aliases
Each alias has a unique ARN. An alias can only point to a function version, not to another alias. You can
update an alias to point to a new version of the function.
Event sources such as Amazon S3 invoke your Lambda function. These event sources maintain a mapping
that identifies the function to invoke when events occur. If you specify a Lambda function alias in the
mapping configuration, you don't need to update the mapping when the function version changes.
In a resource policy, you can grant permissions for event sources to use your Lambda function. If you
specify an alias ARN in the policy, you don't need to update the policy when the function version
changes.
Resource policies
When you use a resource-based policy (p. 41) to give a service, resource, or account access to your
function, the scope of that permission depends on whether you applied it to an alias, to a version, or
to the function. If you use an alias name (such as helloworld:PROD), the permission is valid only for
invoking the helloworld function using the alias ARN. You get a permission error if you use a version
ARN or the function ARN. This includes the version ARN that the alias points to.
For example, the following AWS CLI command grants Amazon S3 permissions to invoke the PROD alias
of the helloworld Lambda function. Note that the --qualifier parameter specifies the alias name.
In this case, Amazon S3 is now able to invoke the PROD alias. Lambda can then execute the helloworld
Lambda function version that the PROD alias references. For this to work correctly, you must use the
PROD alias ARN in the S3 bucket's notification configuration.
You can point an alias to a maximum of two Lambda function versions. The versions must meet the
following criteria:
80
AWS Lambda Developer Guide
Alias routing configuration
5. In the Create a new alias window, enter a value for Name, optionally enter a value for Description,
and choose the Version of the Lambda function that the alias references.
6. Under Additional version, specify the following items:
The following example creates an alias (named routing-alias) for a Lambda function. The alias points
to version 1 of the function. Version 2 of the function receives 3 percent of the traffic. The remaining 97
percent of traffic is routed to version 1.
Use the update-alias command to increase the percentage of incoming traffic to version 2. In the
following example, you increase the traffic to 5 percent.
To route all traffic to version 2, use the UpdateAlias command to change the function-version
property to point the alias to version 2. The command also resets the routing configuration.
The CLI commands in the preceding steps correspond to the following AWS Lambda API operations:
• CloudWatch Logs – Lambda automatically emits a START log entry that contains the invoked version
ID to CloudWatch Logs for every function invocation. The following is an example:
For alias invocations, Lambda uses the Executed Version dimension to filter the metric data by the
executed version. For more information, see Working with AWS Lambda function metrics (p. 478).
81
AWS Lambda Developer Guide
Alias routing configuration
82
AWS Lambda Developer Guide
Layers
Layers let you keep your deployment package small, which makes development easier. You can avoid
errors that can occur when you install and package dependencies with your function code. For [Link],
Python, and Ruby functions, you can develop your function code in the Lambda console (p. 8) as long as
you keep your deployment package under 3 MB.
Note
A function can use up to 5 layers at a time. The total unzipped size of the function and all layers
can't exceed the unzipped deployment package size limit of 250 MB. For more information, see
AWS Lambda limits (p. 34).
You can create layers, or use layers published by AWS and other AWS customers. Layers support
resource-based policies (p. 87) for granting layer usage permissions to specific AWS accounts, AWS
Organizations, or all accounts.
Layers are extracted to the /opt directory in the function execution environment. Each runtime looks for
libraries in a different location under /opt, depending on the language. Structure your layer (p. 86) so
that function code can access libraries without additional configuration.
You can also use AWS Serverless Application Model (AWS SAM) to manage layers and your function's
layer configuration. For instructions, see Declaring serverless resources in the AWS Serverless Application
Model Developer Guide.
Sections
• Configuring a function to use layers (p. 83)
• Managing layers (p. 84)
• Including library dependencies in a layer (p. 86)
• Layer permissions (p. 87)
To add layers to your function, use the update-function-configuration command. The following
example adds two layers: one from the same account as the function, and one from a different account.
83
AWS Lambda Developer Guide
Managing layers
"CodeSize": 169
},
{
"Arn": "arn:aws:lambda:us-east-2:210987654321:layer:their-layer:2",
"CodeSize": 169
}
],
"RevisionId": "81cc64f5-5772-449a-b63e-12330476bcc4",
...
}
You must specify the version of each layer to use by providing the full ARN of the layer version. When
you add layers to a function that already has layers, the previous list is overwritten by the new one.
Include all layers every time you update the layer configuration. To remove all layers, specify an empty
list.
Your function can access the content of the layer during execution in the /opt directory. Layers are
applied in the order that's specified, merging any folders with the same name. If the same file appears in
multiple layers, the version in the last applied layer is used.
The creator of a layer can delete the version of the layer that you're using. When this happens, your
function continues to run as though the layer version still existed. However, when you update the layer
configuration, you must remove the reference to the deleted version.
Managing layers
To create a layer, use the publish-layer-version command with a name, description, ZIP archive,
and a list of runtimes (p. 129) that are compatible with the layer. The list of runtimes is optional, but it
makes the layer easier to discover.
Each time you call publish-layer-version, you create a new version. Functions that use the layer
refer directly to a layer version. You can configure permissions (p. 87) on an existing layer version, but
to make any other changes, you must create a new version.
84
AWS Lambda Developer Guide
Managing layers
To find layers that are compatible with your function's runtime, use the list-layers command.
You can omit the runtime option to list all layers. The details in the response reflect the latest version of
the layer. See all the versions of a layer with list-layer-versions. To see more information about a
version, use get-layer-version.
The link in the response lets you download the layer archive and is valid for 10 minutes. To delete a layer
version, use the delete-layer-version command.
When you delete a layer version, you can no longer configure functions to use it. However, any function
that already uses the version continues to have access to it. Version numbers are never re-used for a layer
name.
85
AWS Lambda Developer Guide
Including library dependencies in a layer
To include libraries in a layer, place them in one of the folders supported by your runtime.
[Link]
# nodejs/node_modules/aws-xray-sdk
Example Pillow
[Link]
# python/PIL
# python/[Link]-info
Example Jackson
[Link]
# java/lib/[Link]
Example JSON
[Link]
# ruby/gems/2.5.0/
| build_info
| cache
| doc
| extensions
| gems
| # json-2.1.0
# specifications
# [Link]
Example JQ
[Link]
# bin/jq
For more information about path settings in the Lambda execution environment, see Runtime
environment variables (p. 62).
86
AWS Lambda Developer Guide
Layer permissions
Layer permissions
Layer usage permissions are managed on the resource. To configure a function with a layer, you need
permission to call GetLayerVersion on the layer version. For functions in your account, you can get
this permission from your user policy (p. 46) or from the function's resource-based policy (p. 41). To use
a layer in another account, you need permission on your user policy, and the owner of the other account
must grant your account permission with a resource-based policy.
To grant layer-usage permission to another account, add a statement to the layer version's permissions
policy with the add-layer-version-permission command. In each statement, you can grant
permission to a single account, all accounts, or an organization.
Permissions only apply to a single version of a layer. Repeat the procedure each time you create a new
layer version.
For more examples, see Granting layer access to other accounts (p. 44).
87
AWS Lambda Developer Guide
Network
When you connect a function to a VPC, Lambda creates an elastic network interface for each
combination of security group and subnet in your function's VPC configuration. This process can take
about a minute. During this time, you cannot perform additional operations that target the function,
such as creating versions (p. 76) or updating the function's code. For new functions, you can't invoke
the function until its state transitions from Pending to Active. For existing functions, you can still
invoke the old version while the update is in progress. For more information about function states, see
Monitoring the state of a function with the Lambda API (p. 112).
Multiple functions connected to the same subnets share network interfaces, so connecting additional
functions to a subnet that already has a Lambda-managed network interface is much quicker. However,
Lambda might create additional network interfaces if you have many functions or very busy functions.
If your functions are not active for a long period of time, Lambda reclaims its network interfaces, and
the function becomes Idle. Invoke an idle function to reactivate it. The first invocation fails and the
function enters a pending state again until the network interface is available.
Lambda functions cannot connect directly to a VPC with dedicated instance tenancy. To connect to
resources in a dedicated VPC, peer it to a second VPC with default tenancy.
VPC tutorials
• Tutorial: Configuring a Lambda function to access Amazon RDS in an Amazon VPC (p. 275)
• Tutorial: Configuring a Lambda function to access Amazon ElastiCache in an Amazon VPC (p. 248)
Sections
• Execution role and user permissions (p. 89)
• Configuring Amazon VPC access with the Lambda API (p. 89)
• Internet and service access for VPC-connected functions (p. 90)
• Sample VPC configurations (p. 90)
88
AWS Lambda Developer Guide
Execution role and user permissions
• ec2:CreateNetworkInterface
• ec2:DescribeNetworkInterfaces
• ec2:DeleteNetworkInterface
When you configure VPC connectivity, Lambda uses your permissions to verify network resources. To
configure a function to connect to a VPC, your IAM user need the following permissions.
User permissions
• ec2:DescribeSecurityGroups
• ec2:DescribeSubnets
• ec2:DescribeVpcs
To connect your function to a VPC during creation with the AWS CLI, use the vpc-config option
with a list of private subnet IDs and security groups. The following example creates a function with a
connection to a VPC with two subnets and one security group.
To connect an existing function, use the vpc-config option with the update-function-
configuration command.
To disconnect your function from a VPC, update the function configuration with an empty list of subnets
and security groups.
89
AWS Lambda Developer Guide
Internet and service access for VPC-connected functions
Internet access from a private subnet requires network address translation (NAT). To give your function
access to the internet, route outbound traffic to a NAT gateway in a public subnet. The NAT gateway
has a public IP address and can connect to the internet through the VPC's internet gateway. For more
information, see NAT gateways in the Amazon VPC User Guide.
• [Link] – A VPC with two private subnets and VPC endpoints for Amazon Simple Storage
Service and Amazon DynamoDB. You can use this template to create a VPC for functions that do not
need internet access. This configuration supports use of Amazon S3 and DynamoDB with the AWS
SDK, and access to database resources in the same VPC over a local network connection.
• [Link] – A VPC with two private subnets, VPC endpoints, a public subnet with a NAT
gateway, and an internet gateway. Internet-bound traffic from functions in the private subnets is
routed to the NAT gateway by a route table.
To use a template to create a VPC, choose Create stack in the AWS CloudFormation console and follow
the instructions.
90
AWS Lambda Developer Guide
Database
Example secret
{
"username": "admin",
"password": "e2abcecxmpldc897"
}
• IAM role – An IAM role with permission to use the secret, and a trust policy that allows Amazon
RDS to assume the role.
• Authentication – The authentication and authorization method for connecting to the proxy from
your function code.
5. Choose Add.
Proxy creation takes a few minutes. When the proxy is available, configure your function to connect to
the proxy endpoint instead of the database endpoint.
Standard Amazon RDS Proxy pricing applies. For more information, see Managing connections with the
Amazon RDS Proxy in the Amazon Aurora User Guide.
Topics
• Using the function's permissions for authentication (p. 91)
• Sample application (p. 92)
You can create a database proxy that uses the function's IAM credentials for authentication and
authorization instead of a password. To use the function's permissions to connect to the proxy, set
Authentication to Execution role.
91
AWS Lambda Developer Guide
Sample application
The Lambda console adds the required permission (rds-db:connect) to the execution role. You can
then use the AWS SDK to generate a token that allows it to connect to the proxy. The following example
shows how to configure a database connection with the mysql2 library in [Link].
For more information, see IAM database authentication in the Amazon RDS User Guide.
Sample application
Sample applications that demonstrate the use of Lambda with an Amazon RDS database are available in
this guide's GitHub repository. There are two applications:
• RDS MySQL – The AWS CloudFormation template [Link] creates a MySQL 5.7
database in a private VPC. In the sample application, a Lambda function proxies queries to the
database. The function and database templates both use Secrets Manager to access database
credentials.
92
AWS Lambda Developer Guide
Sample application
• List Manager – A processor function reads events from a Kinesis stream. It uses the data from the
events to update DynamoDB tables, and stores a copy of the event in a MySQL database.
93
AWS Lambda Developer Guide
Sample application
To use the sample applications, follow the instructions in the GitHub repository: RDS MySQL, List
Manager.
94
AWS Lambda Developer Guide
Tags
5. Choose Save.
You can filter functions based on the presence or value of a tag with the Lambda console or with the
AWS Resource Groups API. Tags apply at the function level, not to versions or aliases. Tags are not part of
the version-specific configuration that is snapshotted when you publish a version.
95
AWS Lambda Developer Guide
Using Tags with the AWS CLI
3. Choose a tag key to see a list of values that are in-use in the current region.
4. Choose a value to see functions with that value, or choose (all values) to see all functions that have
a tag with that key.
The search bar also supports searching for tag keys. Type tag to see just a list of tag keys, or start typing
the name of a key to find it in the list.
With AWS Billing and Cost Management, you can use tags to customize billing reports and create
cost-allocation reports. For more information, see see Monthly Cost Allocation Report and Using Cost
Allocation Tags in the AWS Billing and Cost Management User Guide.
Sections
• Using Tags with the AWS CLI (p. 96)
• Tag Key and Value Requirements (p. 97)
96
AWS Lambda Developer Guide
Tag Key and Value Requirements
If you want to view the tags that are applied to a specific Lambda function, you can use either of the
following Lambda API commands:
• ListTags (p. 619) – You supply your Lambda function ARN (Amazon Resource Name) to view a list of
the tags associated with this function:
• GetFunction (p. 565) – You supply your Lambda function name to a view a list of the tags associated
with this function:
You can also use the AWS Tagging Service’s GetResources API to filter your resources by tags. The
GetResources API receives up to 10 filters, with each filter containing a tag key and up to 10 tag values.
You provide GetResources with a ‘ResourceType’ to filter by specific resource types. For more information
about the AWS Tagging Service, see Working with Resource Groups.
97
AWS Lambda Developer Guide
When you invoke a function, you can choose to invoke it synchronously or asynchronously. With
synchronous invocation (p. 99), you wait for the function to process the event and return a response.
With asynchronous (p. 101) invocation, Lambda queues the event for processing and returns a response
immediately. For asynchronous invocation, Lambda handles retries and can send invocation records to a
destination (p. 103).
To use your function to process data automatically, add one or more triggers. A trigger is a Lambda
resource or a resource in another service that you configure to invoke your function in response to
lifecycle events, external requests, or on a schedule. Your function can have multiple triggers. Each
trigger acts as an client invoking your function independently. Each event that Lambda passes to your
function only has data from one client or trigger.
To process items from a stream or queue, you can create an event source mapping (p. 109). An event
source mapping is a resource in Lambda that reads items from an Amazon SQS queue, an Amazon
Kinesis stream, or an Amazon DynamoDB stream, and sends them to your function in batches. Each
event that your function processes can contain hundreds or thousands of items.
Other AWS services and resources invoke your function directly. For example, you can configure
CloudWatch Events to invoke your function on a timer, or you can configure Amazon S3 to invoke your
function when an object is created. Each service varies in the method it uses to invoke your function,
the structure of the event, and how you configure it. For more information, see Using AWS Lambda with
other services (p. 166).
Depending on who invokes your function and how it's invoked, scaling behavior and the types of errors
that occur can vary. When you invoke a function synchronously, you receive errors in the response and
can retry. When you invoke asynchronously, use an event source mapping, or configure another service
to invoke your function, the retry requirements and the way that your function scales to handle large
numbers of events can vary. For details, see AWS Lambda function scaling (p. 114) and Error handling
and automatic retries in AWS Lambda (p. 119).
Topics
• Synchronous invocation (p. 99)
• Asynchronous invocation (p. 101)
• AWS Lambda event source mappings (p. 109)
• Monitoring the state of a function with the Lambda API (p. 112)
• AWS Lambda function scaling (p. 114)
• Error handling and automatic retries in AWS Lambda (p. 119)
• Invoking Lambda functions with the AWS Mobile SDK for Android (p. 121)
98
AWS Lambda Developer Guide
Synchronous invocation
Synchronous invocation
When you invoke a function synchronously, Lambda runs the function and waits for a response. When
the function execution ends, Lambda returns the response from the function's code with additional data,
such as the version of the function that was executed. To invoke a function synchronously with the AWS
CLI, use the invoke command.
$ aws lambda invoke --function-name my-function --payload '{ "key": "value" }'
[Link]
{
"ExecutedVersion": "$LATEST",
"StatusCode": 200
}
The following diagram shows clients invoking a Lambda function synchronously. Lambda sends the
events directly to the function and sends the function's response back to the invoker.
The payload is a string that contains an event in JSON format. The name of the file where the AWS CLI
writes the response from the function is [Link]. If the function returns an object or error, the
response is the object or error in JSON format. If the function exits without error, the response is null.
The output from the command, which is displayed in the terminal, includes information from headers
in the response from Lambda. This includes the version that processed the event (useful when you use
aliases (p. 79)), and the status code returned by Lambda. If Lambda was able to run the function, the
status code is 200, even if the function returned an error.
Note
For functions with a long timeout, your client might be disconnected during synchronous
invocation while it waits for a response. Configure your HTTP client, SDK, firewall, proxy, or
operating system to allow for long connections with timeout or keep-alive settings.
If Lambda isn't able to run the function, the error is displayed in the output.
To get logs for an invocation from the command line, use the --log-type option. The response
includes a LogResult field that contains up to 4 KB of base64-encoded logs from the invocation.
99
AWS Lambda Developer Guide
Synchronous invocation
The base64 utility is available on Linux, macOS, and Ubuntu on Windows. For macOS, the command is
base64 -D.
For more information about the Invoke API, including a full list of parameters, headers, and errors, see
Invoke (p. 592).
When you invoke a function directly, you can check the response for errors and retry. The AWS CLI
and AWS SDK also automatically retry on client timeouts, throttling, and service errors. For more
information, see Error handling and automatic retries in AWS Lambda (p. 119).
100
AWS Lambda Developer Guide
Asynchronous invocation
Asynchronous invocation
Several AWS services, such as Amazon Simple Storage Service (Amazon S3) and Amazon Simple
Notification Service (Amazon SNS), invoke functions asynchronously to process events. When you invoke
a function asynchronously, you don't wait for a response from the function code. You hand off the event
to Lambda and Lambda handles the rest. You can configure how Lambda handles errors, and can send
invocation records to a downstream resource to chain together components of your application.
The following diagram shows clients invoking a Lambda function asynchronously. Lambda queues the
events before sending them to the function.
For asynchronous invocation, Lambda places the event in a queue and returns a success response
without additional information. A separate process reads events from the queue and sends them to your
function. To invoke a function asynchronously, set the invocation type parameter to Event.
The output file ([Link]) doesn't contain any information, but is still created when you run
this command. If Lambda isn't able to add the event to the queue, the error message appears in the
command output.
Lambda manages the function's asynchronous event queue and attempts to retry on errors. If the
function returns an error, Lambda attempts to run it two more times, with a one-minute wait between
the first two attempts, and two minutes between the second and third attempts. Function errors include
errors returned by the function's code and errors returned by the function's runtime, such as timeouts.
101
AWS Lambda Developer Guide
Asynchronous invocation
If the function doesn't have enough concurrency available to process all events, additional requests
are throttled. For throttling errors (429) and system errors (500-series), Lambda returns the event
to the queue and attempts to run the function again for up to 6 hours. The retry interval increases
exponentially from 1 second after the first attempt to a maximum of 5 minutes. However, it might be
longer if the queue is backed up. Lambda also reduces the rate at which it reads events from the queue.
The following example shows an event that was successfully added to the queue, but is still pending one
hour later due to throttling.
Even if your function doesn't return an error, it's possible for it to receive the same event from Lambda
multiple times because the queue itself is eventually consistent. If the function can't keep up with
incoming events, events might also be deleted from the queue without being sent to the function.
Ensure that your function code gracefully handles duplicate events, and that you have enough
concurrency available to handle all invocations.
When the queue is backed up, new events might age out before Lambda has a chance to send them
to your function. When an event expires or fails all processing attempts, Lambda discards it. You can
configure error handling (p. 103) for a function to reduce the number of retries that Lambda performs,
or to discard unprocessed events more quickly.
You can also configure Lambda to send an invocation record to another service. Lambda supports the
following destinations (p. 103) for asynchronous invocation.
102
AWS Lambda Developer Guide
Configuring error handling for asynchronous invocation
The invocation record contains details about the request and response in JSON format. You can configure
separate destinations for events that are processed successfully, and events that fail all processing
attempts. Alternatively, you can configure an SQS queue or SNS topic as a dead-letter queue (p. 106)
for discarded events. For dead-letter queues, Lambda only sends the content of the event, without
details about the response.
Sections
• Configuring error handling for asynchronous invocation (p. 103)
• Configuring destinations for asynchronous invocation (p. 103)
• Asynchronous invocation configuration API (p. 105)
• AWS Lambda function dead-letter queues (p. 106)
• Maximum age of event – The maximum amount of time Lambda retains an event in the
asynchronous event queue, up to 6 hours.
• Retry attempts – The number of times Lambda retries when the function returns an error,
between 0 and 2.
5. Choose Save.
When an invocation event exceeds the maximum age or fails all retry attempts, Lambda discards it. To
retain a copy of discarded events, configure a failed-event destination.
The following example shows a function that is processing asynchronous invocations. When the function
returns a success response or exits without throwing an error, Lambda sends a record of the invocation
to an EventBridge event bus. When an event fails all processing attempts, Lambda sends an invocation
record to an Amazon SQS queue.
103
AWS Lambda Developer Guide
Configuring destinations for asynchronous invocation
To send events to a destination, your function needs additional permissions. Add a policy with the
required permissions to your function's execution role (p. 37). Each destination service requires a
different permission, as follows:
104
AWS Lambda Developer Guide
Asynchronous invocation configuration API
• On failure – Send a record when the event fails all processing attempts or exceeds the maximum
age.
• On success – Send a record when the function successfully processes an asynchronous invocation.
6. For Destination type, choose the type of resource that receives the invocation record.
7. For Destination, choose a resource.
8. Choose Save.
When an invocation matches the condition, Lambda sends a JSON document with details about the
invocation to the destination. The following example shows an invocation record for an event that failed
three processing attempts due to a function error.
{
"version": "1.0",
"timestamp": "2019-11-14T[Link].568Z",
"requestContext": {
"requestId": "e4b46cbf-b738-xmpl-8880-a18cdf61200e",
"functionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:
$LATEST",
"condition": "RetriesExhausted",
"approximateInvokeCount": 3
},
"requestPayload": {
"ORDER_IDS": [
"9e07af03-ce31-4ff3-xmpl-36dce652cb4f",
"637de236-e7b2-464e-xmpl-baf57f86bb53",
"a81ddca6-2c35-45c7-xmpl-c3a03a31ed15"
]
},
"responseContext": {
"statusCode": 200,
"executedVersion": "$LATEST",
"functionError": "Unhandled"
},
"responsePayload": {
"errorMessage": "RequestId: e4b46cbf-b738-xmpl-8880-a18cdf61200e Process exited
before completing request"
}
}
The invocation record contains details about the event, the response, and the reason that the record was
sent.
• PutFunctionEventInvokeConfig
• GetFunctionEventInvokeConfig
• UpdateFunctionEventInvokeConfig
• ListFunctionEventInvokeConfigs
• DeleteFunctionEventInvokeConfig
105
AWS Lambda Developer Guide
Dead-letter queues
To configure asynchronous invocation with the AWS CLI, use the put-function-event-invoke-
config command. The following example configures a function with a maximum event age of 1 hour
and no retries.
If you don't have a queue or topic, create one. Choose the target type that matches your use case.
• Amazon SQS queue – A queue holds failed events until they're retrieved. You can retrieve events
manually, or you can configure Lambda to read from the queue (p. 304) and invoke a function.
106
AWS Lambda Developer Guide
Dead-letter queues
To send events to a queue or topic, your function needs additional permissions. Add a policy with the
required permissions to your function's execution role (p. 37).
If the target queue or topic is encrypted with a customer managed key, the execution role must also be a
user in the key's resource-based policy.
After creating the target and updating your function's execution role, add the dead-letter queue to your
function. You can configure multiple functions to send events to the same target.
To configure a dead-letter queue with the AWS CLI, use the update-function-configuration
command.
Lambda sends the event to the dead-letter queue as-is, with additional information in attributes. You
can use this information to identify the error that the function returned, or to correlate the event with
logs or an AWS X-Ray trace.
• RequestID (String) – The ID of the invocation request. Request IDs appear in function logs. You can
also use the X-Ray SDK to record the request ID on an attribute in the trace. You can then search for
traces by request ID in the X-Ray console. For an example, see the error processor sample (p. 327).
• ErrorCode (Number) – The HTTP status code.
• ErrorMessage (String) – The first 1 KB of the error message.
107
AWS Lambda Developer Guide
Dead-letter queues
If Lambda can't send a message to the dead-letter queue, it deletes the event and emits the
DeadLetterErrors (p. 478) metric. This can happen because of lack of permissions, or if the total size of
the message exceeds the limit for the target queue or topic. For example, if an Amazon SNS notification
with a body close to 256 KB triggers a function that results in an error, the additional event data added
by Amazon SNS, combined with the attributes added by Lambda, can cause the message to exceed the
maximum size allowed in the dead-letter queue.
If you're using Amazon SQS as an event source, configure a dead-letter queue on the Amazon SQS queue
itself and not on the Lambda function. For more information, see Using AWS Lambda with Amazon
SQS (p. 304).
108
AWS Lambda Developer Guide
Event source mapping
An event source mapping uses permissions in the function's execution role (p. 37) to read and manage
items in the event source. Permissions, event structure, settings, and polling behavior vary by event
source. For more information, see the linked topic for the service that you use as an event source.
To manage event source mappings with the AWS CLI or AWS SDK, use the following API actions:
The following example uses the AWS CLI to map a function named my-function to a DynamoDB
stream that is specified by its Amazon Resource Name (ARN), with a batch size of 500.
Event source mappings read items from a stream or queue in batches. They include multiple items in the
event that your function receives. You can configure the size of the batch that the event source mapping
sends to your function, up to a maximum that varies by service. The number of items in the event can be
smaller than the batch size if there aren't enough items available, or if the batch is too large to send in
one event and has to be split up.
109
AWS Lambda Developer Guide
Event source mapping
The following example shows an event source mapping that reads from a Kinesis stream. If a batch of
events fails all processing attempts, the event source mapping sends details about the batch to an SQS
queue.
The event batch is the event that Lambda sends to the function. It is a batch of records or messages
compiled from the items that the event source mapping reads from a stream or queue. Batch size and
other settings only apply to the event batch.
For streams, an event source mapping creates an iterator for each shard in the stream and processes
items in each shard in order. You can configure the event source mapping to read only new items that
appear in the stream, or to start with older items. Processed items aren't removed from the stream and
can be processed by other functions or consumers.
By default, if your function returns an error, the entire batch is reprocessed until the function succeeds,
or the items in the batch expire. To ensure in-order processing, processing for the affected shard is
paused until the error is resolved. You can configure the event source mapping to discard old events,
110
AWS Lambda Developer Guide
Event source mapping
restrict the number of retries, or process multiple batches in parallel. If you process multiple batches in
parallel, in-order processing is still guaranteed for each partition key, but multiple partition keys in the
same shard are processed simultaneously.
You can also configure the event source mapping to send an invocation record to another service when it
discards an event batch. Lambda supports the following destinations (p. 103) for event source mappings.
The invocation record contains details about the failed event batch in JSON format.
{
"requestContext": {
"requestId": "c9b8fa9f-5a7f-xmpl-af9c-0c604cde93a5",
"functionArn": "arn:aws:lambda:us-east-2:123456789012:function:myfunction",
"condition": "RetryAttemptsExhausted",
"approximateInvokeCount": 1
},
"responseContext": {
"statusCode": 200,
"executedVersion": "$LATEST",
"functionError": "Unhandled"
},
"version": "1.0",
"timestamp": "2019-11-14T[Link].021Z",
"KinesisBatchInfo": {
"shardId": "shardId-000000000001",
"startSequenceNumber": "49601189658422359378836298521827638475320189012309704722",
"endSequenceNumber": "49601189658422359378836298522902373528957594348623495186",
"approximateArrivalOfFirstRecord": "2019-11-14T[Link].835Z",
"approximateArrivalOfLastRecord": "2019-11-14T[Link].580Z",
"batchSize": 500,
"streamArn": "arn:aws:kinesis:us-east-2:123456789012:stream/mystream"
}
}
Lambda also supports in-order processing for FIFO (first-in, first-out) queues (p. 304), scaling up to
the number of active message groups. For standard queues, items aren't necessarily processed in order.
Lambda scales up to process a standard queue as quickly as possible. When an error occurs, batches
are returned to the queue as individual items and might be processed in a different grouping than the
original batch. Occasionally, the event source mapping might receive the same item from the queue
twice, even if no function error occurred. Lambda deletes items from the queue after they're processed
successfully. You can configure the source queue to send items to a dead-letter queue if they can't be
processed.
For information about services that invoke Lambda functions directly, see Using AWS Lambda with other
services (p. 166).
111
AWS Lambda Developer Guide
Function states
If you configure your function to connect to a virtual private cloud (VPC), the process can take longer.
When you first connect a function to a VPC, Lambda provisions network interfaces, which takes about
a minute. To communicate the current state of your function, Lambda includes additional fields in the
function configuration (p. 700) document that is returned by several Lambda API actions.
When you create a function, the function is initially in the Pending state. When the function is ready to
be invoked, the state changes from Pending to Active. While the state is Pending, invocations and
other API actions that operate on the function return an error. If you build automation around creating
and updating functions, wait for the function to become active before performing additional actions that
operate on the function.
You can use the Lambda API to get information about a function's state. State information is included in
the FunctionConfiguration (p. 700) document returned by several API actions. To view the function's
state with the AWS CLI, use the get-function-configuration command.
The StateReason and StateReasonCode contain additional information about the state when it is not
Active. The following operations fail while function creation is pending:
When you update a function's configuration, the update can trigger an asynchronous operation to
provision resources. While this is in progress, you can invoke the function, but other operations on
the function fail. Invocations that occur while the update is in progress run against the previous
configuration. The function's state is Active, but its LastUpdateStatus is InProgress.
{
"FunctionName": "my-function",
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function",
112
AWS Lambda Developer Guide
Function states
"Runtime": "nodejs12.x",
"VpcConfig": {
"SubnetIds": [
"subnet-071f712345678e7c8",
"subnet-07fd123456788a036",
"subnet-0804f77612345cacf"
],
"SecurityGroupIds": [
"sg-085912345678492fb"
],
"VpcId": "vpc-08e1234569e011e83"
},
"State": "Active",
"LastUpdateStatus": "InProgress",
...
}
For example, when you connect your function to a virtual private cloud (VPC), Lambda provisions an
elastic network interface for each subnet. This process can leave your function in a pending state for a
minute or so. Lambda also reclaims network interfaces that are not in use, placing your function in an
Inactive state. When the function is inactive, an invocation causes it to enter the Pending state while
network access is restored. The invocation that triggers restoration, and further invocations while the
operation is pending, fail with ResourceNotReadyException.
If Lambda encounters an error when restoring a function's network interface, the function goes back to
the Inactive state. The next invocation can trigger another attempt. For some configuration errors,
Lambda waits at least 5 minutes before attempting to create another network interface. These errors
have the following LastUpdateStatusReasonCode values:
For more information on how states work with VPC connectivity, see Configuring a Lambda function to
access resources in a VPC (p. 88).
113
AWS Lambda Developer Guide
Function scaling
Your functions' concurrency is the number of instances that serve requests at a given time. For an initial
burst of traffic, your functions' cumulative concurrency in a Region can reach an initial level of between
500 and 3000, which varies per Region.
After the initial burst, your functions' concurrency can scale by an additional 500 instances each
minute. This continues until there are enough instances to serve all requests, or until a concurrency
limit is reached. When requests come in faster than your function can scale, or when your function is at
maximum concurrency, additional requests fail with a throttling error (429 status code).
The following example shows a function processing a spike in traffic. As invocations increase
exponentially, the function scales up. It initializes a new instance for any request that can't be routed to
an available instance. When the burst concurrency limit is reached, the function starts to scale linearly.
If this isn't enough concurrency to serve all requests, additional requests are throttled and should be
retried.
114
AWS Lambda Developer Guide
Function scaling
Legend
• Function instances
• Open requests
• Throttling possible
The function continues to scale until the account's concurrency limit for the function's Region is reached.
The function catches up to demand, requests subside, and unused instances of the function are stopped
after being idle for some time. Unused instances are frozen while they're waiting for requests and don't
incur any charges.
115
AWS Lambda Developer Guide
Function scaling
The regional concurrency limit starts at 1,000. You can increase the limit by submitting a request in the
Support Center console. To allocate capacity on a per-function basis, you can configure functions with
reserved concurrency (p. 67). Reserved concurrency creates a pool that can only be used by its function,
and also prevents its function from using unreserved concurrency.
When your function scales up, the first request served by each instance is impacted by the time it
takes to load and initialize your code. If your initialization code (p. 22) takes a long time, the impact on
average and percentile latency can be significant. To enable your function to scale without fluctuations
in latency, use provisioned concurrency (p. 67). The following example shows a function with provisioned
concurrency processing a spike in traffic.
Legend
• Function instances
• Open requests
• Provisioned concurrency
• Standard concurrency
116
AWS Lambda Developer Guide
Function scaling
When provisioned concurrency is allocated, the function scales with the same burst behavior as standard
concurrency. After it's allocated, provisioned concurrency serves incoming requests with very low latency.
When all provisioned concurrency is in use, the function scales up normally to handle any additional
requests.
Application Auto Scaling takes this a step further by providing autoscaling for provisioned concurrency.
With Application Auto Scaling, you can create a target tracking scaling policy that adjusts provisioned
concurrency levels automatically, based on the utilization metric that Lambda emits. Use the Application
Auto Scaling API (p. 72) to register an alias as a scalable target and create a scaling policy.
In the following example, a function scales between a minimum and maximum amount of provisioned
concurrency based on utilization. When the number of open requests increases, Application Auto
Scaling increases provisioned concurrency in large steps until it reaches the configured maximum. The
function continues to scale on standard concurrency until utilization starts to drop. When utilization is
consistently low, Application Auto Scaling decreases provisioned concurrency in smaller periodic steps.
117
AWS Lambda Developer Guide
Function scaling
Legend
• Function instances
• Open requests
• Provisioned concurrency
• Standard concurrency
When you invoke your function asynchronously, by using an event source mapping or another AWS
service, scaling behavior varies. For example, event source mappings that read from a stream are limited
by the number of shards in the stream. Scaling capacity that is unused by an event source is available for
use by other clients and event sources. For more information, see the following topics.
You can monitor concurrency levels in your account by using the following metrics:
Concurrency metrics
• ConcurrentExecutions
• UnreservedConcurrentExecutions
• ProvisionedConcurrentExecutions
• ProvisionedConcurrencyInvocations
• ProvisionedConcurrencySpilloverInvocations
• ProvisionedConcurrencyUtilization
For more information, see Working with AWS Lambda function metrics (p. 478).
118
AWS Lambda Developer Guide
Error handling
Issues with the request, caller, or account can cause invocation errors. Invocation errors include an error
type and status code in the response that indicate the cause of the error.
• Request – The request event is too large or isn't valid JSON, the function doesn't exist, or a parameter
value is the wrong type.
• Caller – The user or service doesn't have permission to invoke the function.
• Account – The maximum number of function instances are already running, or requests are being
made too quickly.
Clients such as the AWS CLI and the AWS SDK retry on client timeouts, throttling errors (429), and
other errors that aren't caused by a bad request (500 series). For a full list of invocation errors, see
Invoke (p. 592).
Function errors occur when your function code or the runtime that it uses return an error.
Unlike invocation errors, function errors don't cause Lambda to return a 400-series or 500-series status
code. If the function returns an error, Lambda indicates this by including a header named X-Amz-
Function-Error, and a JSON-formatted response with the error message and other details. For
examples of function errors in each language, see the following topics.
When you invoke a function directly, you determine the strategy for handling errors. You can retry, send
the event to a queue for debugging, or ignore the error. Your function's code might have run completely,
partially, or not at all. If you retry, ensure that your function's code can handle the same event multiple
times without causing duplicate transactions or other unwanted side effects.
When you invoke a function indirectly, you need to be aware of the retry behavior of the invoker and any
service that the request encounters along the way. This includes the following scenarios.
119
AWS Lambda Developer Guide
Error handling
• Asynchronous invocation – Lambda retries function errors twice. If the function doesn't have enough
capacity to handle all incoming requests, events might wait in the queue for hours or days to be sent
to the function. You can configure a dead-letter queue on the function to capture events that weren't
successfully processed. For more information, see Asynchronous invocation (p. 101).
• Event source mappings – Event source mappings that read from streams retry the entire batch of
items. Repeated errors block processing of the affected shard until the error is resolved or the items
expire. To detect stalled shards, you can monitor the Iterator Age (p. 478) metric.
For event source mappings that read from a queue, you determine the length of time between retries
and destination for failed events by configuring the visibility timeout and redrive policy on the source
queue. For more information, see AWS Lambda event source mappings (p. 109) and the service-
specific topics under Using AWS Lambda with other services (p. 166).
• AWS services – AWS services can invoke your function synchronously (p. 99) or asynchronously. For
synchronous invocation, the service decides whether to retry. Services like API Gateway and Elastic
Load Balancing, which proxy requests from an upstream user or client, can also choose to relay the
error response back to the requestor.
For asynchronous invocation, the behavior is the same as when you invoke the function
asynchronously. For more information, see the service-specific topics under Using AWS Lambda with
other services (p. 166) and the invoking service's documentation.
• Other accounts and clients – When you grant access to other accounts, you can use resource-based
policies (p. 41) to restrict the services or resources they can configure to invoke your function. To
protect your function from being overloaded, consider putting an API layer in front of your function
with Amazon API Gateway (p. 170).
To help you deal with errors in Lambda applications, Lambda integrates with services like Amazon
CloudWatch and AWS X-Ray. You can use a combination of logs, metrics, alarms, and tracing to quickly
detect and identify issues in your function code, API, or other resources that support your application.
For more information, see Monitoring and troubleshooting Lambda applications (p. 476).
For a sample application that uses a CloudWatch Logs subscription, X-Ray tracing, and a Lambda
function to detect and process errors, see Error processor sample application for AWS Lambda (p. 327).
120
AWS Lambda Developer Guide
Mobile SDK for Android
When you invoke a function from a mobile application, you choose the event structure, invocation
type (p. 98), and permission model. You can use aliases (p. 79) to enable seamless updates to your
function code, but otherwise the function and application are tightly coupled. As you add more
functions, you can create an API layer to decouple your function code from your front-end clients and
improve performance.
To create a fully-featured web API for your mobile and web applications, use Amazon API Gateway.
With API Gateway, you can add custom authorizers, throttle requests, and cache results for all of your
functions. For more information, see Using AWS Lambda with Amazon API Gateway (p. 170).
Topics
• Tutorial: Using AWS Lambda with the Mobile SDK for Android (p. 121)
• Sample function code (p. 127)
The mobile application retrieves AWS credentials from an Amazon Cognito identity pool and uses them
to invoke a Lambda function with an event that contains request data. The function processes the
request and returns a response to the front-end.
121
AWS Lambda Developer Guide
Tutorial
Prerequisites
This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda
console. If you haven't already, follow the instructions in Getting started with AWS Lambda (p. 3) to
create your first Lambda function.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate:
For long commands, an escape character (\) is used to split a command over multiple lines.
On Linux and macOS, use your preferred shell and package manager. On Windows 10, you can install the
Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
The AWSLambdaBasicExecutionRole policy has the permissions that the function needs to write logs to
CloudWatch Logs.
Example [Link]
122
AWS Lambda Developer Guide
Tutorial
For more information about IAM roles, see IAM roles in the IAM User Guide. For more information about
Amazon Cognito services, see the Amazon Cognito product detail page.
• The identity pool you are creating must allow access to unauthenticated identities because our
example mobile application does not require a user log in. Therefore, make sure to select the
Enable access to unauthenticated identities option.
• Add the following statement to the permission policy associated with the unauthenticated
identities.
{
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": [
"arn:aws:lambda:us-
east-1:123456789012:function:AndroidBackendLambdaFunction"
]
}
123
AWS Lambda Developer Guide
Tutorial
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"mobileanalytics:PutEvents",
"cognito-sync:*"
],
"Resource":[
"*"
]
},
{
"Effect":"Allow",
"Action":[
"lambda:invokefunction"
],
"Resource":[
"arn:aws:lambda:us-east-1:account-
id:function:AndroidBackendLambdaFunction"
]
}
]
}
For instructions about how to create an identity pool, log in to the Amazon Cognito console and
follow the New Identity Pool wizard.
3. Note the identity pool ID. You specify this ID in your mobile application you create in the next
section. The app uses this ID when it sends request to Amazon Cognito to request for temporary
security credentials.
1. Create a new Android project called AndroidEventGenerator using the following configuration:
compile '[Link]:aws-android-sdk-core:2.2.+'
compile '[Link]:aws-android-sdk-lambda:2.2.+'
3. Build the project so that the required dependencies are downloaded, as needed.
4. In the Android application manifest ([Link]), add the following permissions so
that your application can connect to the Internet. You can add them just before the </manifest>
end tag.
124
AWS Lambda Developer Guide
Tutorial
import [Link].*;
import [Link];
import [Link];
6. In the package section, add the following two classes (RequestClass and ResponseClass). Note
that the POJO is same as the POJO you created in your Lambda function in the preceding section.
• RequestClass. The instances of this class act as the POJO (Plain Old Java Object) for event data
which consists of first and last name. If you are using Java example for your Lambda function
you created in the preceding section, this POJO is same as the POJO you created in your Lambda
function code.
package [Link]....lambdaeventgenerator;
public class RequestClass {
String firstName;
String lastName;
public RequestClass() {
}
}
• ResponseClass
package [Link]....lambdaeventgenerator;
public class ResponseClass {
String greetings;
125
AWS Lambda Developer Guide
Tutorial
public ResponseClass() {
}
}
7. In the same package, create interface called MyInterface for invoking the
AndroidBackendLambdaFunction Lambda function.
package [Link].....lambdaeventgenerator;
import [Link];
public interface MyInterface {
/**
* Invoke the Lambda function "AndroidBackendLambdaFunction".
* The function name is the method name.
*/
@LambdaFunction
ResponseClass AndroidBackendLambdaFunction(RequestClass request);
The @LambdaFunction annotation in the code maps the specific client method to the same-name
Lambda function.
8. To keep the application simple, we are going to add code to invoke the Lambda function in the
onCreate() event handler. In MainActivity, add the following code toward the end of the
onCreate() code.
// Create the Lambda proxy object with a default Json data binder.
// You can provide your own data binder by implementing
// LambdaDataBinder.
final MyInterface myInterface = [Link]([Link]);
@Override
protected void onPostExecute(ResponseClass result) {
if (result == null) {
return;
}
126
AWS Lambda Developer Guide
Sample code
// Do a toast
[Link]([Link], [Link](),
Toast.LENGTH_LONG).show();
}
}.execute(request);
Topics
• [Link] (p. 127)
• Java (p. 127)
[Link]
The following example uses data to generate a string response.
Example [Link]
Zip up the sample code to create a deployment package. For instructions, see AWS Lambda deployment
package in [Link] (p. 336).
Java
The following example uses data to generate a string response.
In the code, the handler (myHandler) uses the RequestClass and ResponseClass types for the
input and output. The code provides implementation for these types.
Example [Link]
package example;
import [Link];
127
AWS Lambda Developer Guide
Sample code
public RequestClass() {
}
}
public ResponseClass() {
}
Dependencies
• aws-lambda-java-core
Build the code with the Lambda library dependencies to create a deployment package. For instructions,
see AWS Lambda deployment package in Java (p. 389).
128
AWS Lambda Developer Guide
Amazon Linux
• Image – amzn-ami-hvm-2018.03.0.20181129-x86_64-gp2
• Linux kernel – 4.14.171-105.231.amzn1.x86_64
Amazon Linux 2
• Image – Custom
• Linux kernel – 4.14.165-102.205.amzn2.x86_64
When your function is invoked, Lambda attempts to re-use the execution environment from a previous
invocation if one is available. This saves time preparing the execution environment, and allows you to
save resources like database connections and temporary files in the execution context (p. 131) to avoid
creating them every time your function runs.
A runtime can support a single version of a language, multiple versions of a language, or multiple
languages. Runtimes specific to a language or framework version are deprecated (p. 132) when the
version reaches end of life.
[Link] runtimes
Python runtimes
129
AWS Lambda Developer Guide
Ruby runtimes
Java runtimes
Go runtimes
.NET runtimes
To use other languages in Lambda, you can implement a custom runtime (p. 133). The Lambda
execution environment provides a runtime interface (p. 136) for getting invocation events and sending
responses. You can deploy a custom runtime alongside your function code, or in a layer (p. 83).
Custom runtime
Topics
• AWS Lambda execution context (p. 131)
• Runtime support policy (p. 132)
• Custom AWS Lambda runtimes (p. 133)
• AWS Lambda runtime interface (p. 136)
• Tutorial – Publishing a custom runtime (p. 139)
130
AWS Lambda Developer Guide
Execution context
It takes time to set up an execution context and do the necessary "bootstrapping", which adds some
latency each time the Lambda function is invoked. You typically see this latency when a Lambda
function is invoked for the first time or after it has been updated because AWS Lambda tries to reuse the
execution context for subsequent invocations of the Lambda function.
After a Lambda function is executed, AWS Lambda maintains the execution context for some time in
anticipation of another Lambda function invocation. In effect, the service freezes the execution context
after a Lambda function completes, and thaws the context for reuse, if AWS Lambda chooses to reuse
the context when the Lambda function is invoked again. This execution context reuse approach has the
following implications:
• Objects declared outside of the function's handler method remain initialized, providing additional
optimization when the function is invoked again. For example, if your Lambda function establishes
a database connection, instead of reestablishing the connection, the original connection is used in
subsequent invocations. We suggest adding logic in your code to check if a connection exists before
creating one.
• Each execution context provides 512 MB of additional disk space in the /tmp directory. The directory
content remains when the execution context is frozen, providing transient cache that can be used for
multiple invocations. You can add extra code to check if the cache has the data that you stored. For
information on deployment limits, see AWS Lambda limits (p. 34).
• Background processes or callbacks initiated by your Lambda function that did not complete when the
function ended resume if AWS Lambda chooses to reuse the execution context. You should make sure
any background processes or callbacks in your code are complete before the code exits.
When you write your Lambda function code, do not assume that AWS Lambda automatically reuses
the execution context for subsequent function invocations. Other factors may dictate a need for AWS
Lambda to create a new execution context, which can lead to unexpected results, such as database
connection failures.
131
AWS Lambda Developer Guide
Runtime support policy
Deprecation occurs in two phases. During the first phase, you can no longer create functions that use
the deprecated runtime. For at least 30 days, you can continue to update existing functions that use the
deprecated runtime. After this period, both function creation and updates are disabled permanently.
However, the function continues to be available to process invocation events.
Note
Python 2.7 reached end-of-life on January 1st, 2020. However, the Python 2.7 runtime is still
supported and is not scheduled to be deprecated at this time. For details, see Continued support
for Python 2.7 on AWS Lambda.
Deprecated runtimes
In most cases, the end-of-life date of a language version or operating system is known well in advance.
If you have functions running on a runtime that will be deprecated in the next 60 days, Lambda notifies
you by email that you should prepare by migrating your function to a supported runtime. In some cases,
such as security issues that require a backwards-incompatible update, or software that doesn't support a
long-term support (LTS) schedule, advance notice might not be possible.
• [Link] – [Link]
• Python – [Link]
• Ruby – [Link]
• Java – [Link] and [Link]/corretto
• Go – [Link]
• .NET Core – [Link]
After a runtime is deprecated, Lambda might retire it completely at any time by disabling invocation.
Deprecated runtimes aren't eligible for security updates or technical support. Before retiring a runtime,
Lambda sends additional notifications to affected customers. No runtimes are scheduled to be retired at
this time.
132
AWS Lambda Developer Guide
Custom runtimes
A runtime is responsible for running the function's setup code, reading the handler name from an
environment variable, and reading invocation events from the Lambda runtime API. The runtime passes
the event data to the function handler, and posts the response from the handler back to Lambda.
Your custom runtime runs in the standard Lambda execution environment (p. 129). It can be a shell
script, a script in a language that's included in Amazon Linux, or a binary executable file that's compiled
in Amazon Linux.
To get started with custom runtimes, see Tutorial – Publishing a custom runtime (p. 139). You can also
explore a custom runtime implemented in C++ at awslabs/aws-lambda-cpp on GitHub.
Topics
• Using a custom runtime (p. 133)
• Building a custom runtime (p. 133)
Example [Link]
.
### bootstrap
### [Link]
If there's a file named bootstrap in your deployment package, Lambda executes that file. If not,
Lambda looks for a runtime in the function's layers. If the bootstrap file isn't found or isn't executable,
your function returns an error upon invocation.
Example bootstrap
#!/bin/sh
cd $LAMBDA_TASK_ROOT
./node-v11.1.0-linux-x64/bin/node [Link]
Your runtime code is responsible for completing some initialization tasks. Then it processes
invocation events in a loop until it's terminated. The initialization tasks run once per instance of the
function (p. 131) to prepare the environment to handle invocations.
Initialization tasks
• Retrieve settings – Read environment variables to get details about the function and environment.
133
AWS Lambda Developer Guide
Building a custom runtime
• _HANDLER – The location to the handler, from the function's configuration. The standard format is
[Link], where file is the name of the file without an extension, and method is the name of
a method or function that's defined in the file.
• LAMBDA_TASK_ROOT – The directory that contains the function code.
• AWS_LAMBDA_RUNTIME_API – The host and port of the runtime API.
See Runtime environment variables (p. 62) for a full list of available variables.
• Initialize the function – Load the handler file and run any global or static code that it contains.
Functions should create static resources like SDK clients and database connections once, and reuse
them for multiple invocations.
• Handle errors – If an error occurs, call the initialization error (p. 137) API and exit immediately.
Initialization counts towards billed execution time and timeout. When an execution triggers the
initialization of a new instance of your function, you can see the initialization time in the logs and AWS
X-Ray trace (p. 314).
Example log
While it runs, a runtime uses the Lambda runtime interface (p. 136) to manage incoming events and
report errors. After completing initialization tasks, the runtime processes incoming events in a loop. In
your runtime code, perform the following steps in order.
Processing tasks
• Get an event – Call the next invocation (p. 136) API to get the next event. The response body
contains the event data. Response headers contain the request ID and other information.
• Propagate the tracing header – Get the X-Ray tracing header from the Lambda-Runtime-Trace-Id
header in the API response. Set the _X_AMZN_TRACE_ID environment variable locally with the same
value. The X-Ray SDK uses this value to connect trace data between services.
• Create a context object – Create an object with context information from environment variables and
headers in the API response.
• Invoke the function handler – Pass the event and context object to the handler.
• Handle the response – Call the invocation response (p. 137) API to post the response from the
handler.
134
AWS Lambda Developer Guide
Building a custom runtime
• Handle errors – If an error occurs, call the invocation error (p. 137) API.
• Cleanup – Release unused resources, send data to other services, or perform additional tasks before
getting the next event.
You can include the runtime in your function's deployment package, or distribute the runtime separately
in a function layer. For an example walkthrough, see Tutorial – Publishing a custom runtime (p. 139).
135
AWS Lambda Developer Guide
Runtime interface
The OpenAPI specification for the runtime API version 2018-06-01 is available here: [Link]
Runtimes get an endpoint from the AWS_LAMBDA_RUNTIME_API environment variable, add the API
version, and use the following resource paths to interact with the API.
Example Request
curl "[Link]
Resources
• Next invocation (p. 136)
• Invocation response (p. 137)
• Invocation error (p. 137)
• Initialization error (p. 137)
Next invocation
Path – /runtime/invocation/next
Method – GET
Retrieves an invocation event. The response body contains the payload from the invocation, which is
a JSON document that contains event data from the function trigger. The response headers contain
additional data about the invocation.
Response headers
• Lambda-Runtime-Aws-Request-Id – The request ID, which identifies the request that triggered the
function invocation.
136
AWS Lambda Developer Guide
Invocation response
Call /runtime/invocation/next to get the invocation event, and pass it to the function handler for
processing. Do not set a timeout on the GET call. Between when Lambda bootstraps the runtime and
when the runtime has an event to return, the runtime process may be frozen for several seconds.
The request ID tracks the invocation within Lambda. Use it to specify the invocation when you send the
response.
The tracing header contains the trace ID, parent ID, and sampling decision. If the request is
sampled, the request was sampled by Lambda or an upstream service. The runtime should set the
_X_AMZN_TRACE_ID with the value of the header. The X-Ray SDK reads this to get the IDs and
determine whether to trace the request.
Invocation response
Path – /runtime/invocation/AwsRequestId/response
Method – POST
Sends an invocation response to Lambda. After the runtime invokes the function handler, it posts the
response from the function to the invocation response path. For synchronous invocations, Lambda then
sends the response back to the client.
REQUEST_ID=156cb537-e2d4-11e8-9b34-d36013741fb9
curl -X POST "[Link]
response" -d "SUCCESS"
Invocation error
Path – /runtime/invocation/AwsRequestId/error
Method – POST
If the function returns an error, the runtime formats the error into a JSON document, and posts it to the
invocation error path.
{
"errorMessage" : "Error parsing event data.",
"errorType" : "InvalidEventDataException"
}
REQUEST_ID=156cb537-e2d4-11e8-9b34-d36013741fb9
ERROR="{\"errorMessage\" : \"Error parsing event data.\", \"errorType\" :
\"InvalidEventDataException\"}"
curl -X POST "[Link]
error" -d "$ERROR" --header "Lambda-Runtime-Function-Error-Type: Unhandled"
Initialization error
Path – /runtime/init/error
137
AWS Lambda Developer Guide
Initialization error
Method – POST
If the runtime encounters an error during initialization, it posts an error message to the initialization
error path.
138
AWS Lambda Developer Guide
Tutorial – Custom runtime
Prerequisites
This tutorial assumes that you have some knowledge of basic Lambda operations and the Lambda
console. If you haven't already, follow the instructions in Getting started with AWS Lambda (p. 3) to
create your first Lambda function.
To follow the procedures in this guide, you will need a command line terminal or shell to run commands.
Commands are shown in listings preceded by a prompt symbol ($) and the name of the current directory,
when appropriate:
For long commands, an escape character (\) is used to split a command over multiple lines.
On Linux and macOS, use your preferred shell and package manager. On Windows 10, you can install the
Windows Subsystem for Linux to get a Windows-integrated version of Ubuntu and Bash.
You need an IAM role to create a Lambda function. The role needs permission to send logs to
CloudWatch Logs and access the AWS services that your function uses. If you don't have a role for
function development, create one now.
The AWSLambdaBasicExecutionRole policy has the permissions that the function needs to write
logs to CloudWatch Logs.
Create a function
Create a Lambda function with a custom runtime. This example includes two files, a runtime bootstrap
file, and a function handler. Both are implemented in Bash.
The runtime loads a function script from the deployment package. It uses two variables to locate the
script. LAMBDA_TASK_ROOT tells it where the package was extracted, and _HANDLER includes the name
of the script.
Example bootstrap
#!/bin/sh
139
AWS Lambda Developer Guide
Create a function
# Processing
while true
do
HEADERS="$(mktemp)"
# Get an event. The HTTP request will block until one is received
EVENT_DATA=$(curl -sS -LD "$HEADERS" -X GET "[Link]
runtime/invocation/next")
After loading the script, the runtime processes events in a loop. It uses the runtime API to retrieve an
invocation event from Lambda, passes the event to the handler, and posts the response back to Lambda.
To get the request ID, the runtime saves the headers from the API response to a temporary file, and
reads the Lambda-Runtime-Aws-Request-Id header from the file.
Note
Runtimes have additional responsibilities, including error handling, and providing context
information to the handler. For details, see Building a custom runtime (p. 133).
The script defines a handler function that takes event data, logs it to stderr, and returns it.
Example [Link]
function handler () {
EVENT_DATA=$1
echo "$EVENT_DATA" 1>&2;
RESPONSE="Echoing request: '$EVENT_DATA'"
echo $RESPONSE
}
runtime-tutorial
# bootstrap
# [Link]
140
AWS Lambda Developer Guide
Create a layer
Create a layer
To separate the runtime code from the function code, create a layer that only contains the runtime.
Layers let you develop your function's dependencies independently, and can reduce storage usage when
you use the same layer with multiple functions.
141
AWS Lambda Developer Guide
Update the function
This adds the runtime to the function in the /opt directory. Lambda uses this runtime, but only if you
remove it from the function's deployment package. Update the function code to only include the handler
script.
Invoke the function to verify that it works with the runtime layer.
142
AWS Lambda Developer Guide
Share the layer
Example bootstrap
#!/bin/sh
You can add multiple statements that each grant permission to a single account, accounts in an
organization, or all accounts.
Clean up
Delete each version of the layer.
Because the function holds a reference to version 2 of the layer, it still exists in Lambda. The function
continues to work, but functions can no longer be configured to use the deleted version. If you then
modify the list of layers on the function, you must specify a new version or omit the deleted layer.
143
AWS Lambda Developer Guide
Clean up
144
AWS Lambda Developer Guide
The AWS Serverless Application Repository provides a collection of Lambda applications that you
can deploy in your account with a few clicks. The repository includes both ready-to-use applications
and samples that you can use as a starting point for your own projects. You can also submit your own
projects for inclusion.
AWS CloudFormation enables you to create a template that defines your application's resources and lets
you manage the application as a stack. You can more safely add or modify resources in your application
stack. If any part of an update fails, AWS CloudFormation automatically rolls back to the previous
configuration. With AWS CloudFormation parameters, you can create multiple environments for your
application from the same template. AWS SAM (p. 32) extends AWS CloudFormation with a simplified
syntax focused on Lambda application development.
The AWS CLI (p. 32) and SAM CLI (p. 32) are command line tools for managing Lambda application
stacks. In addition to commands for managing application stacks with the AWS CloudFormation API, the
AWS CLI supports higher-level commands that simplify tasks like uploading deployment packages and
updating templates. The AWS SAM CLI provides additional functionality, including validating templates
and testing locally.
Topics
• Managing applications in the AWS Lambda console (p. 146)
• Creating an application with continuous delivery in the Lambda console (p. 149)
• Rolling deployments for Lambda functions (p. 158)
• Common Lambda application types and use cases (p. 160)
• Best Practices for Working with AWS Lambda Functions (p. 163)
145
AWS Lambda Developer Guide
Manage applications
• AWS CloudFormation template or SAM template – The template that defines your application.
• Resources – The AWS resources that are defined in your application's template. To manage your
application's Lambda functions, choose a function name from the list.
Monitoring applications
The Monitoring tab shows an Amazon CloudWatch dashboard with aggregate metrics for the resources
in your application.
By default, the Lambda console shows a basic dashboard. You can customize this page by defining
custom dashboards in your application template. When your template includes one or more dashboards,
the page shows your dashboards instead of the default dashboard. You can switch between dashboards
with the drop-down menu on the top right of the page.
146
AWS Lambda Developer Guide
Custom monitoring dashboards
Resources:
MyDashboard:
Type: AWS::CloudWatch::Dashboard
Properties:
DashboardName: my-dashboard
DashboardBody: |
{
"widgets": [
{
"type": "metric",
"width": 12,
"height": 6,
"properties": {
"metrics": [
[
"AWS/Lambda",
"Invocations",
"FunctionName",
"my-function",
{
"stat": "Sum",
"label": "MyFunction"
}
],
[
{
"expression": "SUM(METRICS())",
"label": "Total Invocations"
}
]
],
"region": "us-east-1",
"title": "Invocations",
"view": "timeSeries",
"stacked": false
}
}
]
}
You can get the definition for any of the widgets in the default monitoring dashboard from the
CloudWatch console.
147
AWS Lambda Developer Guide
Custom monitoring dashboards
5. Choose Source.
For more information about authoring CloudWatch dashboards and widgets, see Dashboard body
structure and syntax in the Amazon CloudWatch API Reference.
148
AWS Lambda Developer Guide
Tutorial – Create an application
• Application – A [Link] Lambda function, build specification, and AWS Serverless Application Model
(AWS SAM) template.
• Pipeline – An AWS CodePipeline pipeline that connects the other resources to enable continuous
delivery.
• Repository – A Git repository in AWS CodeCommit. When you push a change, the pipeline copies the
source code into an Amazon S3 bucket and passes it to the build project.
• Trigger – An Amazon CloudWatch Events rule that watches the master branch