Intro to OpenTelemetry for Node.js Apps with New Relic and freeCodeCamp.org

9 min read

When I first joined New Relic, I really didn't understand the importance of observability, because I came from a frontend background. As I began learning about why observability was valuable for developers, I started digging deeper into the open source ecosystem and learning what makes it possible for modern apps to maintain uptime. I learned more about OpenTelemetry, a popular open source tool for monitoring your apps and websites, but it was intimidating because I couldn't find any introductory tutorials online guiding me through the process of instrumentation.

It wasn't until I began instrumenting my own apps using the OpenTelemetry documentation that I realized how easy it was to get started. I collaborated with freeCodeCamp.org to create a beginner-friendly resource for anyone to begin instrumenting apps with OpenTelemetry. I worked with an amazing technical content creator named Ania Kubów to bring this one-hour video course to life. This course teaches how to use OpenTelemetry, including microservices, observability, tracing, and more.

Instrumenting your Node.js apps with OpenTelemetry

As systems become more complex, it’s increasingly important to get visibility into the inner workings of systems to increase performance and reliability. Distributed tracing shows how each request passes through the application, giving developers context to resolve incidents and showing what parts of their systems are slow or broken.

A single trace shows the path a request makes, from the browser or mobile device down to the database. By looking at traces as a whole, developers can quickly discover which parts of their applications are having the biggest impact on performance and how their users are affected.

That’s pretty abstract, right? So let’s zero in on a specific example to help clarify things. We’ll use OpenTelemetry to generate and view traces from a small sample application. You can watch the following video and also walk through the steps I describe in the the rest of this post.

Spinning up a movies app

We wrote a simple application consisting of two microservices: movies and dashboard. The movies service provides the names of movies and their genre in JSON format, and the dashboard service returns the results from the movies service.

👉 Clone the repo

To spin up the app, run the following command:

$ npm i
$ node dashboard.js
$ node movies.js

Notice the delay variable in the movies microservice. It causes random delays returning the JSON:

const express = require('express')
const app = express()
const port = 3000

app.get('/movies', async function (req, res) {
  res.type('json')
  const delay = Math.floor( ( Math.random() * 2000 ) + 100);
  setTimeout((() => {
      res.send(({movies: [
         { name: 'Jaws', genre: 'Thriller'},
         { name: 'Annie', genre: 'Family'},
         { name: 'Jurassic Park', genre: 'Action'},
      ]}))
  }), delay)
})

Tracing HTTP requests with OpenTelemetry

OpenTelemetry traces incoming and outgoing HTTP requests by attaching IDs. To do this, you need to complete the following steps:

  • Instantiate a trace provider to get data flowing.
  • Configure that trace provider with an exporter to send telemetry data to another system where you can view, store, and analyze it.
  • Install OpenTelemetry plugins to instrument specific node modules to automatically instrument various frameworks.

You need to have Docker on your machine to run a Zipkin instance. If you don't have Docker yet, it's easy to install. As for Zipkin, it's an open-source distributed tracing system created by Twitter that helps gather timing data needed to troubleshoot latency problems in service architectures. The OpenZipkin volunteer organization currently runs it. Finally, if you want to export your OpenTelemetry data to New Relic in Step 4,  sign up to analyze, store, and use your telemetry data for free, forever.

Step 1: Create a trace provider and configure it with an exporter

To create a trace provider, you need to install the following tool:

$ npm install @opentelemetry/node

OpenTelemetry auto instrumentation package for Node.js

The @opentelemetry/node module provides auto-instrumentation for Node.js applications, which automatically identifies frameworks (such as Express), common protocols (HTTP), databases, and other libraries within your application. This module uses other community-contributed plugins to instrument your application to automatically produce spans and provide end-to-end tracing with just a few lines of code. A span represents a unit of work in a distributed system.

OpenTelemetry plugins

Install the plugins:

$ npm install @opentelemetry/plugin-http
$ npm install @opentelemetry/plugin-express

When the Node.js HTTP module handles any API requests, the @opentelemetry/plugin-http plugin generates trace data. The @opentelemetry/plugin-express plugin generates trace data from requests sent through the Express framework.

Step 2: Add the trace provider and the span processor

After tracers are implemented into applications, they record timing and metadata about operations that take place (for example, when a web server records exactly when it receives a request, and when it sends a response).

Add the following code snippet, which performs two actions:

  • Creates a trace provider.
  • Adds a span processor to the trace provider.

This code gets data from your local application and prints it to the terminal:

const { NodeTracerProvider } = require('@opentelemetry/node');
const { ConsoleSpanExporter, SimpleSpanProcessor } = require('@opentelemetry/tracing');

const provider = new NodeTracerProvider();
const consoleExporter = new ConsoleSpanExporter();
const spanProcessor = new SimpleSpanProcessor(consoleExporter);
provider.addSpanProcessor(spanProcessor);
provider.register()

If you want to learn more about this code, check out the OpenTelemetry docs on tracers.

After you add this code snippet, whenever you reload http://localhost:3001/dashboard, you should get something like this (beautiful things in your terminal):

Dashboard Example OpenTelemetry

Step 3: Use Docker to install Zipkin and start tracing your application

You instrumented OpenTelemetry in the previous step. Now you move the data that you collected to a running Zipkin instance.

Spin up Zipkin

Spin up a Zipkin instance with the Docker Hub Image:

$ docker run -d -p 9411:9411 openzipkin/zipkin

You now have a Zipkin instance up and running. You can load it by opening http://localhost:9411 on your web browser  You see something like this:

Zipkin example OpenTelemetry

Export to Zipkin

Although neat, spans in a terminal window are a poor way to gain visibility into a service. You’re not going to want to scroll through JSON data in your terminal. Instead, it’s a lot easier to see a visualization in a dashboard. Let's work on that now. In the previous step, we added a console exporter to the system. Now you ship this data to Zipkin.

In the following code snippet, you instantiate a Zipkin exporter, and then add it to the trace provider:

const { NodeTracerProvider } = require('@opentelemetry/node')
const { ConsoleSpanExporter, SimpleSpanProcessor } = require('@opentelemetry/tracing')
const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin')
const provider = new NodeTracerProvider()
const consoleExporter = new ConsoleSpanExporter()
const spanProcessor = new SimpleSpanProcessor(consoleExporter)
provider.addSpanProcessor(spanProcessor)
provider.register()

const zipkinExporter = new ZipkinExporter({
  url: 'http://localhost:9411/api/v2/spans',
  serviceName: 'movies-service'
})

const zipkinProcessor = new SimpleSpanProcessor(zipkinExporter)
provider.addSpanProcessor(zipkinProcessor)

After you make the changes, open your Zipkin instance at localhost:9411, start your application back up, and request some URLs. Tracing data is usually represented by a bar, just like the following example, and is referred to as span.

Zipkin example instance OpenTelemetry tutorial

Step 4: Use the OpenTelemetry Collector to export the data into New Relic

What happens if you want to send the OpenTelemetry data to another service that manages and analyzes your data for you?

The talented contributors to OpenTelemetry came up with a solution to address this challenge:

OpenTelemetry Example Diagram

The OpenTelemetry Collector is a way for developers to receive, process, and export telemetry data to multiple backends. This collector acts as the intermediary, getting data from the instrumentation and sending it to multiple backends to store, process, and analyze the data.

It supports multiple open source observability data formats like Zipkin, Jaeger, Prometheus, and Fluent Bit, sending it to one or more open source or commercial backends.

Configuring the OpenTelemetry Collector with New Relic

New Relic is a platform for you to analyze, store, and use your telemetry data for free, forever. Sign up to use it with the remaining steps in this tutorial.

Clone the OpenTelemetry Collector with New Relic Exporter and spin up the Docker container, making sure to export the New Relic API key. To get a key, go to the New Relic one dashboard and choose API keys from the dropdown menu in the upper right.

Select API keys from the dropdown in the upper right corner.

Then, from the API keys window, click the Create a key button.

Click on the blue Create a Key button in the upper right.

When creating the key, make sure you choose the Ingest - License key type. Then click Create a key to generate the key.

 

Choose Ingest-License for Key type and click Create a key.

After you have an API key, you need to replace <INSERT-API-KEY-HERE> in the code snippet below with your API key.

export NEW_RELIC_API_KEY=<INSERT-API-KEY-HERE>
docker-compose -f docker-compose.yaml up

Make sure to change the reporting URL from http://localhost:9411/api/v2/spans to http://localhost:9411/ in both dashboard.js and movies.js:

const zipkinExporter = new ZipkinExporter({
  url: 'http://localhost:9411',
  serviceName: 'movies-service'
})

Step 5: Look at your beautiful data

In New Relic One, click the Explorer tab:

Explorer tab in New Relic One

When you click on the service, you should be able to see some traces!

The trace in the dashboard is transmitting data about the random delay that was added to the API calls:

Traces Example OpenTelemetry

Final thoughts

Instrumenting your app with OpenTelemetry makes it easy to figure out what is going wrong when parts of your application are slow, broken, or both. With the collector, you can forward your data anywhere. You can choose to spin up an open source backend, use a proprietary backend like New Relic, or just roll your own backend! Whatever you choose, I wish you well you in your journey to instrument everything.