0% found this document useful (0 votes)
994 views733 pages

Amazon Aws Lambda-Dg PDF

Uploaded by

Rahul Karthi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
994 views733 pages

Amazon Aws Lambda-Dg PDF

Uploaded by

Rahul Karthi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 733

AWS Lambda

Developer Guide
AWS Lambda Developer Guide

AWS Lambda: Developer Guide


Copyright © 2020 Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

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

Function development ...................................................................................................... 46


Layer development and use ............................................................................................... 49
Cross-account roles ........................................................................................................... 50
Resources and conditions .......................................................................................................... 51
Functions ........................................................................................................................ 52
Event source mappings ..................................................................................................... 53
Layers ............................................................................................................................. 54
Permissions boundaries ............................................................................................................. 55
Managing functions .......................................................................................................................... 57
Configuration console ............................................................................................................... 58
Environment variables ............................................................................................................... 61
Runtime environment variables .......................................................................................... 62
Securing environment variables .......................................................................................... 63
Configuring environment variables with the Lambda API ....................................................... 65
Sample code and templates .............................................................................................. 66
Concurrency ............................................................................................................................. 67
Configuring reserved concurrency ....................................................................................... 67
Configuring provisioned concurrency .................................................................................. 69
Configuring concurrency with the Lambda API ..................................................................... 72
Versions .................................................................................................................................. 76
Managing versions with the Lambda API ............................................................................. 77
Using versions .................................................................................................................. 77
Resource policies .............................................................................................................. 78
Aliases .................................................................................................................................... 79
Managing aliases with the Lambda API ............................................................................... 79
Using aliases .................................................................................................................... 80
Resource policies .............................................................................................................. 80
Alias routing configuration ................................................................................................ 80
Layers ..................................................................................................................................... 83
Configuring a function to use layers ................................................................................... 83
Managing layers ............................................................................................................... 84
Including library dependencies in a layer ............................................................................. 86
Layer permissions ............................................................................................................. 87
Network .................................................................................................................................. 88
Execution role and user permissions ................................................................................... 89
Configuring Amazon VPC access with the Lambda API .......................................................... 89
Internet and service access for VPC-connected functions ....................................................... 90
Sample VPC configurations ................................................................................................ 90
Database ................................................................................................................................. 91
Using the function's permissions for authentication .............................................................. 91
Sample application ........................................................................................................... 92
Tags ........................................................................................................................................ 95
Using Tags with the AWS CLI ............................................................................................. 96
Tag Key and Value Requirements ....................................................................................... 97
Invoking functions ............................................................................................................................ 98
Synchronous invocation ............................................................................................................. 99
Asynchronous invocation ......................................................................................................... 101
Configuring error handling for asynchronous invocation ...................................................... 103
Configuring destinations for asynchronous invocation ......................................................... 103
Asynchronous invocation configuration API ........................................................................ 105
Dead-letter queues ......................................................................................................... 106
Event source mapping ............................................................................................................. 109
Function states ....................................................................................................................... 112
Function scaling ..................................................................................................................... 114
Error handling ........................................................................................................................ 119
Mobile SDK for Android .......................................................................................................... 121
Tutorial ......................................................................................................................... 121

iv
AWS Lambda Developer Guide

Sample code .................................................................................................................. 127


Lambda runtimes ........................................................................................................................... 129
Execution context ................................................................................................................... 131
Runtime support policy ........................................................................................................... 132
Custom runtimes .................................................................................................................... 133
Using a custom runtime .................................................................................................. 133
Building a custom runtime ............................................................................................... 133
Runtime interface ................................................................................................................... 136
Next invocation .............................................................................................................. 136
Invocation response ........................................................................................................ 137
Invocation error .............................................................................................................. 137
Initialization error ........................................................................................................... 137
Tutorial – Custom runtime ....................................................................................................... 139
Prerequisites .................................................................................................................. 139
Create a function ............................................................................................................ 139
Create a layer ................................................................................................................ 141
Update the function ....................................................................................................... 142
Update the runtime ........................................................................................................ 142
Share the layer ............................................................................................................... 143
Clean up ........................................................................................................................ 143
Lambda applications ....................................................................................................................... 145
Manage applications ............................................................................................................... 146
Monitoring applications ................................................................................................... 146
Custom monitoring dashboards ........................................................................................ 146
Tutorial – Create an application ................................................................................................ 149
Prerequisites .................................................................................................................. 150
Create an application ...................................................................................................... 150
Invoke the function ........................................................................................................ 151
Add an AWS resource ...................................................................................................... 152
Update the permissions boundary .................................................................................... 154
Update the function code ................................................................................................ 154
Next steps ..................................................................................................................... 155
Troubleshooting ............................................................................................................. 156
Clean up ........................................................................................................................ 157
Rolling deployments ............................................................................................................... 158
Example AWS SAM Lambda template ............................................................................... 158
Use cases ............................................................................................................................... 160
Example 1: Amazon S3 pushes events and invokes a Lambda function ................................... 160
Example 2: AWS Lambda pulls events from a Kinesis stream and invokes a Lambda function ..... 161
Best Practices ......................................................................................................................... 163
Function Code ................................................................................................................ 163
Function Configuration .................................................................................................... 164
Alarming and Metrics ...................................................................................................... 164
Stream Event Invokes ...................................................................................................... 165
Working with other services ............................................................................................................. 166
Alexa ..................................................................................................................................... 169
API Gateway .......................................................................................................................... 170
Permissions .................................................................................................................... 172
Handling errors with an API Gateway API .......................................................................... 174
Choosing an API type ...................................................................................................... 174
Sample applications ........................................................................................................ 176
Tutorial ......................................................................................................................... 176
Sample code .................................................................................................................. 185
Microservice blueprint ..................................................................................................... 187
Sample template ............................................................................................................ 188
CloudTrail .............................................................................................................................. 190
CloudTrail logs ............................................................................................................... 192

v
AWS Lambda Developer Guide

Tutorial ......................................................................................................................... 194


Sample code .................................................................................................................. 199
CloudWatch Events ................................................................................................................. 201
Tutorial ......................................................................................................................... 202
Sample template ............................................................................................................ 204
Schedule expressions ...................................................................................................... 205
CloudWatch Logs .................................................................................................................... 207
CloudFormation ...................................................................................................................... 208
CloudFront (Lambda@Edge) ..................................................................................................... 210
CodeCommit .......................................................................................................................... 212
CodePipeline .......................................................................................................................... 213
Permissions .................................................................................................................... 214
Tutorial ......................................................................................................................... 214
Cognito ................................................................................................................................. 221
Config ................................................................................................................................... 222
DynamoDB ............................................................................................................................. 223
Execution role permissions ............................................................................................... 224
Configuring a stream as an event source ........................................................................... 225
Event source mapping APIs .............................................................................................. 226
Error handling ................................................................................................................ 227
Amazon CloudWatch metrics ............................................................................................ 228
Tutorial ......................................................................................................................... 228
Sample code .................................................................................................................. 233
Sample template ............................................................................................................ 236
EC2 ....................................................................................................................................... 238
Permissions .................................................................................................................... 238
Tutorial – Spot Instances ................................................................................................. 239
ElastiCache ............................................................................................................................ 248
Prerequisites .................................................................................................................. 248
Create the execution role ................................................................................................ 248
Create an ElastiCache cluster ........................................................................................... 249
Create a deployment package .......................................................................................... 249
Create the Lambda function ............................................................................................ 250
Test the Lambda function ................................................................................................ 250
Elastic Load Balancing ............................................................................................................. 251
IoT ........................................................................................................................................ 253
IoT Events ............................................................................................................................. 254
Kinesis Firehose ...................................................................................................................... 256
Kinesis Streams ...................................................................................................................... 257
Configuring your data stream and function ........................................................................ 258
Execution role permissions ............................................................................................... 259
Configuring a stream as an event source ........................................................................... 259
Event source mapping API ............................................................................................... 260
Error handling ................................................................................................................ 262
Amazon CloudWatch metrics ............................................................................................ 263
Tutorial ......................................................................................................................... 263
Sample code .................................................................................................................. 267
Sample template ............................................................................................................ 270
Lex ....................................................................................................................................... 272
Roles and permissions ..................................................................................................... 273
RDS ...................................................................................................................................... 275
Tutorial: Amazon RDS ..................................................................................................... 275
S3 ......................................................................................................................................... 279
Tutorial ......................................................................................................................... 280
Sample code .................................................................................................................. 286
Sample template ............................................................................................................ 292
S3 Batch ................................................................................................................................ 294

vi
AWS Lambda Developer Guide

Invoking Lambda functions from Amazon S3 batch operations ............................................. 295


SES ....................................................................................................................................... 296
SNS ...................................................................................................................................... 298
Tutorial ......................................................................................................................... 299
Sample code .................................................................................................................. 301
SQS ...................................................................................................................................... 304
Scaling and processing .................................................................................................... 305
Configuring a queue for use with Lambda ......................................................................... 305
Execution role permissions ............................................................................................... 306
Configuring a queue as an event source ............................................................................ 306
Event source mapping APIs .............................................................................................. 226
Tutorial ......................................................................................................................... 307
Sample code .................................................................................................................. 310
Sample template ............................................................................................................ 313
X-Ray .................................................................................................................................... 314
Execution role permissions ............................................................................................... 315
The AWS X-Ray daemon .................................................................................................. 316
Enabling active tracing with the Lambda API ..................................................................... 316
Enabling active tracing with AWS CloudFormation .............................................................. 316
Samples ........................................................................................................................................ 318
Blank function ....................................................................................................................... 320
Architecture and handler code ......................................................................................... 320
Deployment automation with AWS CloudFormation and the AWS CLI .................................... 321
Instrumentation with the AWS X-Ray ................................................................................ 324
Dependency management with layers ............................................................................... 325
Error processor ....................................................................................................................... 327
Architecture and event structure ...................................................................................... 327
Instrumentation with AWS X-Ray ...................................................................................... 328
AWS CloudFormation template and additional resources ..................................................... 329
Working with [Link] ...................................................................................................................... 331
Handler ................................................................................................................................. 334
Async handlers ............................................................................................................... 334
Non-async handlers ........................................................................................................ 335
Deployment package .............................................................................................................. 336
Updating a function with no dependencies ........................................................................ 336
Updating a function with additional dependencies .............................................................. 336
Context ................................................................................................................................. 338
Logging ................................................................................................................................. 340
Viewing logs in the AWS Management Console .................................................................. 341
Using the AWS CLI .......................................................................................................... 341
Deleting logs ................................................................................................................. 343
Errors .................................................................................................................................... 344
Tracing .................................................................................................................................. 346
Enabling active tracing with the Lambda API ..................................................................... 348
Enabling active tracing with AWS CloudFormation .............................................................. 348
Storing runtime dependencies in a layer ............................................................................ 349
Working with Python ...................................................................................................................... 350
Handler ................................................................................................................................. 353
Deployment package .............................................................................................................. 354
Prerequisites .................................................................................................................. 354
Updating a function with no dependencies ........................................................................ 354
Updating a function with additional dependencies .............................................................. 355
With a virtual environment .............................................................................................. 356
Context ................................................................................................................................. 358
Logging ................................................................................................................................. 359
Viewing logs in the AWS Management Console .................................................................. 360
Using the AWS CLI .......................................................................................................... 360

vii
AWS Lambda Developer Guide

Deleting logs ................................................................................................................. 361


Logging library ............................................................................................................... 361
Errors .................................................................................................................................... 363
Tracing .................................................................................................................................. 364
Enabling active tracing with the Lambda API ..................................................................... 366
Enabling active tracing with AWS CloudFormation .............................................................. 366
Storing runtime dependencies in a layer ............................................................................ 367
Working with Ruby ......................................................................................................................... 368
Handler ................................................................................................................................. 370
Deployment package .............................................................................................................. 371
Updating a function with no dependencies ........................................................................ 371
Updating a function with additional dependencies .............................................................. 371
Context ................................................................................................................................. 373
Logging ................................................................................................................................. 374
Viewing logs in the AWS Management Console .................................................................. 360
Using the AWS CLI .......................................................................................................... 360
Deleting logs ................................................................................................................. 361
Errors .................................................................................................................................... 379
Tracing .................................................................................................................................. 381
Enabling active tracing with the Lambda API ..................................................................... 383
Enabling active tracing with AWS CloudFormation .............................................................. 383
Storing runtime dependencies in a layer ............................................................................ 384
Working with Java .......................................................................................................................... 385
Sample apps .......................................................................................................................... 387
Deployment package .............................................................................................................. 389
Building a deployment package with Gradle ...................................................................... 390
Building a deployment package with Maven ...................................................................... 391
Uploading a deployment package with the Lambda API ...................................................... 392
Uploading a deployment package with AWS SAM ............................................................... 393
Handler ................................................................................................................................. 395
Choosing input and output types ..................................................................................... 396
Handler interfaces .......................................................................................................... 397
Sample handler code ...................................................................................................... 398
Context ................................................................................................................................. 399
Context in sample applications ......................................................................................... 400
Logging ................................................................................................................................. 402
Viewing logs in the AWS Management Console .................................................................. 403
Using the AWS CLI .......................................................................................................... 403
Deleting logs ................................................................................................................. 405
Advanced logging with Log4j 2 and SLF4J ......................................................................... 405
Sample logging code ...................................................................................................... 407
Errors .................................................................................................................................... 408
Viewing error output ....................................................................................................... 409
Understanding error types and sources ............................................................................. 410
Error handling in clients .................................................................................................. 411
Error handling in other AWS services ................................................................................ 412
Error handling in sample applications ............................................................................... 412
Tracing .................................................................................................................................. 414
Enabling active tracing with the Lambda API ..................................................................... 416
Enabling active tracing with AWS CloudFormation .............................................................. 416
Storing runtime dependencies in a layer ............................................................................ 417
Tracing in sample applications ......................................................................................... 417
Tutorial - Eclipse IDE ............................................................................................................... 419
Prerequisites .................................................................................................................. 419
Create and build a project ............................................................................................... 419
Working with Go ............................................................................................................................ 422
Deployment package .............................................................................................................. 423

viii
AWS Lambda Developer Guide

Creating a deployment package on Windows ..................................................................... 423


Handler ................................................................................................................................. 425
Lambda function handler using structured types ................................................................ 426
Using global state .......................................................................................................... 427
Context ................................................................................................................................. 429
Accessing invoke context information ................................................................................ 429
Logging ................................................................................................................................. 431
Viewing logs in the AWS Management Console .................................................................. 432
Using the AWS CLI .......................................................................................................... 432
Deleting logs ................................................................................................................. 434
Errors .................................................................................................................................... 435
Tracing .................................................................................................................................. 436
Enabling active tracing with the Lambda API ..................................................................... 438
Enabling active tracing with AWS CloudFormation .............................................................. 438
Environment variables ............................................................................................................. 439
Working with C# ............................................................................................................................ 440
Deployment Package .............................................................................................................. 442
.NET Core CLI ................................................................................................................. 442
AWS Toolkit for Visual Studio .......................................................................................... 445
Handler ................................................................................................................................. 448
Handling streams ........................................................................................................... 448
Handling standard data types .......................................................................................... 449
Handler signatures .......................................................................................................... 450
Serializing Lambda functions ........................................................................................... 450
Lambda function handler restrictions ................................................................................ 451
Using async in C# functions with AWS Lambda .................................................................. 451
Context ................................................................................................................................. 453
Logging ................................................................................................................................. 454
Viewing logs in the AWS Management Console .................................................................. 455
Using the AWS CLI .......................................................................................................... 455
Deleting logs ................................................................................................................. 457
Errors .................................................................................................................................... 458
Tracing .................................................................................................................................. 461
Enabling active tracing with the Lambda API ..................................................................... 463
Enabling active tracing with AWS CloudFormation .............................................................. 463
Working with PowerShell ................................................................................................................. 465
Development Environment ...................................................................................................... 466
Deployment package .............................................................................................................. 467
Handler ................................................................................................................................. 469
Returning data ............................................................................................................... 469
Context ................................................................................................................................. 470
Logging ................................................................................................................................. 471
Viewing logs in the AWS Management Console .................................................................. 472
Using the AWS CLI .......................................................................................................... 472
Deleting logs ................................................................................................................. 474
Errors .................................................................................................................................... 475
Monitoring ..................................................................................................................................... 476
Monitoring console ................................................................................................................. 477
Function metrics ..................................................................................................................... 478
Using invocation metrics ................................................................................................. 478
Using performance metrics .............................................................................................. 479
Using concurrency metrics ............................................................................................... 479
CloudWatch logs .................................................................................................................... 481
Security ......................................................................................................................................... 483
Data protection ...................................................................................................................... 483
Encryption in transit ....................................................................................................... 484
Encryption at rest ........................................................................................................... 484

ix
AWS Lambda Developer Guide

Identity and access management .............................................................................................. 484


Audience ....................................................................................................................... 485
Authenticating with identities .......................................................................................... 485
Managing access using policies ......................................................................................... 487
How AWS Lambda works with IAM ................................................................................... 488
Identity-based policy examples ........................................................................................ 488
Troubleshooting ............................................................................................................. 490
Compliance validation ............................................................................................................. 492
Resilience .............................................................................................................................. 492
Infrastructure security ............................................................................................................. 493
Configuration and vulnerability analysis .................................................................................... 493
Troubleshooting ............................................................................................................................. 494
Deployment ........................................................................................................................... 494
Invocation .............................................................................................................................. 496
Execution ............................................................................................................................... 497
Networking ............................................................................................................................ 499
Releases ........................................................................................................................................ 500
Earlier updates ....................................................................................................................... 507
API reference ................................................................................................................................. 512
Actions .................................................................................................................................. 512
AddLayerVersionPermission .............................................................................................. 514
AddPermission ............................................................................................................... 517
CreateAlias ..................................................................................................................... 521
CreateEventSourceMapping .............................................................................................. 525
CreateFunction ............................................................................................................... 531
DeleteAlias ..................................................................................................................... 540
DeleteEventSourceMapping .............................................................................................. 542
DeleteFunction ............................................................................................................... 546
DeleteFunctionConcurrency .............................................................................................. 548
DeleteFunctionEventInvokeConfig ..................................................................................... 550
DeleteLayerVersion ......................................................................................................... 552
DeleteProvisionedConcurrencyConfig ................................................................................ 554
GetAccountSettings ......................................................................................................... 556
GetAlias ......................................................................................................................... 558
GetEventSourceMapping .................................................................................................. 561
GetFunction ................................................................................................................... 565
GetFunctionConcurrency .................................................................................................. 568
GetFunctionConfiguration ................................................................................................ 570
GetFunctionEventInvokeConfig ......................................................................................... 576
GetLayerVersion ............................................................................................................. 579
GetLayerVersionByArn ..................................................................................................... 582
GetLayerVersionPolicy ..................................................................................................... 585
GetPolicy ....................................................................................................................... 587
GetProvisionedConcurrencyConfig ..................................................................................... 589
Invoke ........................................................................................................................... 592
InvokeAsync ................................................................................................................... 597
ListAliases ...................................................................................................................... 599
ListEventSourceMappings ................................................................................................ 602
ListFunctionEventInvokeConfigs ........................................................................................ 605
ListFunctions .................................................................................................................. 608
ListLayers ...................................................................................................................... 611
ListLayerVersions ............................................................................................................ 613
ListProvisionedConcurrencyConfigs ................................................................................... 616
ListTags ......................................................................................................................... 619
ListVersionsByFunction .................................................................................................... 621
PublishLayerVersion ........................................................................................................ 624
PublishVersion ................................................................................................................ 628

x
AWS Lambda Developer Guide

PutFunctionConcurrency .................................................................................................. 635


PutFunctionEventInvokeConfig ......................................................................................... 638
PutProvisionedConcurrencyConfig ..................................................................................... 642
RemoveLayerVersionPermission ........................................................................................ 645
RemovePermission .......................................................................................................... 647
TagResource ................................................................................................................... 649
UntagResource ............................................................................................................... 651
UpdateAlias ................................................................................................................... 653
UpdateEventSourceMapping ............................................................................................ 657
UpdateFunctionCode ....................................................................................................... 663
UpdateFunctionConfiguration ........................................................................................... 670
UpdateFunctionEventInvokeConfig .................................................................................... 679
Data Types ............................................................................................................................ 682
AccountLimit .................................................................................................................. 684
AccountUsage ................................................................................................................ 685
AliasConfiguration .......................................................................................................... 686
AliasRoutingConfiguration ............................................................................................... 688
Concurrency ................................................................................................................... 689
DeadLetterConfig ........................................................................................................... 690
DestinationConfig ........................................................................................................... 691
Environment .................................................................................................................. 692
EnvironmentError ........................................................................................................... 693
EnvironmentResponse ..................................................................................................... 694
EventSourceMappingConfiguration ................................................................................... 695
FunctionCode ................................................................................................................. 698
FunctionCodeLocation ..................................................................................................... 699
FunctionConfiguration ..................................................................................................... 700
FunctionEventInvokeConfig .............................................................................................. 705
Layer ............................................................................................................................. 707
LayersListItem ................................................................................................................ 708
LayerVersionContentInput ................................................................................................ 709
LayerVersionContentOutput ............................................................................................. 710
LayerVersionsListItem ...................................................................................................... 711
OnFailure ....................................................................................................................... 713
OnSuccess ..................................................................................................................... 714
ProvisionedConcurrencyConfigListItem .............................................................................. 715
TracingConfig ................................................................................................................. 717
TracingConfigResponse .................................................................................................... 718
VpcConfig ...................................................................................................................... 719
VpcConfigResponse ......................................................................................................... 720
Certificate errors when using an SDK ........................................................................................ 720
AWS glossary ................................................................................................................................. 722

xi
AWS Lambda Developer Guide
When should I use AWS Lambda?

What is AWS Lambda?


AWS Lambda is a compute service that lets you run code without provisioning or managing servers.
AWS Lambda executes your code only when needed and scales automatically, from a few requests
per day to thousands per second. You pay only for the compute time you consume - there is no
charge when your code is not running. With AWS Lambda, you can run code for virtually any type of
application or backend service - all with zero administration. AWS Lambda runs your code on a high-
availability compute infrastructure and performs all of the administration of the compute resources,
including server and operating system maintenance, capacity provisioning and automatic scaling,
code monitoring and logging. All you need to do is supply your code in one of the languages that AWS
Lambda supports (p. 129).

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 should I use AWS Lambda?


AWS Lambda is an ideal compute platform for many application scenarios, provided that you can
write your application code in languages supported by AWS Lambda, and run within the AWS Lambda
standard runtime environment and resources provided by Lambda.

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.

Are you a first-time user of AWS Lambda?


If you are a first-time user of AWS Lambda, we recommend that you read the following sections in order:

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

Getting started with AWS Lambda


To get started with AWS Lambda, use the Lambda console to create a function. In a few minutes, you can
create a function, invoke it, and view logs, metrics, and trace data.
Note
To use Lambda and other AWS services, you need an AWS account. If you don't have an account,
visit [Link] and choose Create an AWS Account. For detailed instructions, see Create
and activate an AWS account.
As a best practice, you should also create an AWS Identity and Access Management (IAM) user
with administrator permissions and use that for all work that does not require root credentials.
Create a password for console access, and access keys to use command line tools. See Creating
your first IAM admin user and group in the IAM User Guide for instructions.

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

Create a Lambda function with the console


In this Getting Started exercise you create a Lambda function using the AWS Lambda console. Next,
you manually invoke the Lambda function using sample event data. AWS Lambda executes the Lambda
function and returns results. You then verify execution results, including the logs that your Lambda
function created and various CloudWatch metrics.

To create a Lambda function

1. Open the AWS Lambda console.


2. Choose Create a function.
3. For Function name, enter my-function.
4. Choose Create 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.

Use the designer


The Designer shows an overview of your function and its upstream and downstream resources. You can
use it to configure triggers, layers, and destinations.

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.

Invoke the Lambda function


Invoke your Lambda function using the sample event data provided in the console.

4
AWS Lambda Developer Guide
Invoke the Lambda function

To invoke a function

1. In the upper right corner, choose Test.


2. In the Configure test event page, choose Create new test event and in Event template, leave the
default Hello World option. Enter an Event name and note the following sample event template:

{
"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.

To delete a Lambda function

1. Open the Lambda console Functions page.


2. Choose a function.
3. Choose Actions, and then choose Delete function.
4. Choose Delete.

To delete the log group

1. Open the Log groups page of the Amazon CloudWatch console.


2. Choose the function's log group (/aws/lambda/my-function).
3. Choose Actions, and then choose Delete log group.
4. Choose Yes, Delete.

6
AWS Lambda Developer Guide
Clean up

To delete the execution role

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

Creating functions using the AWS Lambda console


editor
The code editor in the AWS Lambda console enables you to write, test, and view the execution results of
your Lambda function code.

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)

Working with files and folders


You can use the Environment window in the code editor to create, open, and manage files for your
function.

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.

To create a new file, do one of the following:

• 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.

Working with code


Use the editor pane in the code editor to view and write code.

Working with tab buttons


Use the tab buttons bar to select, view, and create files.

To display an open file's contents, do one of the following:

• Choose the file's tab.


• Choose the drop-down menu button in the tab buttons bar, and then choose the file's name.

10
AWS Lambda Developer Guide
Working with code

To close an open file, do one of the following:

• Choose the X icon in the file's tab.


• Choose the file's tab. Then choose the drop-down menu button in the tab buttons bar, and choose
Close Pane.

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.

Working with the status bar


Use the status bar to move quickly to a line in the active file and to change how code is displayed.

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

Working in fullscreen mode


You can expand the code editor to get more room to work with your code.

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.

Working with preferences


You can change various code editor settings such as which coding hints and warnings are displayed, code
folding behaviors, code autocompletion behaviors, and much more.

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.

• Project setting changes you can make


• User setting changes you can make

Note that some of the settings listed in those references are not available in the code editor.

13
AWS Lambda Developer Guide
AWS CLI

Using AWS Lambda with the AWS Command Line


Interface
You can use the AWS Command Line Interface to manage functions and other AWS Lambda resources.
The AWS CLI uses the AWS SDK for Python (Boto) to interact with the Lambda API. You can use it to
learn about the API, and apply that knowledge in building applications that use Lambda with the AWS
SDK.

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:

~/lambda-project$ this is a command


this is output

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.

Create the execution role


Create the execution role (p. 37) that gives your function permission to access AWS resources. To
create an execution role with the AWS CLI, use the create-role command.

$ aws iam create-role --role-name lambda-ex --assume-role-policy-document [Link]


[Link]
{
"Role": {
"Path": "/",
"RoleName": "lambda-ex",
"RoleId": "AROAQFOXMPL6TZ6ITKWND",
"Arn": "arn:aws:iam::123456789012:role/lambda-ex",
"CreateDate": "2020-01-17T[Link]Z",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "[Link]"
},
"Action": "sts:AssumeRole"
}

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.

$ aws iam create-role --role-name lambda-ex --assume-role-policy-document


'{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service":
"[Link]"}, "Action": "sts:AssumeRole"}]}'

To add permissions to the role, use the attach-policy-to-role command. Start by adding the
AWSLambdaBasicExecutionRole managed policy.

$ aws iam attach-role-policy --role-name lambda-ex --policy-arn arn:aws:iam::aws:policy/


service-role/AWSLambdaBasicExecutionRole

The AWSLambdaBasicExecutionRole policy has the permissions that the function needs to write logs to
CloudWatch Logs.

Create the function


The following example logs the values of environment variables and the event object.

Example [Link]

[Link] = async function(event, context) {


[Link]("ENVIRONMENT VARIABLES\n" + [Link]([Link], null, 2))
[Link]("EVENT\n" + [Link](event, null, 2))
return [Link]
}

To create the function

1. Copy the sample code into a file named [Link].


2. Create a deployment package.

15
AWS Lambda Developer Guide
Create the function

$ zip [Link] [Link]

3. Create a Lambda function with the create-function command. Replace the highlighted text in
the role ARN with your account ID.

$ aws lambda create-function --function-name my-function \


--zip-file fileb://[Link] --handler [Link] --runtime nodejs12.x \
--role arn:aws:iam::123456789012:role/lambda-ex
{
"FunctionName": "my-function",
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function",
"Runtime": "nodejs12.x",
"Role": "arn:aws:iam::123456789012:role/lambda-ex",
"Handler": "[Link]",
"CodeSha256": "FpFMvUhayLkOoVBpNuNiIVML/tuGv2iJQ7t0yWVTU8c=",
"Version": "$LATEST",
"TracingConfig": {
"Mode": "PassThrough"
},
"RevisionId": "88ebe1e1-bfdf-4dc3-84de-3017268fa1ff",
...
}

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.

$ aws lambda invoke --function-name my-function out --log-type Tail


{
"StatusCode": 200,
"LogResult":
"U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...",
"ExecutedVersion": "$LATEST"
}

You can use the base64 utility to decode the logs.

$ aws lambda invoke --function-name my-function out --log-type Tail \


--query 'LogResult' --output text | base64 -d
START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST
"AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-
f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib",
END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8
REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed
Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB

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.

Example [Link] Script

This example requires that my-function returns a log stream ID.

#!/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

sed -i'' -e 's/"//g' out


sleep 15
aws logs get-log-events --log-group-name /aws/lambda/my-function --log-stream-name $(cat
out) --limit 5

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"
}

List the Lambda functions in your account


Execute the following AWS CLI list-functions command to retrieve a list of functions that you have
created.

$ aws lambda list-functions --max-items 10


{
"Functions": [
{
"FunctionName": "cli",
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function",
"Runtime": "nodejs12.x",

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.

$ aws lambda list-functions --max-items 10 --starting-


token eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxMH0=

Retrieve a Lambda function


The Lambda CLI get-function command returns Lambda function metadata and a presigned URL that
you can use to download the function's deployment package.

$ aws lambda get-function --function-name my-function


{
"Configuration": {
"FunctionName": "my-function",
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function",
"Runtime": "nodejs12.x",
"Role": "arn:aws:iam::123456789012:role/lambda-ex",
"CodeSha256": "FpFMvUhayLkOoVBpNuNiIVML/tuGv2iJQ7t0yWVTU8c=",
"Version": "$LATEST",
"TracingConfig": {
"Mode": "PassThrough"
},
"RevisionId": "88ebe1e1-bfdf-4dc3-84de-3017268fa1ff",
...
},
"Code": {
"RepositoryType": "S3",
"Location": "[Link]
snapshots/123456789012/my-function-4203078a-b7c9-4f35-..."
}
}

For more information, see GetFunction (p. 565).

Clean up
Execute the following delete-function command to delete the my-function function.

$ aws lambda delete-function --function-name my-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

AWS Lambda concepts


With AWS Lambda, you run functions to process events. You can send events to your function by
invoking it with the Lambda API, or by configuring an AWS service or resource to invoke it.

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.

For more information, see AWS Lambda runtimes (p. 129).

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.

Example custom event – Weather data

{
"TemperatureK": 281,
"WindKmh": -3,
"HumidityPct": 0.55,
"PressureHPa": 1020
}

When an AWS service invokes your function, the service defines the shape of the event.

Example service event – Amazon SNS notification

{
"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

AWS Lambda features


AWS Lambda provides a management console and API for managing and invoking functions. It provides
runtimes that support a standard set of features so that you can easily switch between languages and
frameworks, depending on your needs. In addition to functions, you can also create versions, aliases,
layers, and custom runtimes.

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.

• Building Lambda functions with [Link] (p. 331)


• Building Lambda functions with Python (p. 350)
• Building Lambda functions with Ruby (p. 368)
• Building Lambda functions with Java (p. 385)
• Building Lambda functions with Go (p. 422)
• Building Lambda functions with C# (p. 440)
• Building Lambda functions with PowerShell (p. 465)

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.

For language-specific instructions, see the following topics.

• AWS Lambda deployment package in [Link] (p. 336)


• AWS Lambda deployment package in Python (p. 354)
• AWS Lambda deployment package in Ruby (p. 371)
• AWS Lambda deployment package in Java (p. 389)
• AWS Lambda deployment package in Go (p. 423)
• AWS Lambda Deployment Package in C# (p. 442)
• AWS Lambda deployment package in PowerShell (p. 467)

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.

For more information, see AWS Lambda layers (p. 83).

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).

For more information, see Asynchronous invocation (p. 101).

Event source mappings


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.

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 for working with AWS Lambda


In addition to the Lambda console, you can use the following tools to manage and invoke Lambda
resources.

Tools
• AWS Command Line Interface (p. 32)
• AWS Serverless Application Model (p. 32)
• SAM CLI (p. 32)
• Code authoring tools (p. 32)

AWS Command Line Interface


Install the AWS Command Line Interface to manage and use Lambda functions from the command
line. Tutorials in this guide use the AWS CLI, which has commands for all Lambda API actions. Some
functionality is not available in the Lambda console and can only be accessed with the AWS CLI or the
AWS SDK.

To set up the AWS CLI, see the following topics in the AWS Command Line Interface User Guide.

• Getting set up with the AWS Command Line Interface


• Configuring the AWS Command Line Interface

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.

$ aws lambda list-functions

AWS Serverless Application Model


AWS SAM is an extension for the AWS CloudFormation template language that lets you define serverless
applications at a higher level. It abstracts away common tasks such as function role creation, which
makes it easier to write templates. AWS SAM is supported directly by AWS CloudFormation, and includes
additional functionality through the AWS CLI and AWS SAM CLI.

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.

Code authoring tools


You can author your Lambda function code in the languages that are supported by AWS Lambda. For a
list of supported languages, see AWS Lambda runtimes (p. 129). There are tools for authoring code,

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:

• Language you choose to write your Lambda function code.


• Libraries that you use in your code. AWS Lambda runtime provides some of the libraries and you must
upload any additional libraries that you use.

The following table lists languages, and the available tools and options that you can use.

Language Tools and options for authoring code

[Link] • AWS Lambda console


• Visual Studio, with IDE plug-in (see AWS Lambda support in
Visual Studio)
• Your own authoring environment

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

C# • Visual Studio, with IDE plug-in (see AWS Lambda support in


Visual Studio)
• .NET Core (see .NET Core installation guide)
• Your own authoring environment

Python • AWS Lambda console


• PyCharm, with the AWS Toolkit for PyCharm
• Your own authoring environment

Ruby • AWS Lambda console


• Your own authoring environment

Go • Your own authoring environment

PowerShell • Your own authoring environment


• PowerShell Core 6.0 (see Installing PowerShell Core)
• .NET Core 3.1 SDK (see .NET downloads)
• AWSLambdaPSCore Module (see PowerShell Gallery)

33
AWS Lambda Developer Guide
Limits

AWS Lambda limits


AWS Lambda limits the amount of compute and storage resources that you can use to run and store
functions. The following limits apply per-region and can be increased. To request an increase, use the
Support Center console.

Resource Default limit

Concurrent executions 1,000

Function and layer storage 75 GB

Elastic network interfaces per VPC (p. 88) 250

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 memory allocation (p. 58) 128 MB to 3,008 MB, in 64 MB


increments.

Function timeout (p. 58) 900 seconds (15 minutes)

Function environment variables (p. 61) 4 KB

Function resource-based policy (p. 41) 20 KB

Function layers (p. 83) 5 layers

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)

10 x concurrent executions limit


(asynchronous (p. 101) – non-AWS
sources)

Unlimited (asynchronous – AWS service


sources (p. 166))

Invocation frequency per function version or alias (requests 10 x allocated provisioned


per second) concurrency (p. 67)

This limit only applies to functions that


use provisioned concurrency.

Invocation payload (p. 98) (request and response) 6 MB (synchronous)

256 KB (asynchronous)

Deployment package (p. 24) size 50 MB (zipped, for direct upload)

250 MB (unzipped, including layers)

34
AWS Lambda Developer Guide
Limits

Resource Limit
3 MB (console editor)

Test events (console editor) 10

/tmp directory storage 512 MB

File descriptors 1,024

Execution processes/threads 1,024

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

AWS Lambda permissions


You can use AWS Identity and Access Management (IAM) to manage access to the Lambda API and
resources like functions and layers. For users and applications in your account that use Lambda, you
manage permissions in a permissions policy that you can apply to IAM users, groups, or roles. To grant
permissions to other accounts or AWS services that use your Lambda resources, you use a policy that
applies to the resource itself.

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

AWS Lambda execution role


An AWS Lambda function's execution role grants it permission to access AWS services and resources.
You provide this role when you create a function, and Lambda assumes the role when your function is
invoked. You can create an execution role for development that has permission to send logs to Amazon
CloudWatch and upload trace data to AWS X-Ray.

To view a function's execution role

1. Open the Lambda console Functions page.


2. Choose a function.
3. Choose Permissions.
4. The resource summary shows the services and resources that the function has access to. The
following example shows the CloudWatch Logs permissions that Lambda adds to an execution role
when you create it in the Lambda console.

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.

Creating an execution role in the IAM console


By default, Lambda creates an execution role with minimal permissions when you create a function (p. 4)
in the Lambda console. You can also create an execution role in the IAM console.

To create an execution role in the IAM console

1. Open the roles page in the IAM console.


2. Choose Create role.
3. Under Common use cases, choose Lambda.
4. Choose Next: Permissions.
5. Under Attach permissions policies, choose the AWSLambdaBasicExecutionRole and
AWSXRayDaemonWriteAccess managed policies.
6. Choose Next: Tags.
7. Choose Next: Review.
8. For Role name, enter lambda-role.
9. Choose Create role.

For detailed instructions, see Creating a role in the IAM User Guide.

Managing roles with the IAM API


An execution role is an IAM role that Lambda has permission to assume when you invoke a function. To
create an execution role with the AWS CLI, use the create-role command.

$ aws iam create-role --role-name lambda-ex --assume-role-policy-document [Link]


[Link]
{
"Role": {
"Path": "/",
"RoleName": "lambda-ex",
"RoleId": "AROAQFOXMPL6TZ6ITKWND",
"Arn": "arn:aws:iam::123456789012:role/lambda-ex",
"CreateDate": "2020-01-17T[Link]Z",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "[Link]"
},
"Action": "sts:AssumeRole"
}
]
}
}
}

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.

$ aws iam create-role --role-name lambda-ex --assume-role-policy-document


'{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service":
"[Link]"}, "Action": "sts:AssumeRole"}]}'

To add permissions to the role, use the attach-policy-to-role command. Start by adding the
AWSLambdaBasicExecutionRole managed policy.

$ aws iam attach-role-policy --role-name lambda-ex --policy-arn arn:aws:iam::aws:policy/


service-role/AWSLambdaBasicExecutionRole

Managed policies for Lambda features


The following managed policies provide permissions that are required to use Lambda features:

• AWSLambdaBasicExecutionRole – Permission to upload logs to CloudWatch.


• AWSLambdaKinesisExecutionRole – Permission to read events from an Amazon Kinesis data stream
or consumer.
• AWSLambdaDynamoDBExecutionRole – Permission to read records from an Amazon DynamoDB
stream.
• AWSLambdaSQSQueueExecutionRole – Permission to read a message from an Amazon Simple Queue
Service (Amazon SQS) queue.
• AWSLambdaVPCAccessExecutionRole – Permission to manage elastic network interfaces to connect
your function to a VPC.
• AWSXRayDaemonWriteAccess – Permission to upload trace data to X-Ray.

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

Services that Lambda reads events from

• Amazon Kinesis (p. 257)


• Amazon DynamoDB (p. 223)
• Amazon Simple Queue Service (p. 304)

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

Using resource-based policies for AWS Lambda


AWS Lambda supports resource-based permissions policies for Lambda functions and layers. Resource-
based policies let you grant usage permission to other accounts on a per-resource basis. You also use a
resource-based policy to allow an AWS service to invoke your function.

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).

To view a function's resource-based policy

1. Open the Lambda console Functions page.


2. Choose a function.
3. Choose Permissions.
4. The resource-based policy shows the permissions that are applied when another account or AWS
service attempts to access the function. The following example shows a statement that allows
Amazon S3 to invoke a function named my-function for a bucket named my-bucket in account
123456789012.

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)

Granting function access to AWS services


When you use an AWS service to invoke your function (p. 166), you grant permission in a statement
on a resource-based policy. You can apply the statement to the function, or limit it to a single version or
alias.
Note
When you add a trigger to your function with the Lambda console, the console updates the
function's resource-based policy to allow the service to invoke it. To grant permissions to other
accounts or services that aren't available in the Lambda console, use the AWS CLI.

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.

$ aws lambda add-permission --function-name my-function --action lambda:InvokeFunction --


statement-id sns \
--principal [Link] --output text
{"Sid":"sns","Effect":"Allow","Principal":
{"Service":"[Link]"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-
east-2:123456789012:function: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.

$ aws lambda add-permission --function-name my-function --action lambda:InvokeFunction --


statement-id sns-my-topic \
--principal [Link] --source-arn arn:aws:sns:us-east-2:123456789012: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.

$ aws lambda add-permission --function-name my-function --action lambda:InvokeFunction --


statement-id s3-account \
--principal [Link] --source-arn arn:aws:s[Link]my-bucket-123456 --source-
account 123456789012

Granting function access to other accounts


To grant permissions to another AWS account, specify the account ID as the principal. The following
example grants account 210987654321 permission to invoke my-function with the prod alias.

$ aws lambda add-permission --function-name my-function:prod --statement-id xaccount --


action lambda:InvokeFunction \
--principal 210987654321 --output text
{"Sid":"xaccount","Effect":"Allow","Principal":
{"AWS":"arn:aws:iam::210987654321:root"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us
east-2:123456789012:function:my-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.

$ aws lambda invoke --function-name arn:aws:lambda:us-west-2:123456789012:function:my-


function:prod out
{
"StatusCode": 200,
"ExecutedVersion": "1"
}

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

• Invoke (p. 592)


• GetFunction (p. 565)
• GetFunctionConfiguration (p. 570)
• UpdateFunctionCode (p. 663)
• DeleteFunction (p. 546)
• PublishVersion (p. 628)
• ListVersionsByFunction (p. 621)

43
AWS Lambda Developer Guide
Granting layer access to other accounts

• CreateAlias (p. 521)


• GetAlias (p. 558)
• ListAliases (p. 599)
• UpdateAlias (p. 653)
• DeleteAlias (p. 540)
• GetPolicy (p. 587)
• PutFunctionConcurrency (p. 635)
• DeleteFunctionConcurrency (p. 548)
• ListTags (p. 619)
• TagResource (p. 649)
• UntagResource (p. 651)

To grant other accounts permission for multiple functions, or for actions that don't operate on a
function, use roles (p. 46).

Granting layer access to other accounts


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.

$ aws lambda add-layer-version-permission --layer-name xray-sdk-nodejs --statement-id


xaccount \
--action lambda:GetLayerVersion --principal 210987654321 --version-number 1 --output text
e210ffdc-e901-43b0-824b-5fcd0dd26d16 {"Sid":"xaccount","Effect":"Allow","Principal":
{"AWS":"arn:aws:iam::210987654321:root"},"Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:u
east-2:123456789012:layer:xray-sdk-nodejs:1"}

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.

$ aws lambda add-layer-version-permission --layer-name my-layer \


--statement-id engineering-org --version-number 3 --principal '*' \
--action lambda:GetLayerVersion --organization-id o-t194hfs8cz --output text
b0cd9796-d4eb-4564-939f-de7fe0b42236 {"Sid":"engineering-
org","Effect":"Allow","Principal":"*","Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:us-
east-2:123456789012:layer:my-layer:3","Condition":{"StringEquals":{"aws:PrincipalOrgID":"o-
t194hfs8cz"}}}"

To grant permission to all AWS accounts, use * for the principal, and omit the organization ID. For
multiple accounts or organizations, add multiple statements.

Cleaning up resource-based policies


To view a function's resource-based policy, use the get-policy command.

$ aws lambda get-policy --function-name my-function --output text


{"Version":"2012-10-17","Id":"default","Statement":
[{"Sid":"sns","Effect":"Allow","Principal":
{"Service":"[Link]"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-

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.

$ aws lambda get-policy --function-name my-function:PROD

To remove permissions from your function, use remove-permission.

$ aws lambda remove-permission --function-name example --statement-id sns

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.

$ aws lambda get-layer-version-policy --layer-name my-layer --version-number 3 --output


text
b0cd9796-d4eb-4564-939f-de7fe0b42236 {"Sid":"engineering-
org","Effect":"Allow","Principal":"*","Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:us-
west-2:123456789012:layer:my-layer:3","Condition":{"StringEquals":{"aws:PrincipalOrgID":"o-
t194hfs8cz"}}}"

$ aws lambda remove-layer-version-permission --layer-name my-layer --version-number 3 --


statement-id engineering-org

45
AWS Lambda Developer Guide
User policies

Identity-based IAM policies for AWS Lambda


You can use identity-based policies in AWS Identity and Access Management (IAM) to grant users in your
account access to Lambda. Identity-based policies can apply to users directly, or to groups and roles that
are associated with a user. You can also grant users in another account permission to assume a role in
your account and access your Lambda resources.

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.

Example Function development policy

{
"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-*"

• DevelopEventSourceMappings – Manage event source mappings on functions that are prefixed


with intern-. These actions operate on event source mappings, but you can restrict them by function
with a condition.

"Action": [
"lambda:DeleteEventSourceMapping",
"lambda:UpdateEventSourceMapping",
"lambda:CreateEventSourceMapping"
],
"Resource": "*",
"Condition": {
"StringLike": {
"lambda:FunctionArn": "arn:aws:lambda:*:*:function:intern-*"
}
}

• PassExecutionRole – View and pass only a role named intern-lambda-execution-role, which


must be created and managed by a user with IAM permissions. PassRole is used when you assign an
execution role to a function.

"Action": [
"iam:ListRolePolicies",
"iam:ListAttachedRolePolicies",
"iam:GetRole",
"iam:GetRolePolicy",
"iam:PassRole",
"iam:SimulatePrincipalPolicy"
],
"Resource": "arn:aws:iam::*:role/intern-lambda-execution-role"

• ViewExecutionRolePolicies – View the AWS-provided managed policies that are attached to


the execution role. This lets you view the function's permissions in the console, but doesn't include
permission to view policies that were created by other users in the account.

"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.

Layer development and use


The following policy grants a user permission to create layers and use them with functions. The resource
patterns allow the user to work in any AWS Region and with any layer version, as long as the name of the
layer starts with test-.

Example layer development policy

{
"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

Resources and conditions for Lambda actions


You can restrict the scope of a user's permissions by specifying resources and conditions in an IAM policy.
Each API action supports a combination of resource and condition types that varies depending on the
behavior of the action.

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.

To restrict permissions by resource, specify the resource by ARN.

Lambda resource ARN format

• 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.

Example invoke function policy

{
"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

Example manage function policy permissions

{
"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

Action Resource Condition

AddPermission (p. 517) Function lambda:Principal

RemovePermission (p. 647) Function version

Function alias

Invoke (p. 592) Function None

Permission: lambda:InvokeFunction Function version

Function alias

CreateFunction (p. 531) Function lambda:Layer

UpdateFunctionConfiguration (p. 670)

52
AWS Lambda Developer Guide
Event source mappings

Action Resource Condition

CreateAlias (p. 521) Function None

DeleteAlias (p. 540)

DeleteFunction (p. 546)

DeleteFunctionConcurrency (p. 548)

GetAlias (p. 558)

GetFunction (p. 565)

GetFunctionConfiguration (p. 570)

GetPolicy (p. 587)

ListAliases (p. 599)

ListVersionsByFunction (p. 621)

PublishVersion (p. 628)

PutFunctionConcurrency (p. 635)

UpdateAlias (p. 653)

UpdateFunctionCode (p. 663)

GetAccountSettings (p. 556) * None

ListFunctions (p. 608)

ListTags (p. 619)

TagResource (p. 649)

UntagResource (p. 651)

Event source mappings


For event source mappings, delete and update permissions can be restricted to a specific event source.
The lambda:FunctionArn condition lets you restrict which functions a user can configure an event
source to invoke.

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.

Event source mappings

Action Resource Condition

DeleteEventSourceMapping (p. 542) Event source mapping lambda:FunctionArn

UpdateEventSourceMapping (p. 657)

CreateEventSourceMapping (p. 525) * lambda:FunctionArn

GetEventSourceMapping (p. 561) * None

53
AWS Lambda Developer Guide
Layers

Action Resource Condition


ListEventSourceMappings (p. 602)

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

Action Resource Condition

AddLayerVersionPermission (p. 514) Layer version None

RemoveLayerVersionPermission (p. 645)

GetLayerVersion (p. 579)

GetLayerVersionPolicy (p. 585)

DeleteLayerVersion (p. 552)

PublishLayerVersion (p. 624) Layer None

ListLayers (p. 611) * None

ListLayerVersions (p. 613)

54
AWS Lambda Developer Guide
Permissions boundaries

Using permissions boundaries for AWS Lambda


applications
When you create an application (p. 149) in the AWS Lambda console, Lambda applies a permissions
boundary to the application's IAM roles. The permissions boundary limits the scope of the execution
role (p. 37) that the application's template creates for each of its functions, and any roles that you add
to the template. The permissions boundary prevents users with write access to the application's Git
repository from escalating the application's permissions beyond the scope of its own resources.

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.

Example permissions boundary

{
"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

Managing AWS Lambda functions


You can use the AWS Lambda API or console to configure settings on your Lambda functions. Basic
function settings (p. 58) include the description, role, and runtime that you specify when you create a
function in the Lambda console. You can configure more settings after you create a function, or use the
API to set things like the handler name, memory allocation, and security groups during creation.

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

Configuring functions in the AWS Lambda console


You can use the Lambda console to configure function settings, add triggers and destinations, and
update and test your code.

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.

You can configure error handling settings on a function, version, or alias.

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:

• UpdateFunctionCode (p. 663) – Update the function's code.


• UpdateFunctionConfiguration (p. 670) – Update version-specific settings.
• TagResource (p. 649) – Tag a function.
• AddPermission (p. 517) – Modify the resource-based policy (p. 41) of a function, version, or alias.
• PutFunctionConcurrency (p. 635) – Configure a function's reserved concurrency.
• PublishVersion (p. 628) – Create an immutable version with the current code and configuration.
• CreateAlias (p. 521) – Create aliases for function versions.
• PutFunctionEventInvokeConfig – Configure error handling for asynchronous invocation.

For example, to update a function's memory setting with the AWS CLI, use the update-function-
configuration command.

$ aws lambda update-function-configuration --function-name my-function --memory-size 256

59
AWS Lambda Developer Guide
Configuration console

For function configuration best practices, see Function Configuration (p. 164).

60
AWS Lambda Developer Guide
Environment variables

Using AWS Lambda environment variables


You can use environment variables to store secrets securely and adjust your function's behavior without
updating code. An environment variable is a pair of strings that are stored in a function's version-
specific configuration. The Lambda runtime makes environment variables available to your code and sets
additional environment variables that contain information about the function and invocation request.

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).

To set environment variables in the Lambda console

1. Open the Lambda console Functions page.


2. Choose a function.
3. Under Environment variables, choose Edit.
4. Choose Add environment variable.
5. Enter a key and value.

Requirements

• Keys start with a letter and are at least two characters.


• Keys only contain letters, numbers, and the underscore character (_).
• Keys aren't reserved by Lambda (p. 62).
• The total size of all environment variables doesn't exceed 4 KB.
6. Choose Save.

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]

let region = [Link].AWS_REGION

61
AWS Lambda Developer Guide
Runtime environment variables

Python

import os
region = [Link]['AWS_REGION']

Ruby

region = ENV["AWS_REGION"]

Java

String region = [Link]("AWS_REGION");

Go

var region = [Link]("AWS_REGION")

C#

string region = [Link]("AWS_REGION");

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)

Runtime environment variables


Lambda runtimes (p. 129) set several environment variables during initialization. Most of the
environment variables provide information about the function or runtime. The keys for these
environment variables are reserved and cannot be set in your function configuration.

Reserved environment variables

• _HANDLER – The handler location configured on the function.


• AWS_REGION – The AWS Region where the Lambda function is executed.
• AWS_EXECUTION_ENV – The runtime identifier (p. 129), prefixed by AWS_Lambda_—for example,
AWS_Lambda_java8.
• AWS_LAMBDA_FUNCTION_NAME – The name of the function.
• AWS_LAMBDA_FUNCTION_MEMORY_SIZE – The amount of memory available to the function in MB.

62
AWS Lambda Developer Guide
Securing environment variables

• AWS_LAMBDA_FUNCTION_VERSION – The version of the function being executed.


• AWS_LAMBDA_LOG_GROUP_NAME, AWS_LAMBDA_LOG_STREAM_NAME – The name of the Amazon
CloudWatch Logs group and stream for the function.
• AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN – The access keys obtained
from the function's execution role (p. 37).
• AWS_LAMBDA_RUNTIME_API – (Custom runtime (p. 133)) The host and port of the runtime
API (p. 136).
• LAMBDA_TASK_ROOT – The path to your Lambda function code.
• LAMBDA_RUNTIME_DIR – The path to runtime libraries.
• TZ – The environment's time zone (UTC). The execution environment uses NTP to synchronize the
system clock.

The following additional environment variables aren't reserved and can be extended in your function
configuration.

Unreserved environment variables

• LANG – The locale of the runtime (en_US.UTF-8).


• PATH – The execution path (/usr/local/bin:/usr/bin/:/bin:/opt/bin).
• LD_LIBRARY_PATH – The system library path (/lib64:/usr/lib64:$LAMBDA_RUNTIME_DIR:
$LAMBDA_RUNTIME_DIR/lib:$LAMBDA_TASK_ROOT:$LAMBDA_TASK_ROOT/lib:/opt/lib).
• NODE_PATH – ([Link] (p. 331)) The [Link] library path (/opt/nodejs/node12/
node_modules/:/opt/nodejs/node_modules:$LAMBDA_RUNTIME_DIR/node_modules).
• PYTHONPATH – (Python 2.7, 3.6, 3.8 (p. 350)) The Python library path ($LAMBDA_RUNTIME_DIR).
• GEM_PATH – (Ruby (p. 368)) The Ruby library path ($LAMBDA_TASK_ROOT/vendor/bundle/
ruby/2.5.0:/opt/ruby/gems/2.5.0).
• _X_AMZN_TRACE_ID – The X-Ray tracing header (p. 314).
• AWS_XRAY_CONTEXT_MISSING – For X-Ray tracing, Lambda sets this to LOG_ERROR to avoid throwing
runtime errors from the X-Ray SDK.
• AWS_XRAY_DAEMON_ADDRESS – For X-Ray tracing, the IP address and port of the X-Ray daemon.

The sample values shown reflect the latest runtimes. The presence of specific variables or their values
can vary on earlier runtimes.

Securing environment variables


Lambda encrypts environment variables with a key that it creates in your account (an AWS managed
customer master key (CMK)). Use of this key is free. You can also choose to provide your own key for
Lambda to use instead of the default key.

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.

To use a customer managed CMK

1. Open the Lambda console Functions page.


2. Choose a function.
3. Under Environment variables, choose Edit.
4. Expand Encryption configuration.

63
AWS Lambda Developer Guide
Securing environment variables

5. Choose Use a customer master key.


6. Choose your customer managed CMK.
7. Choose Save.

Customer managed CMKs incur standard AWS KMS charges.

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.

• kms:ListAliases – To view keys in the Lambda console.


• kms:CreateGrant, kms:Encrypt – To configure a customer managed CMK on a function.
• kms:Decrypt – To view and manage environment variables that are encrypted with a customer
managed CMK.

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.

Example IAM policy – Deny access by key ARN

{
"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 encrypt environment variables on the client side

1. Open the Lambda console Functions page.


2. Choose a function.
3. Under Environment variables, choose Edit.
4. Expand Encryption configuration.
5. Choose Enable helpers for encryption in transit.
6. Choose Encrypt next to a variable to encrypt its value.
7. Choose Save.

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.

Configuring environment variables with the Lambda


API
To manage environment variables with the AWS CLI or AWS SDK, use the following API operations.

• UpdateFunctionConfiguration (p. 670)


• GetFunctionConfiguration (p. 570)
• CreateFunction (p. 531)

The following example sets two environment variables on a function named my-function.

$ aws lambda update-function-configuration --function-name my-function \


--environment "Variables={BUCKET=my-bucket,KEY=[Link]}"

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.

To get the current configuration, use the get-function-configuration command.

$ aws lambda get-function-configuration --function-name my-function


{
"FunctionName": "my-function",
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function",
"Runtime": "nodejs12.x",
"Role": "arn:aws:iam::123456789012:role/lambda-role",
"Environment": {
"Variables": {
"BUCKET": "my-bucket",
"KEY": "[Link]"
}
},
"RevisionId": "0894d3c1-2a3d-4d48-bf7f-abade99f3c15",
...
}

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.

To configure a function's encryption key, set the KMSKeyARN option.

$ aws lambda update-function-configuration --function-name my-function \


--kms-key-arn arn:aws:kms:us-east-2:123456789012:key/055efbb4-xmpl-4336-
ba9c-538c7d31f599

Sample code and templates


Sample applications in this guide's GitHub repository demonstrate the use of environment variables in
function code and AWS CloudFormation templates.

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

Managing concurrency for a Lambda function


Concurrency is the number of requests that your function is serving at any given time. When your
function is invoked, Lambda allocates 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 allocated, which increases the function's 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)

Configuring reserved concurrency


To manage reserved concurrency settings for a function, use the Lambda console.

To reserve concurrency for a function

1. Open the Lambda console Functions page.


2. Choose a function.
3. Under Concurrency, choose Reserve concurrency.
4. Enter the amount of concurrency to reserve for the function.
5. Choose Save.

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

Reserving concurrency has the following effects.

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.

Configuring provisioned concurrency


To manage provisioned concurrency settings for a version or alias, use the Lambda console.

To reserve concurrency for an alias

1. Open the Lambda console Functions page.


2. Choose a function.
3. Under Provisioned concurrency configurations, choose Add.
4. Choose an alias or version.
5. Enter the amount of provisioned concurrency to allocate.
6. Choose Save.

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.

Lambda emits the following metrics for provisioned concurrency:

Provisioned concurrency metrics

• ProvisionedConcurrentExecutions
• ProvisionedConcurrencyInvocations
• ProvisionedConcurrencySpilloverInvocations
• ProvisionedConcurrencyUtilization

For details, see Working with AWS Lambda function metrics (p. 478).

Configuring concurrency with the Lambda API


To manage concurrency settings and autoscaling with the AWS CLI or AWS SDK, use the following API
operations.

• PutFunctionConcurrency (p. 635)


• GetFunctionConcurrency
• DeleteFunctionConcurrency (p. 548)
• PutProvisionedConcurrencyConfig
• GetProvisionedConcurrencyConfig
• ListProvisionedConcurrencyConfigs
• DeleteProvisionedConcurrencyConfig
• GetAccountSettings (p. 556)
• (Application Auto Scaling) RegisterScalableTarget
• (Application Auto Scaling) PutScalingPolicy

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:

$ aws lambda put-function-concurrency --function-name my-function --reserved-concurrent-


executions 100
{
"ReservedConcurrentExecutions": 100
}

To allocate provisioned concurrency for a function, use put-provisioned-concurrency-config.


The following command allocates a concurrency of 100 for the BLUE alias of a function named my-
function:

$ aws lambda put-provisioned-concurrency-config --function-name my-function \


--qualifier BLUE --provisioned-concurrent-executions 100

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:

$ aws application-autoscaling register-scalable-target --service-namespace lambda \


--resource-id function:my-function:BLUE --min-capacity 1 --max-capacity 100 \
--scalable-dimension lambda:function:ProvisionedConcurrency

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:

$ aws application-autoscaling put-scaling-policy --service-namespace lambda \


--scalable-dimension lambda:function:ProvisionedConcurrency --resource-id function:my-
function:BLUE \
--policy-name my-policy --policy-type TargetTrackingScaling \
--target-tracking-scaling-policy-configuration '{ "TargetValue":
0.7, "PredefinedMetricSpecification": { "PredefinedMetricType":
"LambdaProvisionedConcurrencyUtilization" }}'
{
"PolicyARN": "arn:aws:autoscaling:us-east-2:123456789012:scalingPolicy:12266dbb-1524-
xmpl-a64e-9a0a34b996fa:resource/lambda/function:my-function:BLUE:policyName/my-policy",
"Alarms": [
{
"AlarmName": "TargetTracking-function:my-function:BLUE-AlarmHigh-aed0e274-
xmpl-40fe-8cba-2e78f000c0a7",
"AlarmARN": "arn:aws:cloudwatch:us-east-2:123456789012:alarm:TargetTracking-
function:my-function:BLUE-AlarmHigh-aed0e274-xmpl-40fe-8cba-2e78f000c0a7"
},
{
"AlarmName": "TargetTracking-function:my-function:BLUE-AlarmLow-7e1a928e-
xmpl-4d2b-8c01-782321bc6f66",
"AlarmARN": "arn:aws:cloudwatch:us-east-2:123456789012:alarm:TargetTracking-
function:my-function:BLUE-AlarmLow-7e1a928e-xmpl-4d2b-8c01-782321bc6f66"
}
]
}

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

To view your account's concurrency limits in a Region, use get-account-settings.

$ aws lambda get-account-settings


{
"AccountLimit": {
"TotalCodeSize": 80530636800,
"CodeSizeUnzipped": 262144000,

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

AWS Lambda function versions


You can use versions to manage the deployment of your AWS Lambda functions. For example, you can
publish a new version of a function for beta testing without affecting users of the stable production
version.

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:

• The function code and all associated dependencies.


• The Lambda runtime that executes the function.
• All of the function settings, including the environment variables.
• A unique Amazon Resource Name (ARN) to identify this version of the function.

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).

To create a new version of a function

1. Open the Lambda console Functions page.


2. Choose the function that you want to publish.
3. In Actions, choose Publish new version.

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.

Managing versions with the Lambda API


To publish a version of a function, use the PublishVersion (p. 628) API action.

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.

$ aws lambda publish-version --function-name my-function


{
"FunctionName": "my-function",
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:1",
"Version": "1",
"Role": "arn:aws:iam::123456789012:role/lambda-role",
"Handler": "[Link]",
"Runtime": "nodejs12.x",
...
}

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

• Qualified ARN – The function ARN with the version suffix.

arn:aws:lambda:aws-region:acct-id:function:helloworld:$LATEST

• Unqualified ARN – The function ARN without the version suffix.

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

AWS Lambda function aliases


You can create one or more aliases for your AWS Lambda function. A Lambda alias is like a pointer to a
specific Lambda function version. Users can access the function version using the alias ARN.

To create an alias

1. Open the Lambda console Functions page.


2. Choose a function.
3. In Actions, choose Create 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.

Managing aliases with the Lambda API


To create an alias, use the create-alias command.

$ aws lambda create-alias --function-name my-function --name alias-name --function-


version version-number --description " "

To change an alias to point a new version of the function, use the update-alias command.

$ aws lambda update-alias --function-name my-function --name alias-name --function-


version version-number

The AWS CLI commands in the preceding steps correspond to the following AWS Lambda APIs:

• CreateAlias (p. 521)


• UpdateAlias (p. 653)

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.

$ aws lambda add-permission --function-name helloworld \


--qualifier PROD --statement-id 1 --principal [Link] --action
lambda:InvokeFunction \
--source-arn arn:aws:s[Link]xamplebucket --source-account 123456789012

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.

Alias routing configuration


Use routing configuration on an alias to send a portion of traffic to a second function version. For
example, you can reduce the risk of deploying a new version by configuring the alias to send most of the
traffic to the existing version, and only a small percentage of traffic to the new version.

You can point an alias to a maximum of two Lambda function versions. The versions must meet the
following criteria:

• Both versions must have the same IAM execution role.


• Both versions must have the same dead-letter queue configuration, or no dead-letter queue
configuration.
• Both versions must be published. The alias cannot point to $LATEST.

To configure routing on an alias

1. Open the Lambda console Functions page.


2. Choose a function.
3. Verify that the function has at least two published versions. To do this, choose Qualifiers and then
choose Versions to display the list of versions. If you need to create additional versions, follow the
instructions in AWS Lambda function versions (p. 76).
4. On the Actions menu, choose Create alias.

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:

a. Choose the second Lambda function version.


b. Enter a weight value for the function. Weight is the percentage of traffic that is assigned
to that version when the alias is invoked. The first version receives the residual weight. For
example, if you specify 10 percent to Additional version, the first version is assigned 90 percent
automatically.
7. Choose Create.

Configuring alias routing


Use the create-alias and update-alias commands to configure the traffic weights between two
function versions. When you create or update the alias, you specify the traffic weight in the routing-
config parameter.

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.

$ aws lambda create-alias --name routing-alias --function-name my-function --function-


version 1 \
--routing-config AdditionalVersionWeights={"2"=0.03}

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.

$ aws lambda update-alias --name routing-alias --function-name my-function \


--routing-config AdditionalVersionWeights={"2"=0.05}

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.

$ aws lambda update-alias --name routing-alias --function-name my-function \


--function-version 2 --routing-config AdditionalVersionWeights={}

The CLI commands in the preceding steps correspond to the following AWS Lambda API operations:

• CreateAlias (p. 521)


• UpdateAlias (p. 653)

Determining which version has been invoked


When you configure traffic weights between two function versions, there are two ways to determine the
Lambda function version that has been invoked:

• 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:

[Link] START RequestId: request id Version: $version

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

• Response payload (synchronous invocations) – Responses to synchronous function invocations


include an x-amz-executed-version header to indicate which function version has been invoked.

82
AWS Lambda Developer Guide
Layers

AWS Lambda layers


You can configure your Lambda function to pull in additional code and content in the form of layers. A
layer is a ZIP archive that contains libraries, a custom runtime (p. 133), or other dependencies. With
layers, you can use libraries in your function without needing to include them in your deployment
package.

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)

Configuring a function to use layers


You can specify up to 5 layers in your function's configuration, during or after function creation. You
choose a specific version of a layer to use. If you want to use a different version later, update your
function's configuration.

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.

$ aws lambda update-function-configuration --function-name my-function \


--layers arn:aws:lambda:us-east-2:123456789012:layer:my-layer:3
\
arn:aws:lambda:us-east-2:210987654321:layer:their-layer:2
{
"FunctionName": "test-layers",
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function",
"Runtime": "nodejs12.x",
"Role": "arn:aws:iam::123456789012:role/service-role/lambda-role",
"Layers": [
{
"Arn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer:3",

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.

$ aws lambda update-function-configuration --function-name my-function --layers []

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.

$ aws lambda publish-layer-version --layer-name my-layer --description "My layer" --


license-info "MIT" \
--content S3Bucket=lambda-layers-us-east-2-123456789012,S3Key=[Link] --compatible-
runtimes python3.6 python3.7
{
"Content": {
"Location": "[Link]
snapshots/123456789012/my-layer-4aaa2fbb-ff77-4b0a-ad92-5b78a716a96a?
versionId=27iWyA73cCAYqyH...",
"CodeSha256": "tv9jJO+rPbXUUXuRKi7CwHzKtLDkDRJLB3cC3Z/ouXo=",
"CodeSize": 169
},
"LayerArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer",
"LayerVersionArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer:1",
"Description": "My layer",
"CreatedDate": "2018-11-14T[Link].894+0000",
"Version": 1,
"LicenseInfo": "MIT",
"CompatibleRuntimes": [
"python3.6",
"python3.7",
"python3.8"
]
}

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.

$ aws lambda list-layers --compatible-runtime python3.8


{
"Layers": [
{
"LayerName": "my-layer",
"LayerArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer",
"LatestMatchingVersion": {
"LayerVersionArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-
layer:2",
"Version": 2,
"Description": "My layer",
"CreatedDate": "2018-11-15T[Link].592+0000",
"CompatibleRuntimes": [
"python3.6",
"python3.7",
"python3.8",
]
}
}
]
}

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.

$ aws lambda get-layer-version --layer-name my-layer --version-number 2


{
"Content": {
"Location": "[Link]
snapshots/123456789012/my-layer-91e9ea6e-492d-4100-97d5-a4388d442f3f?
versionId=GmvPV.309OEpkfN...",
"CodeSha256": "tv9jJO+rPbXUUXuRKi7CwHzKtLDkDRJLB3cC3Z/ouXo=",
"CodeSize": 169
},
"LayerArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer",
"LayerVersionArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer:2",
"Description": "My layer",
"CreatedDate": "2018-11-15T[Link].592+0000",
"Version": 2,
"CompatibleRuntimes": [
"python3.6",
"python3.7",
"python3.8"
]
}

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.

$ aws lambda delete-layer-version --layer-name my-layer --version-number 1

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

Including library dependencies in a layer


You can move runtime dependencies out of your function code by placing them in a layer. Lambda
runtimes include paths in the /opt directory to ensure that your function code has access to libraries
that are included in layers.

To include libraries in a layer, place them in one of the folders supported by your runtime.

• [Link] – nodejs/node_modules, nodejs/node8/node_modules (NODE_PATH)

Example AWS X-Ray SDK for [Link]

[Link]
# nodejs/node_modules/aws-xray-sdk

• Python – python, python/lib/python3.8/site-packages (site directories)

Example Pillow

[Link]
# python/PIL
# python/[Link]-info

• Java – java/lib (classpath)

Example Jackson

[Link]
# java/lib/[Link]

• Ruby – ruby/gems/2.5.0 (GEM_PATH), ruby/lib (RUBYLIB)

Example JSON

[Link]
# ruby/gems/2.5.0/
| build_info
| cache
| doc
| extensions
| gems
| # json-2.1.0
# specifications
# [Link]

• All – bin (PATH), lib (LD_LIBRARY_PATH)

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.

$ aws lambda add-layer-version-permission --layer-name xray-sdk-nodejs --statement-id


xaccount \
--action lambda:GetLayerVersion --principal 210987654321 --version-number 1 --output text
e210ffdc-e901-43b0-824b-5fcd0dd26d16 {"Sid":"xaccount","Effect":"Allow","Principal":
{"AWS":"arn:aws:iam::210987654321:root"},"Action":"lambda:GetLayerVersion","Resource":"arn:aws:lambda:u
east-2:123456789012:layer:xray-sdk-nodejs:1"}

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

Configuring a Lambda function to access resources


in a VPC
You can configure a function to connect to private subnets in a virtual private cloud (VPC) in your
account. Use Amazon Virtual Private Cloud (Amazon VPC) to create a private network for resources such
as databases, cache instances, or internal services. Connect your function to the VPC to access private
resources during execution.

To connect a function to a VPC

1. Open the Lambda console.


2. Choose a function.
3. Under VPC, choose Edit.
4. Choose Custom VPC.
5. Choose a VPC, subnets, and security groups.
Note
Connect your function to private subnets to access private resources. If your function needs
internet access, use NAT (p. 90). Connecting a function to a public subnet does not give it
internet access or a public IP address.
6. Choose Save.

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

Execution role and user permissions


Lambda uses your function's permissions to create and manage network interfaces. To connect to a VPC,
your function's execution role must have the following permissions.

Execution role permissions

• ec2:CreateNetworkInterface
• ec2:DescribeNetworkInterfaces
• ec2:DeleteNetworkInterface

These permissions are included in the AWSLambdaVPCAccessExecutionRole managed policy.

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

Configuring Amazon VPC access with the Lambda API


You can connect a function to a VPC with the following APIs.

• CreateFunction (p. 531)


• UpdateFunctionConfiguration (p. 670)

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.

$ aws lambda create-function --function-name my-function \


--runtime nodejs12.x --handler [Link] --zip-file fileb://[Link] \
--role arn:aws:iam::123456789012:role/lambda-role \
--vpc-config
SubnetIds=subnet-071f712345678e7c8,subnet-07fd123456788a036,SecurityGroupIds=sg-085912345678492fb

To connect an existing function, use the vpc-config option with the update-function-
configuration command.

$ aws lambda update-function-configuration --function-name my-function \


--vpc-config
SubnetIds=subnet-071f712345678e7c8,subnet-07fd123456788a036,SecurityGroupIds=sg-085912345678492fb

To disconnect your function from a VPC, update the function configuration with an empty list of subnets
and security groups.

$ aws lambda update-function-configuration --function-name my-function \


--vpc-config SubnetIds=[],SecurityGroupIds=[]

89
AWS Lambda Developer Guide
Internet and service access for VPC-connected functions

Internet and service access for VPC-connected


functions
By default, Lambda runs your functions in a secure VPC with access to AWS services and the internet.
The VPC is owned by Lambda and does not connect to your account's default VPC. When you connect
a function to a VPC in your account, it does not have access to the internet unless your VPC provides
access.
Note
Several services offer VPC endpoints. You can use VPC endpoints to connect to AWS services
from within a VPC without internet access.

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.

Sample VPC configurations


Sample AWS CloudFormation templates for VPC configurations that you can use with Lambda functions
are available in this guide's GitHub repository. There are two templates:

• [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

Configuring database access for a Lambda


function
You can use the Lambda console to create an Amazon RDS Proxy database proxy for your function. A
database proxy manages a pool of database connections and relays queries from a function. This enables
a function to reach high concurrency (p. 21) levels without exhausting database connections.

To create a database proxy

1. Open the Lambda console Functions page.


2. Choose a function.
3. Choose Add database proxy.
4. Configure the following options.

• Proxy identifier – The name of the proxy.


• RDS DB instance – A supported MySQL or PostgreSQL DB instance or cluster.
• Secret – A Secrets Manager secret with the database user name and password.

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)

Using the function's permissions for authentication


By default, you can connect to a proxy with the same username and password that it uses to connect to
the database. The only difference in your function code is the endpoint that the database client connects
to. The drawback of this method is that you must expose the password to your function code, either by
configuring it in a secure environment variable or by retrieving it from Secrets Manager.

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].

Example dbadmin/[Link] – AWS SDK signer

const signer = new [Link]({


region: region,
hostname: host,
port: sqlport,
username: username
})

[Link] = async (event) => {


let connectionConfig = {
host : host,
user : username,
database : database,
ssl: 'Amazon RDS',
authPlugins: { mysql_clear_password: () => () => [Link]() }
}
var connection = [Link](connectionConfig)
var query = [Link]
var result
[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

Tagging Lambda Functions


You can tag Lambda functions to organize them by owner, project or department. Tags are freeform
key-value pairs that are supported across AWS services for use in filtering resources and adding detail to
billing reports.

To add tags to a function

1. Open the Lambda console Functions page.


2. Choose a function.
3. Under Tags, choose Manage tags.
4. Enter a key and value. To add additional tags, choose Add new tag.

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.

To filter functions with tags

1. Open the Lambda console Functions page.


2. Click within the search bar to see a list of function attributes and tag keys.

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)

Using Tags with the AWS CLI


When you create a new Lambda function, you can include tags with the --tags option.

96
AWS Lambda Developer Guide
Tag Key and Value Requirements

$ aws lambda create-function --function-name my-function


--handler [Link] --runtime nodejs12.x \
--role arn:aws:iam::123456789012:role/lambda-role \
--tags Department=Marketing,CostCenter=1234ABCD

To add tags to an existing function, use the tag-resource command.

$ aws lambda tag-resource \


--resource arn:aws:lambda:us-east-2:123456789012:function:my-function \
--tags Department=Marketing,CostCenter=1234ABCD

To remove tags, use the untag-resource command.

$ aws lambda untag-resource --resource function arn \


--tag-keys Department

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:

$ aws lambda list-tags --resource function arn

• GetFunction (p. 565) – You supply your Lambda function name to a view a list of the tags associated
with this function:

$ aws lambda get-function --function-name my-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.

Tag Key and Value Requirements


The following requirements apply to tags:

• Maximum number of tags per resource—50


• Maximum key length—128 Unicode characters in UTF-8
• Maximum value length—256 Unicode characters in UTF-8
• Tag keys and values are case sensitive.
• Do not use the aws: prefix in your tag names or values because it is reserved for AWS use. You can't
edit or delete tag names or values with this prefix. Tags with this prefix do not count against your tags
per resource limit.
• If your tagging schema will be used across multiple services and resources, remember that other
services may have restrictions on allowed characters. Generally allowed characters are: letters, spaces,
and numbers representable in UTF-8, plus the following special characters: + - = . _ : / @.

97
AWS Lambda Developer Guide

Invoking AWS Lambda functions


You can invoke Lambda functions directly with the Lambda console (p. 4), the Lambda API, the AWS SDK,
the AWS CLI, and AWS toolkits. You can also configure other AWS services to invoke your function, or you
can configure Lambda to read from a stream or queue and invoke your function.

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.

$ aws lambda invoke --function-name my-function --payload value [Link]


An error occurred (InvalidRequestContentException) when calling the Invoke operation: Could
not parse request body into json: Unrecognized token 'value': was expecting ('true',
'false' or 'null')
at [Source: (byte[])"value"; line: 1, column: 11]

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

$ aws lambda invoke --function-name my-function out --log-type Tail


{
"StatusCode": 200,
"LogResult":
"U1RBUlQgUmVxdWVzdElkOiA4N2QwNDRiOC1mMTU0LTExZTgtOGNkYS0yOTc0YzVlNGZiMjEgVmVyc2lvb...",
"ExecutedVersion": "$LATEST"
}

You can use the base64 utility to decode the logs.

$ aws lambda invoke --function-name my-function out --log-type Tail \


--query 'LogResult' --output text | base64 -d
START RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Version: $LATEST
"AWS_SESSION_TOKEN": "AgoJb3JpZ2luX2VjELj...", "_X_AMZN_TRACE_ID": "Root=1-5d02e5ca-
f5792818b6fe8368e5b51d50;Parent=191db58857df8395;Sampled=0"",ask/lib:/opt/lib",
END RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8
REPORT RequestId: 57f231fb-1730-4395-85cb-4f71bd2b87b8 Duration: 79.67 ms Billed
Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB

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.

$ aws lambda invoke --function-name my-function --invocation-type Event --payload


'{ "key": "value" }' [Link]
{
"StatusCode": 202
}

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.

• Amazon SQS – A standard SQS queue.


• Amazon SNS – An SNS topic.
• AWS Lambda – A Lambda function.

102
AWS Lambda Developer Guide
Configuring error handling for asynchronous invocation

• Amazon EventBridge – An EventBridge event bus.

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)

Configuring error handling for asynchronous


invocation
Use the Lambda console to configure error handling settings on a function, a version, or an alias.

To configure error handling

1. Open the Lambda console Functions page.


2. Choose a function.
3. Under Asynchronous invocation, choose Edit.
4. Configure the following settings.

• 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.

Configuring destinations for asynchronous invocation


To send records of asynchronous invocations to another service, add a destination to your function.
You can configure separate destinations for events that fail processing and events that are successfully
processed. Like error handling settings, you can configure destinations on a function, a version, or an
alias.

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:

• Amazon SQS – sqs:SendMessage


• Amazon SNS – sns:Publish
• Lambda – lambda:InvokeFunction
• EventBridge – events:PutEvents

Add destinations to your function in the Lambda console's function designer.

To configure a destination for asynchronous invocation records

1. Open the Lambda console Functions page.


2. Choose a function.
3. Under Designer, choose Add destination.

104
AWS Lambda Developer Guide
Asynchronous invocation configuration API

4. For Source, choose Asynchronous invocation.


5. For Condition, choose from the following options:

• 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.

Example invocation record

{
"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.

Asynchronous invocation configuration API


To manage asynchronous invocation settings with the AWS CLI or AWS SDK, use the following API
operations.

• 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.

$ aws lambda put-function-event-invoke-config --function-name error \


--maximum-event-age-in-seconds 3600 --maximum-retry-attempts 0
{
"LastModified": 1573686021.479,
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:error:$LATEST",
"MaximumRetryAttempts": 0,
"MaximumEventAgeInSeconds": 3600,
"DestinationConfig": {
"OnSuccess": {},
"OnFailure": {}
}
}

The put-function-event-invoke-config command overwrites any existing configuration on the


function, version, or alias. To configure an option without resetting others, use update-function-
event-invoke-config. The following example configures Lambda to send a record to an SQS queue
named destination when an event can't be processed.

$ aws lambda update-function-event-invoke-config --function-name error \


--destination-config '{"OnFailure":{"Destination": "arn:aws:sqs:us-
east-2:123456789012:destination"}}'
{
"LastModified": 1573687896.493,
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:error:$LATEST",
"MaximumRetryAttempts": 0,
"MaximumEventAgeInSeconds": 3600,
"DestinationConfig": {
"OnSuccess": {},
"OnFailure": {
"Destination": "arn:aws:sqs:us-east-2:123456789012:destination"
}
}
}

AWS Lambda function dead-letter queues


As an alternative to an on-failure destination (p. 103), you can configure your function with a dead-
letter queue to save discarded events for further processing. A dead-letter queue acts the same as an
on-failure destination in that it is used when an event fails all processing attempts or expires without
being processed. However, a dead-letter queue is part of a function's version-specific configuration, so
it is locked in when you publish a version. On-failure destinations also support additional targets and
include details about the function's response in the invocation record.

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.

Create a queue in the Amazon SQS console.


• Amazon SNS topic – A topic relays failed events to one or more destinations. You can configure a topic
to send events to an email address, a Lambda function, or an HTTP endpoint.

Create a topic in the Amazon SNS console.

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).

• Amazon SQS – sqs:SendMessage


• Amazon SNS – sns:Publish

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

1. Open the Lambda console Functions page.


2. Choose a function.
3. Under Asynchronous invocation, choose Edit.
4. Set DLQ resource to Amazon SQS or Amazon SNS.
5. Choose the target queue or topic.
6. Choose Save.

To configure a dead-letter queue with the AWS CLI, use the update-function-configuration
command.

$ aws lambda update-function-configuration --function-name my-function \


--dead-letter-config TargetArn=arn:aws:sns:us-east-2:123456789012:my-topic

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.

Dead-letter queue message attributes

• 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

AWS Lambda event source mappings


An event source mapping is an AWS Lambda resource that reads from an event source and invokes
a Lambda function. You can use event source mappings to process items from a stream or queue in
services that don't invoke Lambda functions directly. Lambda provides event source mappings for the
following services.

Services that Lambda reads events from

• Amazon Kinesis (p. 257)


• Amazon DynamoDB (p. 223)
• Amazon Simple Queue Service (p. 304)

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:

• CreateEventSourceMapping (p. 525)


• ListEventSourceMappings (p. 602)
• GetEventSourceMapping (p. 561)
• UpdateEventSourceMapping (p. 657)
• DeleteEventSourceMapping (p. 542)

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.

$ aws lambda create-event-source-mapping --function-name my-function --batch-size 500 --


starting-position LATEST \
--event-source-arn arn:aws:dynamodb:us-east-2:123456789012:table/my-table/
stream/2019-06-10T[Link].525
{
"UUID": "14e0db71-5d35-4eb5-b481-8945cf9d10c2",
"BatchSize": 500,
"MaximumBatchingWindowInSeconds": 0,
"ParallelizationFactor": 1,
"EventSourceArn": "arn:aws:dynamodb:us-east-2:123456789012:table/my-table/
stream/2019-06-10T[Link].525",
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function",
"LastModified": 1560209851.963,
"LastProcessingResult": "No records processed",
"State": "Creating",
"StateTransitionReason": "User action",
"DestinationConfig": {},
"MaximumRecordAgeInSeconds": 604800,
"BisectBatchOnFunctionError": false,
"MaximumRetryAttempts": 10000
}

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.

• Amazon SQS – An SQS queue.


• Amazon SNS – An SNS topic.

The invocation record contains details about the failed event batch in JSON format.

The following example shows an invocation record for a Kinesis stream.

Example invocation Record

{
"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

Monitoring the state of a function with the


Lambda API
When you create or update a function, Lambda provisions the compute and networking resources that
enable it to run. In most cases, this process is very fast, and your function is ready to be invoked or
modified right away.

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.

$ aws lambda get-function-configuration --function-name my-function


{
"FunctionName": "my-function",
"FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function",
"Runtime": "nodejs12.x",
"Role": "arn:aws:iam::123456789012:role/lambda-role",
"TracingConfig": {
"Mode": "Active"
},
"State": "Pending",
"StateReason": "The function is being created.",
"StateReasonCode": "Creating",
...
}

The StateReason and StateReasonCode contain additional information about the state when it is not
Active. The following operations fail while function creation is pending:

• Invoke (p. 592)


• UpdateFunctionCode (p. 663)
• UpdateFunctionConfiguration (p. 670)
• PublishVersion (p. 628)

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.

Example Function configuration – Connecting to a VPC

{
"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",
...
}

The following operations fail while an asynchronous update is in progress:

• UpdateFunctionCode (p. 663)


• UpdateFunctionConfiguration (p. 670)
• PublishVersion (p. 628)

Other operations, including invocation, work while updates are in progress.

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:

• InsufficientRolePermission – Role doesn't exist or is missing permissions.


• SubnetOutOfIPAddresses – All IP addresses in a subnet are in use.

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

AWS Lambda function scaling


The first time you invoke your function, AWS Lambda creates an instance of the function and runs its
handler method to process the event. When the function returns a response, it stays active and waits
to process additional events. If you invoke the function again while the first event is being processed,
Lambda initializes another instance, and the function processes the two events concurrently. As more
events come in, Lambda routes them to available instances and creates new instances as needed. When
the number of requests decreases, Lambda stops unused instances to free up scaling capacity for other
functions.

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.

Burst concurrency limits

• 3000 – US West (Oregon), US East (N. Virginia), Europe (Ireland)


• 1000 – Asia Pacific (Tokyo), Europe (Frankfurt)
• 500 – Other Regions

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.

• Asynchronous invocation (p. 101)


• AWS Lambda event source mappings (p. 109)
• Error handling and automatic retries in AWS Lambda (p. 119)
• Using AWS Lambda with other services (p. 166)

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

Error handling and automatic retries in AWS


Lambda
When you invoke a function, two types of error can occur. Invocation errors occur when the invocation
request is rejected before your function receives it. Function errors occur when your function's code or
runtime (p. 129) returns an error. Depending on the type of error, the type of invocation, and the client
or service that invokes the function, the retry behavior and the strategy for managing errors varies.

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.

Common invocation errors

• 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.

Common function errors

• Function – Your function's code throws an exception or returns an error object.


• Runtime – The runtime terminated your function because it ran out of time, detected a syntax error, or
failed to marshal the response object into JSON. The function exited with an error code.

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.

• AWS Lambda function errors in [Link] (p. 344)


• AWS Lambda function errors in Python (p. 363)
• AWS Lambda function errors in Ruby (p. 379)
• AWS Lambda function errors in Java (p. 408)
• AWS Lambda function errors in Go (p. 435)
• AWS Lambda function errors in C# (p. 458)
• AWS Lambda function errors in PowerShell (p. 475)

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

Invoking Lambda functions with the AWS Mobile


SDK for Android
You can call a Lambda function from a mobile application. Put business logic in functions to separate
its development lifecycle from that of front-end clients, making mobile applications less complex to
develop and maintain. With the Mobile SDK for Android, you use Amazon Cognito to authenticate users
and authorize requests (p. 121).

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)

Tutorial: Using AWS Lambda with the Mobile SDK for


Android
In this tutorial, you create a simple Android mobile application that uses Amazon Cognito to get
credentials and invokes a Lambda function.

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:

~/lambda-project$ this is a command


this is output

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.

Create the execution role


Create the execution role (p. 37) that gives your function permission to access AWS resources.

To create an execution role

1. Open the roles page in the IAM console.


2. Choose Create role.
3. Create a role with the following properties.

• Trusted entity – AWS Lambda.


• Permissions – AWSLambdaBasicExecutionRole.
• Role name – lambda-android-role.

The AWSLambdaBasicExecutionRole policy has the permissions that the function needs to write logs to
CloudWatch Logs.

Create the function


The following example uses data to generate a string response.
Note
For sample code in other languages, see Sample function code (p. 127).

Example [Link]

[Link] = function(event, context, callback) {


[Link]("Received event: ", event);
var data = {
"greetings": "Hello, " + [Link] + " " + [Link] + "."
};
callback(null, data);
}

To create the function

1. Copy the sample code into a file named [Link].


2. Create a deployment package.

122
AWS Lambda Developer Guide
Tutorial

$ zip [Link] [Link]

3. Create a Lambda function with the create-function command.

$ aws lambda create-function --function-name AndroidBackendLambdaFunction \


--zip-file fileb://[Link] --handler [Link] --runtime nodejs12.x \
--role arn:aws:iam::123456789012:role/lambda-android-role

Test the Lambda function


Invoke the function manually using the sample event data.

To test the Lambda function (AWS CLI)

1. Save the following sample event JSON in a file, [Link].

{ "firstName": "first-name", "lastName": "last-name" }

2. Execute the following invoke command:

$ aws lambda invoke --function-name AndroidBackendLambdaFunction \


--payload [Link] [Link]

Create an Amazon Cognito identity pool


In this section, you create an Amazon Cognito identity pool. The identity pool has two IAM
roles. You update the IAM role for unauthenticated users and grant permissions to execute the
AndroidBackendLambdaFunction Lambda function.

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.

To create an identity pool

1. Open the Amazon Cognito console.


2. Create a new identity pool called JavaFunctionAndroidEventHandlerPool. Before you follow
the procedure to create an identity pool, note the following:

• 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

The resulting policy will be as follows:

{
"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.

Create an Android application


Create a simple Android mobile application that generates events and invokes Lambda functions by
passing the event data as parameters.

The following instructions have been verified using Android studio.

1. Create a new Android project called AndroidEventGenerator using the following configuration:

• Select the Phone and Tablet platform.


• Choose Blank Activity.
2. In the [Link] (Module:app) file, add the following in the dependencies section:

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.

<uses-permission android:name="[Link]" />

124
AWS Lambda Developer Guide
Tutorial

<uses-permission android:name="[Link].ACCESS_NETWORK_STATE" />

5. In MainActivity, add the following imports:

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 String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


[Link] = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


[Link] = lastName;
}

public RequestClass(String firstName, String lastName) {


[Link] = firstName;
[Link] = lastName;
}

public RequestClass() {
}
}

• ResponseClass

package [Link]....lambdaeventgenerator;
public class ResponseClass {
String greetings;

public String getGreetings() {


return greetings;
}

public void setGreetings(String greetings) {


[Link] = greetings;
}

public ResponseClass(String greetings) {


[Link] = 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 an instance of CognitoCachingCredentialsProvider


CognitoCachingCredentialsProvider cognitoProvider = new
CognitoCachingCredentialsProvider(
[Link](), "identity-pool-id", Regions.US_WEST_2);

// Create LambdaInvokerFactory, to be used to instantiate the Lambda proxy.


LambdaInvokerFactory factory = new LambdaInvokerFactory([Link](),
Regions.US_WEST_2, cognitoProvider);

// 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]);

RequestClass request = new RequestClass("John", "Doe");


// The Lambda function invocation results in a network call.
// Make sure it is not called from the main thread.
new AsyncTask<RequestClass, Void, ResponseClass>() {
@Override
protected ResponseClass doInBackground(RequestClass... params) {
// invoke "echo" method. In case it fails, it will throw a
// LambdaFunctionException.
try {
return [Link](params[0]);
} catch (LambdaFunctionException lfe) {
Log.e("Tag", "Failed to invoke echo", lfe);
return null;
}
}

@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);

9. Run the code and verify it as follows:

• The [Link]() displays the response returned.


• Verify that CloudWatch Logs shows the log created by the Lambda function. It should show the
event data (first name and last name). You can also verify this in the AWS Lambda console.

Sample function code


Sample code is available for the following languages.

Topics
• [Link] (p. 127)
• Java (p. 127)

[Link]
The following example uses data to generate a string response.

Example [Link]

[Link] = function(event, context, callback) {


[Link]("Received event: ", event);
var data = {
"greetings": "Hello, " + [Link] + " " + [Link] + "."
};
callback(null, data);
}

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];

public class HelloPojo {

// Define two classes/POJOs for use with Lambda function.


public static class RequestClass {
String firstName;
String lastName;

127
AWS Lambda Developer Guide
Sample code

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


[Link] = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


[Link] = lastName;
}

public RequestClass(String firstName, String lastName) {


[Link] = firstName;
[Link] = lastName;
}

public RequestClass() {
}
}

public static class ResponseClass {


String greetings;

public String getGreetings() {


return greetings;
}

public void setGreetings(String greetings) {


[Link] = greetings;
}

public ResponseClass(String greetings) {


[Link] = greetings;
}

public ResponseClass() {
}

public static ResponseClass myHandler(RequestClass request, Context context){


String greetingString = [Link]("Hello %s, %s.", [Link],
[Link]);
[Link]().log(greetingString);
return new ResponseClass(greetingString);
}
}

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

AWS Lambda runtimes


AWS Lambda supports multiple languages through the use of runtimes. You choose a runtime when
you create a function, and you can change runtimes by updating your function's configuration. The
underlying execution environment provides additional libraries and environment variables (p. 61) that
you can access from your function code.

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

Name Identifier AWS SDK for Operating system


JavaScript

[Link] 12 nodejs12.x 2.631.0 Amazon Linux 2

[Link] 10 nodejs10.x 2.631.0 Amazon Linux 2

Python runtimes

Name Identifier AWS SDK for Python Operating system

Python 3.8 python3.8 boto3-1.12.22 Amazon Linux 2


botocore-1.15.22

Python 3.7 python3.7 boto3-1.12.22 Amazon Linux


botocore-1.15.22

Python 3.6 python3.6 boto3-1.12.22 Amazon Linux


botocore-1.15.22

Python 2.7 python2.7 boto3-1.12.22 Amazon Linux


botocore-1.15.22

129
AWS Lambda Developer Guide

Ruby runtimes

Name Identifier AWS SDK for Ruby Operating system

Ruby 2.7 ruby2.7 3.0.1 Amazon Linux 2

Ruby 2.5 ruby2.5 3.0.1 Amazon Linux

Java runtimes

Name Identifier JDK Operating system

Java 11 java11 amazon-corretto-11 Amazon Linux 2

Java 8 java8 java-1.8.0-openjdk Amazon Linux

Go runtimes

Name Identifier Operating system

Go 1.x go1.x Amazon Linux

.NET runtimes

Name Identifier Operating system

.NET Core 3.1 dotnetcore3.1 Amazon Linux 2

.NET Core 2.1 dotnetcore2.1 Amazon Linux

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

Name Identifier Operating system

Custom Runtime provided Amazon Linux

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

AWS Lambda execution context


When AWS Lambda executes your Lambda function, it provisions and manages the resources needed to
run your Lambda function. When you create a Lambda function, you specify configuration information,
such as the amount of memory and maximum execution time that you want to allow for your Lambda
function. When a Lambda function is invoked, AWS Lambda launches an execution context based on
the configuration settings you provide. The execution context is a temporary runtime environment that
initializes any external dependencies of your Lambda function code, such as database connections or
HTTP endpoints. This affords subsequent invocations better performance because there is no need to
"cold-start" or initialize those external dependencies, as explained below.

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

Runtime support policy


AWS Lambda runtimes (p. 129) are built around a combination of operating system, programming
language, and software libraries that are subject to maintenance and security updates. When a
component of a runtime is no longer supported for security updates, Lambda deprecates the runtime.

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.

The following runtimes have been deprecated:

Deprecated runtimes

Name Identifier Operating system Deprecation


completed date

.NET Core 1.0 dotnetcore1.0 Amazon Linux July 30, 2019

.NET Core 2.0 dotnetcore2.0 Amazon Linux May 30, 2019

[Link] 0.10 nodejs Amazon Linux October 31, 2016

[Link] 4.3 nodejs4.3 Amazon Linux March 6, 2020

[Link] 4.3 edge nodejs4.3-edge Amazon Linux April 30, 2019

[Link] 6.10 nodejs6.10 Amazon Linux August 12, 2019

[Link] 8.10 nodejs8.10 Amazon Linux March 6, 2020

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.

Language and framework support policies

• [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

Custom AWS Lambda runtimes


You can implement an AWS Lambda runtime in any programming language. A runtime is a program that
runs a Lambda function's handler method when the function is invoked. You can include a runtime in
your function's deployment package in the form of an executable file named bootstrap.

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)

Using a custom runtime


To use a custom runtime, set your function's runtime to provided. The runtime can be included in your
function's deployment package, or in a layer (p. 83).

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.

Building a custom runtime


A custom runtime's entry point is an executable file named bootstrap. The bootstrap file can be the
runtime, or it can invoke another file that creates the runtime. The following example uses a bundled
version of [Link] to execute a JavaScript runtime in a separate file named [Link].

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

REPORT RequestId: f8ac1208... Init Duration: 48.26 ms Duration: 237.17 ms Billed


Duration: 300 ms Memory Size: 128 MB Max Memory Used: 26 MB

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

AWS Lambda runtime interface


AWS Lambda provides an HTTP API for custom runtimes (p. 133) to receive invocation events from
Lambda and send response data back within the Lambda execution environment (p. 129).

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.

For example, 8476a536-e9f4-11e8-9739-2dfe598c3fcd.


• Lambda-Runtime-Deadline-Ms – The date that the function times out in Unix time milliseconds.

For example, 1542409706888.


• Lambda-Runtime-Invoked-Function-Arn – The ARN of the Lambda function, version, or alias
that's specified in the invocation.

For example, arn:aws:lambda:us-east-2:123456789012:function:custom-runtime.


• Lambda-Runtime-Trace-Id – The AWS X-Ray tracing header.

For example, Root=1-5bef4de7-


ad49b0e87f6ef6c87fc2e700;Parent=9a9197af755a6419;Sampled=1.
• Lambda-Runtime-Client-Context – For invocations from the AWS Mobile SDK, data about the
client application and device.
• Lambda-Runtime-Cognito-Identity – For invocations from the AWS Mobile SDK, data about the
Amazon Cognito identity provider.

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.

Example success request

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.

Example request body

{
"errorMessage" : "Error parsing event data.",
"errorType" : "InvalidEventDataException"
}

Example error request

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.

Example initialization error request

ERROR="{\"errorMessage\" : \"Failed to load function.\", \"errorType\" :


\"InvalidFunctionException\"}"
curl -X POST "[Link] -d "$ERROR"
--header "Lambda-Runtime-Function-Error-Type: Unhandled"

138
AWS Lambda Developer Guide
Tutorial – Custom runtime

Tutorial – Publishing a custom runtime


In this tutorial, you create a Lambda function with a custom runtime. You start by including the runtime
in the function's deployment package. Then you migrate it to a layer that you manage independently
from the function. Finally, you share the runtime layer with the world by updating its resource-based
permissions policy.

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:

~/lambda-project$ this is a command


this is output

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.

To create an execution role

1. Open the roles page in the IAM console.


2. Choose Create role.
3. Create a role with the following properties.

• Trusted entity – Lambda.


• Permissions – AWSLambdaBasicExecutionRole.
• Role name – lambda-role.

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

set -euo pipefail

# Initialization - load function handler


source $LAMBDA_TASK_ROOT/"$(echo $_HANDLER | cut -d. -f1).sh"

# 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")

# Extract request ID by scraping response headers received above


REQUEST_ID=$(grep -Fi Lambda-Runtime-Aws-Request-Id "$HEADERS" | tr -d '[:space:]' | cut
-d: -f2)

# Execute the handler function from the script


RESPONSE=$($(echo "$_HANDLER" | cut -d. -f2) "$EVENT_DATA")

# Send the response


curl -X POST "[Link]
response" -d "$RESPONSE"
done

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
}

Save both files in a project directory named runtime-tutorial.

runtime-tutorial
# bootstrap
# [Link]

Make the files executable and add them to a ZIP archive.

runtime-tutorial$ chmod 755 [Link] bootstrap


runtime-tutorial$ zip [Link] [Link] bootstrap
adding: [Link] (deflated 24%)
adding: bootstrap (deflated 39%)

Create a function named bash-runtime.

140
AWS Lambda Developer Guide
Create a layer

runtime-tutorial$ aws lambda create-function --function-name bash-runtime \


--zip-file fileb://[Link] --handler [Link] --runtime provided \
--role arn:aws:iam::123456789012:role/lambda-role
{
"FunctionName": "bash-runtime",
"FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:bash-runtime",
"Runtime": "provided",
"Role": "arn:aws:iam::123456789012:role/lambda-role",
"Handler": "[Link]",
"CodeSha256": "mv/xRv84LPCxdpcbKvmwuuFzwo7sLwUO1VxcUv3wKlM=",
"Version": "$LATEST",
"TracingConfig": {
"Mode": "PassThrough"
},
"RevisionId": "2e1d51b0-6144-4763-8e5c-7d5672a01713",
...
}

Invoke the function and verify the response.

runtime-tutorial$ aws lambda invoke --function-name bash-runtime --payload


'{"text":"Hello"}' [Link]
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
runtime-tutorial$ cat [Link]
Echoing request: '{"text":"Hello"}'

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.

Create a layer archive that contains the bootstrap file.

runtime-tutorial$ zip [Link] bootstrap


adding: bootstrap (deflated 39%)

Create a layer with the publish-layer-version command.

runtime-tutorial$ aws lambda publish-layer-version --layer-name bash-runtime --zip-file


fileb://[Link]
{
"Content": {
"Location": "[Link]
snapshots/123456789012/bash-runtime-018c209b...",
"CodeSha256": "bXVLhHi+D3H1QbDARUVPrDwlC7bssPxySQqt1QZqusE=",
"CodeSize": 584,
"UncompressedCodeSize": 0
},
"LayerArn": "arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime",
"LayerVersionArn": "arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:1",
"Description": "",
"CreatedDate": "2018-11-28T[Link].476+0000",
"Version": 1
}

141
AWS Lambda Developer Guide
Update the function

This creates the first version of the layer.

Update the function


To use the runtime layer with the function, configure the function to use the layer, and remove the
runtime code from the function.

Update the function configuration to pull in the layer.

runtime-tutorial$ aws lambda update-function-configuration --function-name bash-runtime \


--layers arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:1
{
"FunctionName": "bash-runtime",
"Layers": [
{
"Arn": "arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:1",
"CodeSize": 584,
"UncompressedCodeSize": 679
}
]
...
}

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.

runtime-tutorial$ zip [Link] [Link]


adding: [Link] (deflated 24%)
runtime-tutorial$ aws lambda update-function-code --function-name bash-runtime --zip-file
fileb://[Link]
{
"FunctionName": "bash-runtime",
"CodeSize": 270,
"Layers": [
{
"Arn": "arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:7",
"CodeSize": 584,
"UncompressedCodeSize": 679
}
]
...
}

Invoke the function to verify that it works with the runtime layer.

runtime-tutorial$ aws lambda invoke --function-name bash-runtime --payload


'{"text":"Hello"}' [Link]
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
runtime-tutorial$ cat [Link]
Echoing request: '{"text":"Hello"}'

Update the runtime


To log information about the execution environment, update the runtime script to output environment
variables.

142
AWS Lambda Developer Guide
Share the layer

Example bootstrap

#!/bin/sh

set -euo pipefail

echo "## Environment variables:"


env

# Initialization - load function handler


source $LAMBDA_TASK_ROOT/"$(echo $_HANDLER | cut -d. -f1).sh"
...

Create a second version of the layer with the new code.

runtime-tutorial$ zip [Link] bootstrap


updating: bootstrap (deflated 39%)
runtime-tutorial$ aws lambda publish-layer-version --layer-name bash-runtime --zip-file
fileb://[Link]

Configure the function to use the new version of the layer.

runtime-tutorial$ aws lambda update-function-configuration --function-name bash-runtime \


--layers arn:aws:lambda:us-west-2:123456789012:layer:bash-runtime:2

Share the layer


Add a permission statement to your runtime layer to share it with other accounts.

runtime-tutorial$ aws lambda add-layer-version-permission --layer-name bash-runtime --


version-number 2 \
--principal "*" --statement-id publish --action lambda:GetLayerVersion
{
"Statement": "{\"Sid\":\"publish\",\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":
\"lambda:GetLayerVersion\",\"Resource\":\"arn:aws:lambda:us-west-2:123456789012:layer:bash-
runtime:2\"}",
"RevisionId": "9d5fe08e-2a1e-4981-b783-37ab551247ff"
}

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.

runtime-tutorial$ aws lambda delete-layer-version --layer-name bash-runtime --version-


number 1
runtime-tutorial$ aws lambda delete-layer-version --layer-name bash-runtime --version-
number 2

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.

Delete the tutorial function with the delete-function command.

143
AWS Lambda Developer Guide
Clean up

runtime-tutorial$ aws lambda delete-function --function-name bash-runtime

144
AWS Lambda Developer Guide

AWS Lambda applications


An AWS Lambda application is a combination of Lambda functions, event sources, and other resources
that work together to perform tasks. You can use AWS CloudFormation and other tools to collect your
application's components into a single package that can be deployed and managed as one resource.
Applications make your Lambda projects portable and enable you to integrate with additional developer
tools, such as AWS CodePipeline, AWS CodeBuild, and the AWS Serverless Application Model command
line interface (SAM CLI).

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

Managing applications in the AWS Lambda console


The AWS Lambda console helps you monitor and manage your Lambda applications (p. 145). The
Applications menu lists AWS CloudFormation stacks with Lambda functions. The menu includes stacks
that you launch in AWS CloudFormation by using the AWS CloudFormation console, the AWS Serverless
Application Repository, the AWS CLI, or the AWS SAM CLI.

To view a Lambda application

1. Open the Lambda console Applications page.


2. Choose an application.

The overview shows the following information about your application.

• 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.

To monitor a Lambda application

1. Open the Lambda console Applications page.


2. Choose Monitoring.

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.

Custom monitoring dashboards


Customize your application monitoring page by adding one or more Amazon CloudWatch dashboards to
your application template with the AWS::CloudWatch::Dashboard resource type. The following example
creates a dashboard with a single widget that graphs the number of invocations of a function named
my-function.

146
AWS Lambda Developer Guide
Custom monitoring dashboards

Example function dashboard template

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.

To view a widget definition

1. Open the Lambda console Applications page.


2. Choose an application that has the standard dashboard.
3. Choose Monitoring.
4. On any widget, choose View in metrics from the drop-down menu.

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

Creating an application with continuous delivery in


the Lambda console
You can use the Lambda console to create an application with an integrated continuous delivery pipeline.
With continuous delivery, every change that you push to your source control repository triggers a
pipeline that builds and deploys your application automatically. The Lambda console provides starter
projects for common application types with [Link] sample code and templates that create supporting
resources.

In this tutorial, you create the following resources.

• 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