paint-brush
Accelerate Troubleshooting in AWS: Lightrun's Seamless Debugging for Lambda Functionsby@talyitzhak
315 reads
315 reads

Accelerate Troubleshooting in AWS: Lightrun's Seamless Debugging for Lambda Functions

by Tal YitzhakAugust 2nd, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Debugging serverless applications, particularly AWS Lambda functions, can be a challenging task due to their stateless and ephemeral nature. Traditional debugging approaches often fall short when trying to inspect code running in a remote, serverless environment. However, with Lightrun's innovative platform, debugging Lambda applications in Python and Node.js has never been easier. In this blog post, we will explore how Lightrun simplifies the debugging process, providing a seamless experience for developers, along with best practices for creating snapshots and logs.
featured image - Accelerate Troubleshooting in AWS: Lightrun's Seamless Debugging for Lambda Functions
Tal Yitzhak HackerNoon profile picture


Debugging serverless applications, particularly AWS Lambda functions, can be a challenging task due to their stateless and ephemeral nature. Traditional debugging approaches often fall short when trying to inspect code running in a remote, serverless environment. However, with Lightrun's innovative platform, debugging Lambda applications in Python and Node.js has never been easier. In this blog post, we will explore how Lightrun simplifies the debugging process, providing a seamless experience for developers, along with best practices for creating snapshots and logs.


About Lightrun

Lightrun is a powerful solution that is designed to streamline the process of debugging and understanding complex live applications. It allows developers to insert real-time log-based breakpoints directly into their running applications, enabling them to instantly inspect and troubleshoot code without the need for redeployment. With Lightrun, developers can accelerate the debugging process, reducing downtime and enhancing the efficiency of their applications running in any environment.


The Power of Lightrun's Platform when Debugging Lambda Functions

Lightrun's platform handles the entire process of spinning up an agent and tearing it down gracefully. By integrating the Lightrun’s agent into your Lambda code, you can enable debugging capabilities without any invasive changes. The solution simplifies the debugging process, allowing developers to focus on identifying and resolving issues without worrying about managing the underlying infrastructure.


Starting to Debug Serverless Architecture with Lightrun is simple and consists of the following steps that happens out-of-the-box and does not require any specific implementation when using our lightrun/lambda library:

  1. Lightrun’s debugging functionality is Enabled.

  2. Agent will show up in the developer's Lightrun’s IDE plugin.

  3. Original function is executed.

  4. Any log or snapshot that was added prior to triggering the lambda will take effect if running as part of the lambda execution.

  5. The lightrun functionality is cleaned up and deactivated (the agent disappears from the Lightrun’s IDE plugin).


Simple Steps to Debug Serverless Architecture with Lightrun: Seamless Troubleshooting Out-of-the-Box 🚀🔍


Code Example

We’ll demonstrate the flow with a real example of a Lambda function that aggregates 30 random wikipedia page titles and returns them to the screen. Once triggered via a Function URL, we expect to see 30 different titles scraped from real wikipedia pages:

Output of a Lambda Function that aggregates random wikipedia page titles


Let’s present the code that was used, breaking it down to index.js, package.json and the Dockerfile that was used to build the image that was deployed to ECR all the way to the Lambda image.

index.js

const lightrun = require("lightrun/lambda");
const axios = require('axios');

async function scrapeWikipediaTitle() {
  try {
    const response = await axios.get('https://en.wikipedia.org/wiki/Special:Random');
    const responseData = response.data;
    const titleStart = responseData.indexOf('<title>');
    if (titleStart === -1) return null;
    
    const titleEnd = responseData.indexOf('</title>', titleStart);
    if (titleEnd === -1) return null;
  
    return responseData.substring(titleStart + 7, titleEnd);
  } catch (error) {
    console.error('Error scraping title:', error.message);
    return null;
  }
}

async function main() {
  const titles = [];

  for (let i = 0; i < 30; i++) {
    const title = await scrapeWikipediaTitle();

    if (!title) {
      console.log('Unable to scrape Wikipedia Title. Exiting...');
      return;
    }
    console.log('Wikipedia Title:');
    console.log(title);
    titles.push(title);
  }

  const result = titles.join('\n');
  return result;
}

exports.handler = lightrun.wrap( async (event, context) => {
        response = main();
        return response;
    }, {
      lightrunSecret: '<LIGHTRUN_KEY>',
      agentLog: {
        logsPath: "",
        level: "debug"
      },
      lightrunWaitForInit: true, 
      lightrunInitWaitTimeMs: 10000,
      metadata: {
        registration: {
            tags: ['aws-lambda-function-nodejs','us-east-1','wikipedia-headline-extraction']
        }
      }
    }
);


Notes:

  • Storing Lightrun’s Secret - you can use the Environment Variables section and encrypt the key in transit and at rest, keeping it secure without exposing it in the code.
  • Ensure that your Lambda function has the necessary permissions to communicate with the Lightrun server. Double-check IAM roles and permissions to avoid any access issues.


package.json

{
  "name": "docker_web_app",
  "version": "1.0.0",
  "description": "Node.js on Docker",
  "author": "Tal Yitzhak",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "express": "^4.18.2",
    "lightrun": "1.13.0",
    "axios": "1.4.0"
  }
}


Dockerfile

FROM public.ecr.aws/lambda/nodejs:12
COPY index.js package.json ./
RUN npm install
CMD [ "index.handler" ]


We Build and deploy the image to ECR using the following process (login and push commands can be taken from ECR console), and afterwards deploy the docker image to your Lambda:

aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin dkr.ecr.us-east-1.amazonaws.com

docker build -t aws-lambda-function-nodejs . --platform=linux/amd64
docker tag aws-lambda-function-nodejs:latest dkr.ecr.us-east-1.amazonaws.com/aws-lambda-function-nodejs:latest
docker push dkr.ecr.us-east-1.amazonaws.com/aws-lambda-function-nodejs:latest

rm -rf node_modules
# Now update the function image in AWS Lambda


Now you can trigger your Lambda, and on any execution you have all Lightrun’s debugging capabilities!


For example, when creating a snapshot for line index.js:31 with a hit limit of 1, and then triggering the Lambda Function we can receive the following hit:


Snapshot hit shown from the Lightrun IDE Plugin for VSCode


For better visibility on only the interesting relevant variables within a snapshot, please refer to our Watch Expressions documentation for more information.


Best Practices


  • Creating Snapshots and Logs based on Lightrun Tags: Lightrun's advanced tagging system empowers developers to create snapshots and logs at critical points in the Lambda function's execution. By strategically placing tags within your lambda agents, describing the region they are deployed, their purpose, owner, environment, etc - you can later on create a snapshot or add a dynamic log which captures the state of variables, monitor execution flow, and gain valuable insights that match ONLY the lambdas that are deployed with an agent with that tag.


    Example: You have 5 lambdas running, in 5 different regions thousands of times per day. Every lambda is wrapped with Lightrun’s agent and is tagged with the relevant region it is deployed in AWS.


    You NEED to research an anomaly on one of the regions, then you would choose, when creating a snapshot/log, the tag with the relevant region; region:us-east1 - which will take effect only for lambdas in that region, making your debugging experience very smooth.


    What if you need to research an anomaly that happens in 2 different regions? Well, you can use Custom Sources and group them to one source and then refer to that source while creating a snapshot/log.


  • Onboard with Long-Lived Lambdas: When debugging lambdas with our service, we recommend customers to start working with long-lived lambdas. The reason is that on long-lived lambdas, our agent has sufficient time to register with the server, ensuring a smoother debugging experience. Long-lived lambdas allow the agent to establish a stable connection, improving the debugging process.


Conclusion

Lightrun's seamless integration with AWS Lambda applications in Python and Node.js brings a new level of simplicity and efficiency to the debugging process. By utilizing Lightrun's wrapper, developers can focus on resolving issues quickly and effectively, without the headache of managing debugging infrastructure. Embrace the power of Lightrun and take your AWS Lambda debugging to new heights!


Watch the demo on our youtube channel: Debugging AWS Lambda Serverless with Lightrun