Search code examples
aws-lambdaaws-api-gatewayserverless-frameworkserverlessaws-xray

Conditionally enable x-ray for API Gateway and Lambda in serverless framework


I am trying to enable x-ray only when I needed to save some bucks. The following serverless.yml loads the environment variables from the .env file. However, it seems like serverless only allows true, Active and PassThrough. Any possible way to bypass this? Thanks.

# serverless.yml

provider:
  name: aws
  runtime: nodejs10.x
  logs:
    restApi: ${env:ENABLE_X_RAY, false}
  tracing:
    apiGateway: ${env:ENABLE_X_RAY, false}
    lambda: ${env:ENABLE_X_RAY, false}

plugins:
  - serverless-dotenv-plugin
# .env

ENABLE_X_RAY=true

Solution

  • If the entry point of your service is API Gateway you can configure Sampling Rules and limits on the AWS X-Ray console or using API to control the number of requests that are sampled by X-Ray.

    See this article for an introduction to sampling in X-Ray:

    https://aws.amazon.com/blogs/aws/apigateway-xray/

    Let me know if you have further questions regarding this.

    Update

    Sampling rules may be specified only in X-Ray. https://docs.aws.amazon.com/xray/latest/devguide/xray-console-sampling.html This allows you to limit the number of traces no matter how many API Gateway or EC2 instances you have for handling your requests.

    Small caveat: As of today, this mode of sampling is supported only if the entry point is API Gateway or if you have the >2.0 version of X-Ray daemon running on your instances (EC2 or otherwise). If the entry point is lambda this sampling effect is not supported today but will be supported soon.

    In your case it seems you are using API Gateway as your entry point, so you can definitely configure sampling rules in X-Ray console and have that take effect globally across all your API Gateway endpoints.

    You can also configure different sampling rules for different URLs like /auth is sampled at 5 TPS and /products is configured for 1 TPS with different reservoirs based on your usecase.