Menu
AWS X-Ray
Developer Guide

Instrumenting an AWS Lambda Function

Scorekeep calls an AWS Lambda function to get random names for new users. When a user creates a session without entering a name, the application calls a function named random-name with the AWS SDK for Java. The X-Ray SDK for Java records information about the call to Lambda in a subsegment like any other call made with an instrumented AWS SDK client.

When Lambda processes the call to random-name, it reads the tracing header, which contains the trace ID and sampling decision written by the X-Ray SDK for Java.

For each sampled request, Lambda runs the X-Ray daemon and writes two segments. The first segment records information about the call to Lambda that invokes the function. This segment contains the same information as the subsegment recorded by Scorekeep, but from the Lambda point of view. The second segment represents the work that the function does. This segment is provided to the X-Ray SDK for extension with annotations and subsegments for downstream calls.

Service graph representing how Scorekeep calls a Lambda function to get random names for new users

The random-name function is implemented in Node.js. It uses the SDK for JavaScript in Node.js to send notifications with Amazon SNS, and the X-Ray SDK for Node.js to instrument the AWS SDK client.

Example _lambda/random-name/index.js -- Random Name Lambda Function

var AWSXRay = require('aws-xray-sdk-core');
var AWS = AWSXRay.captureAWS(require('aws-sdk'));

AWS.config.update({region: process.env.AWS_REGION});
var Chance = require('chance');

var myFunction = function(event, context, callback) {
  var sns = new AWS.SNS();
  var chance = new Chance();
  var segment = AWSXRay.getSegment();
  var userid = event.userid;
  segment.addAnnotation('User ID', userid);

  var name = chance.first();
  segment.addAnnotation('Name', name);

  // Notify
  var params = {
    Message: 'Created randon name "' + name + '"" for user "' + userid + '".',
    Subject: 'New user: ' + name,
    TopicArn: process.env.TOPIC_ARN
  };
  sns.publish(params, function(err, data) {
    if (err) {
      console.log(err, err.stack);
      callback(err);
    }
    else {
      console.log(data);
      callback(null, {"name": name});
    }
  });
};

exports.handler = myFunction;

The xray branch includes a script to create a blank Lambda function. Configuration files in the .ebextensions folder build the function package with npm install during deployment, and then update the Lambda function with the AWS CLI.

See the readme for more information and instructions: AWS Lambda Integration.