Tracing with X-ray
In this section we will enable X-ray for the Lambda function to track incoming and outgoing requests to the function, knowing how much time each segment of the function takes. Then we will know where the function is slow and from there easily optimize it.
- Open console of AWS Lambda
- Click the function book_delete
- Click the Configure tab
- Click Monitoring and operations tools in the menu on the left
- Press Edit
- Click Active tracing in the AWS X-Ray section
- Press Save
- Call DELETE API with Postman
- Open the CloudWatch dashboard
- Expanded X-Ray traces
- Press Traces
- Scroll to the bottom and click on the currently displayed trace
- Initialization subsegment: represents the init phase of the Lambda execution environment lifecycle. During this phase, Lambda creates or opens an execution environment with configured resources, downloads the function code and all classes, runs the runtime, and initializes the function.
- Invocation subsegment: represents the stage when Lambda calls the function handler. This starts with the runtime and registers the extension and it ends when the runtime is ready to send a response.
- Overhead subsegment: represents the period that occurs between the time that the runtime sends the response and signal for the next call. During this time, the runtime finishes all tasks associated with an invocation and prepares to freeze the sandbox.
- To patch all the libraries used in the function we add the following code at the beginning of your machine
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
patch_all()
- Run the following commands in the book_delete directory
pip install --target ./package aws_xray_sdk
cd package
zip -r ../deployment-package.zip .
cd ..
zip -g deployment-package.zip book_delete.py
- Return to the function panel book_delete
- Press tab Code
- Click Upload from, select .zip file
- Press Upload, then select the deployment-package.zip file you just created
- Press Save
- Call DELETE API with Postman
- Navigate to the CloudWatch dashboard
- Click on the latest trace
- You will see more specific information than in the previous trace