Optimise AWS Lambda Performance using CloudWatch and Xray

Optimise AWS Lambda Performance using CloudWatch and Xray

My specialities in previous years includes optimisation of page load during the launch of websites-this is reduce energy consumption and improve user experience. XRay from AWS has got tremendous features to help us when used at right time to spot the delays in page load.

Let us see some interesting use cases by creating a simple website using Lambda.

Lambda Blueprint based Website

Navigate to AWS Lambda to create a function:

Choose the option of 'Use a blueprint':

Make sure to create a role with basic Lambda functions to execute this code:

Use a simple handler to launch the page with status code as 200:


Code:

import * as fs from 'node:fs';

const html = fs.readFileSync('index.html', { encoding: 'utf8' });

/**
 * Returns an HTML page containing an interactive Web-based tutorial.
 * Visit the function URL to see it and learn how to build with lambda.
 */
export const handler = async (event) => {
    console.log('Received event:', JSON.stringify(event, null, 2));
    
    const response = {
        statusCode: 200,
        headers: {
            'Content-Type': 'text/html',
        },
        body: html,
    };
    return response;
};        


Now deploy the code using Deploy button. Once deployed, navigate to configuration section to navigate to monitoring and operational tools to enable Xray:

Click enable button for Xray at Lambda:

Now launch the website by copying the function URL from function overview. Once page is loaded, navigate to cloud watch to see logs (via monitoring of Lambda):

Similarly click on Monitoring->Open XRay logs to navigate to see each components load time and delays within XRay Logs:

This trace will further help on identifying root cause for some of the failures and delays during the page load time-this is similar to lighthouse extension of Google Chrome:

Overview

AWS X-Ray is a service that helps developers analyze and debug distributed applications, particularly those built using microservices. When it comes to website page load performance, AWS X-Ray can be extremely useful for identifying and resolving bottlenecks or performance issues. Here's how it can be applied to optimize page load:

1. Trace Requests Across Services

  • Distributed Tracing: In modern web applications, especially those using microservices or serverless architecture, a single page load might involve multiple backend services. X-Ray traces requests across these services, capturing data such as API calls, database queries, and other dependencies.
  • End-to-End View: You can track the entire request lifecycle from the user's browser through the backend services (e.g., load balancers, web servers, databases) to understand where delays or errors occur during the page load.

2. Identify Performance Bottlenecks

  • Latency Analysis: X-Ray helps pinpoint where latency is introduced in the application stack. This could be slow database queries, inefficient API calls, network delays, or other issues that impact page load times.
  • Service Dependencies: It visualizes how different services interact, so you can see if a particular service is slowing down the entire system. For instance, a delay in an external API call can cascade and affect the page load speed.

3. Monitor and Debug Errors

  • Error Tracing: X-Ray automatically captures error rates and traces them to specific components, so you can identify and debug issues such as timeouts, HTTP errors, or failed requests during page load.
  • Exception Logging: If an exception occurs during a page load (e.g., a JavaScript error, a backend error, or a database failure), X-Ray can help you trace it to the source, enabling you to fix issues faster.

4. Visualize the Request Flow

  • Service Map: AWS X-Ray provides a graphical representation of your application architecture. This "service map" visualizes how different components of the app (e.g., front-end, APIs, databases) interact with each other. By analyzing the service map, you can see which service is causing delays and impacting page load performance.
  • Root Cause Analysis: If the page load time is slower than expected, X-Ray can help you drill down into specific requests and identify the root cause of the delay.

5. Track External Service Calls

  • Third-party Dependencies: For websites that rely on third-party services (e.g., payment gateways, analytics services, CDN), X-Ray tracks these calls and measures their impact on page load. If an external service is slow or unreliable, it can affect the overall page performance.

6. Improve User Experience

  • Performance Optimization: By identifying where delays are occurring, developers can optimize the application for faster page loads, which ultimately leads to a better user experience (UX). For example, optimizing database queries, reducing API call latency, or caching responses can significantly improve performance.
  • Real-Time Monitoring: AWS X-Ray allows you to monitor performance over time, so you can identify trends and proactively address issues before they affect end users.

7. Integrating with AWS Services

  • AWS Lambda & API Gateway: X-Ray works seamlessly with AWS Lambda and API Gateway, which are often used for dynamic backend operations in serverless web applications. It helps trace API requests and functions to ensure there are no delays in the execution.
  • CloudFront: For websites using AWS CloudFront (a CDN), X-Ray can also help trace requests from CloudFront to the origin servers, identifying any performance issues in the delivery process.

8. Root Cause of Slow Loading Web Pages

  • By using X-Ray, you can track the exact steps involved in loading a webpage. For instance, if the issue is slow loading due to: A long-running database query. A slow backend service. A high latency in external API requests.
  • X-Ray will break down and show you which part of the infrastructure or code is causing the slowdown.

Example Use Case:

Imagine a scenario where a webpage takes too long to load, and you need to debug it. With AWS X-Ray enabled, you can:

  • See the API request taking longer than expected.
  • Identify whether the delay is due to a database query, an external API call, or the rendering process itself.
  • Find if a particular microservice is the bottleneck or if there's an issue in the network.
  • Improve the response time by addressing the specific performance issue.

Conclusion:

In short, AWS X-Ray helps you track and optimize the performance of a web application by providing deep insights into the time it takes for each component of the app to process requests during a page load. It gives you the ability to diagnose and fix performance bottlenecks, reduce latency, improve reliability, and ensure a smooth user experience on your website.

??Please feel free to share your views in the comments section on some AWS XRay usecases.


?Follow me on LinkedIn: Link

Like this article? Subscribe to Engineering Leadership , Digital Accessibility, Digital Payments Hub and Motivation newsletters to enjoy reading useful articles. Press SHARE and REPOST button to help sharing the content with your network.

#LinkedInNewsUK #FinanceLeadership

要查看或添加评论,请登录

NARAYANAN PALANI ???????的更多文章

社区洞察