/bespoke-edge-metrics

Using EMF to create metrics on the edge with CloudFront Functions

Primary LanguageJavaScript

Bespoke CloudFront Edge Metrics

This is the companion repo for the blog post: Bespoke CloudFront Edge Metrics The stack will create a CloudFront distribution that uses a CloudFront function to emit latency metrics and queryable logs for a Lambda function as measured by the CloudFront edge.

Interesting files

  1. lib/bespoke-edge-metrics-stack.mjs - The CDK stack that creates the CloudFront distribution, CloudFront functions, Lambda Function/Function Url.
  2. cloudfront-functions/metricsAspect.js The CloudFront function that injects the x-request-time header and processes all of the x-meta-* response headers from the lambda function to emit a latency metric in the EMF format to the log.
  3. src/handler.js - The Lambda function that sets response headers so they are accessible in the CloudFront Function.

Setup

npm install

If you've never used the CDK before, run:

npx cdk bootstrap

Deploy

npx cdk deploy

Usage

Outputs will print the url for the CloudFront distribution.

BespokeEdgeMetricsStack.CloudFrontUrl = https://d1xxxxxxxxxxxx.cloudfront.net/api/hello

Hit the url a few times, then if you are logged into the AWS console, use these links to see your metrics and logs. There may be an initial delay of 2-3 minutes before your metrics and logs are available.

You can see the metrics in CloudWatch Metrics here

You can see the logs in CloudWatch Logs here

Tearing down

npx cdk destroy

Useful commands

  • npm run build compile typescript to js
  • npm run watch watch for changes and compile
  • npx cdk deploy deploy this stack to your default AWS account/region
  • npx cdk diff compare deployed stack with current state
  • npx cdk synth emits the synthesized CloudFormation template