Debug School

rakesh kumar
rakesh kumar

Posted on

Explain AWS lambda lifecycle

Steps for Building a Lambda function

command to perform lambda lifecycle

The lifecycle of Lambda function includes four necessary steps −

  1. Authoring
  2. Deploying
  3. Monitoring
  4. Troubleshooting

Authoring Lambda Code
AWS Lambda function code can be written in following languages −

NodeJS
Java,
Python
C#
Go.
Enter fullscreen mode Exit fullscreen mode

We can write code for AWS Lambda using the AWS console, AWS CLI, from Eclipse IDE, from Visual Studio IDE, serverless framework etc.

The following table shows a list of languages and the different tools and IDE that can be used to write the Lambda function −

Image description

Deploying Lambda Code
Once you decide the language you want to write the Lambda function, there are two ways to deploy the code −

  1. Directly write the code in AWS console
  2. Zip or jar the files with all the files and dependencies However, remember that proper permission has to given to be given to the zip file .

Testing Lambda Code
Lambda Code can be tested for events inside the AWS Lambda console. It is also possible to test the Lambda function from the AWS cli and serverless cli. AWS console has also event data which can be used as sample events while testing AWS Lambda function.

Monitoring Lambda function
Monitoring of Lambda function can be done using the AWS CloudWatch. We can add necessary log messages in languages we choose and see the same in AWS CloudWatch.

To start writing Lambda function, there is pattern to be followed. The following are the main core concepts to be followed for writing a Lambda function −

Handler
Handler is a name of the AWS lambda function from where the execution starts. It appears in AWS console as shown below −

Image description

Handler
Notice that here we have changed the default handler to another name and updated the same in the Handler −

Image description

Default Handler
Note that the way a handler is called differs from the languages selected as runtime.

Params passed to handler
If you observe the handler function, the params passed are event, context and call back function as shown below −

Image description

Params Passed
Event parameter has all the details for the trigger used.

Context parameter basically takes care of runtime details for the Lambda function to execute. We can interact with the Lambda function using the context param. It has the details like the time left before AWS Lambda terminates a function i.e, timeout specified while creating Lambda function, name of the Lambda function, cloudwatch group name, arn details etc.

Example
Let us understand the details obtained from AWS Lambda context object with the help of an example −

exports.lambdahandler = (event, context, callback) => {
   // TODO implement
   console.log("context object details");
   console.log(JSON.stringify(context));
   callback(null, 'Lambda test');
};
Enter fullscreen mode Exit fullscreen mode

When you execute the Lambda function shown above, you can see the following output −

Output

Image description

Logging
The logs added inside the Lambda function are displayed in AWS CloudWatch when the AWS function executes. The logs syntax will vary from the language selected. For Example in nodejs, it is console.log.

This is the output you can see in AWSCloudWatch −

AWSCloudWatch
Error Handling
AWS Lambda function provides a callback function which is used to notify to the Lambda function that an error or success has happened. Note that here we have used nodejs as the runtime. The error handling will differ as per the language selected.

Observe the Example given here for a better understanding −

exports.lambdahandler = (event, context, callback) => {
   // TODO implement
   var error = new Error("There is error in code");
   callback(error);
};
Enter fullscreen mode Exit fullscreen mode

Output
When you test the Lambda code, you can find the output as shown below −

Execution Result Failed
The log details as follows −

Log Output

Image description

command to perform lambda lifecycle

The lifecycle of an AWS Lambda function involves several stages, from creation to invocation and eventual deletion. Here's an overview of the typical lifecycle of a Lambda function:

  1. Creation:
    Definition:

  2. A Lambda function is created in the AWS Management Console, AWS CLI, or an AWS SDK.

  3. During creation, you specify the runtime, handler function, and other configuration settings
    .
    Example:

Creating a Lambda function using the AWS Management Console:

aws lambda create-function --function-name MyLambdaFunction \
--runtime python3.8 --role arn:aws:iam::123456789012:role/execution_role \
--handler my_function.handler --zip-file fileb://my_function.zip
Enter fullscreen mode Exit fullscreen mode
  1. Configuration: Definition:

After creation, you can configure additional settings such as environment variables, timeouts, memory allocation, and triggers.
Example:

Setting environment variables for a Lambda function:

aws lambda update-function-configuration --function-name MyLambdaFunction \
--environment Variables={Key1=Value1,Key2=Value2}
Enter fullscreen mode Exit fullscreen mode
  1. Invocation:
    Definition:

  2. Lambda functions can be invoked in response to events or manually triggered.

  3. Events can include API Gateway requests, S3 bucket changes, CloudWatch Events, etc
    .
    Example:

Manually invoking a Lambda function using the AWS CLI:

aws lambda invoke --function-name MyLambdaFunction \
--payload '{"key1":"value1", "key2":"value2"}' output.txt
Enter fullscreen mode Exit fullscreen mode
  1. Execution: Definition:

Lambda executes the function code in a runtime environment.
Resources (CPU, memory) are allocated based on the configured settings.
Example:

A Python Lambda function handling an S3 event:

import json

def lambda_handler(event, context):
    for record in event['Records']:
        # Process S3 event record
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']
        print(f"Processing {key} from {bucket}")
Enter fullscreen mode Exit fullscreen mode
  1. Logging and Monitoring:
    Definition:

  2. Lambda functions generate logs that can be viewed in Amazon CloudWatch Logs.

  3. Monitoring metrics such as invocation count, duration, and errors are available in CloudWatch Metrics
    .
    Example:

Viewing logs in CloudWatch Logs:


aws logs get-log-events --log-group-name /aws/lambda/MyLambdaFunction --log-stream-name <LogStreamName>
Enter fullscreen mode Exit fullscreen mode
  1. Scaling:
    Definition:

  2. Lambda functions can automatically scale based on the incoming traffic.

  3. Multiple instances (containers) of the function may run concurrently to handle concurrent invocations
    .
    Example:
    Automatic scaling based on the number of incoming API Gateway requests.

  4. Error Handling:
    Definition:

  5. Lambda functions can handle errors and exceptions using try-catch blocks in the code.

  6. Failed invocations are logged in CloudWatch Logs and Metrics
    .
    Example:

Adding error handling in a Lambda function:

def lambda_handler(event, context):
    try:
        # Function logic
    except Exception as e:
        print(f"Error: {e}")
        raise
Enter fullscreen mode Exit fullscreen mode
  1. Updating:
    Definition:

  2. Lambda functions can be updated by uploading new code or modifying configuration settings.

  3. Updates can be done through the AWS Management Console, AWS CLI, or SDKs
    .
    Example:

Updating Lambda function code using the AWS CLI:

aws lambda update-function-code --function-name MyLambdaFunction --zip-file fileb://new_function.zip
Enter fullscreen mode Exit fullscreen mode
  1. Deletion: Definition:

Lambda functions can be deleted when they are no longer needed.
Deleted functions release associated resources.
Example:

Deleting a Lambda function using the AWS Management Console or AWS CLI:

aws lambda delete-function --function-name MyLambdaFunction
This lifecycle provides an overview of the major stages in the lifecycle of an AWS Lambda function. It's important to note that Lambda is a serverless compute service, and users are billed based on the number of invocations and the time their code executes. Understanding the lifecycle helps in effective management, optimization, and monitoring of Lambda functions.

Top comments (0)