The Relicans

Daniel Kim 🪐
Daniel Kim 🪐

Posted on • Originally published at dev.to

Instrumenting Your Node.js Apps with OpenTelemetry

As systems become increasingly 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, showing what parts of their system 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 application is having the biggest impact on performance as it affects your users’ experiences.

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.

Spinning up our Movies App

We have written a simple application consisting of two microservices, movies and dashboard. The movies service provides the name of movies and their genre in JSON format, while the dashboard service returns the results from the movies service.

👉 Clone the repo

To spin up the app, run

$ npm i
$ node dashboard.js
$ node movies.js
Enter fullscreen mode Exit fullscreen mode

Notice the variable delay, built into the movies microservice that 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')
+  var 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)
})
Enter fullscreen mode Exit fullscreen mode

Tracing HTTP Requests with Open Telemetry

OpenTelemetry traces incoming and outgoing HTTP requests by attaching IDs. To do this, we need to

  • 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 module(s) to automatically instrument various frameworks

Step 1: Create our trace provider and configuring it with an exporter

We’ll start by creating our trace provider and configuring it with an exporter. To do this, we’ll need to install

$ npm install @opentelemetry/node
Enter fullscreen mode Exit fullscreen mode

OpenTelemetry auto instrumentation package for NodeJS

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

OpenTelemetry Plugins

$ npm install @opentelemetry/plugin-http
$ npm install @opentelemetry/plugin-express
Enter fullscreen mode Exit fullscreen mode

The @opentelemetry/plugin-http plugin generates trace data from NodeJS’s underlying HTTP handling APIs that both send, and handle requests. The @opentelemetry/plugin-express plugin generates trace data from requests sent through the express framework.

Step 2: Adding the Trace Provider and the Span Processor

Add this code snippet to

  • create a trace provider
  • adds a span processor to the trace provider

This code gets data out of your local application and exports into your console!

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()
Enter fullscreen mode Exit fullscreen mode

Once we add this code snippet, whenever we reload http://localhost:3001/dashboard, we should get something like this - beautiful things on the console.

giphy

Step 3a: Spinning up Zipkin

Let's spin up a Zipkin instance with the Docker Hub Image

$ docker run -d -p 9411:9411 openzipkin/zipkin
Enter fullscreen mode Exit fullscreen mode

and you’ll have a Zipkin instance up and running. You’ll be able to load it by pointing your web browser to http://localhost:9411. You’ll see something like this

Screenshot of Zipkin

Step 3: Exporting to Zipkin

While it’s neat, spans in a terminal window are a poor way to have visibility into a service. In our code above, the following lines are what added a console exporter to our system. Let's now ship this data to Zipkin.

In this code snippet, we are instantiating a Zipkin exporter, and then adding it to the trace provider. The great thing about OpenTelemetry is that it's backend agnostic, meaning you can have as many different exporters configured as you like,

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)
Enter fullscreen mode Exit fullscreen mode

After you make these changes, let's visit our Zipkin instance at localhost:9411, start our application back up and request some URLs.

Screen Shot 2021-06-23 at 3.54.32 PM

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

What happens if we want to send the OpenTelemetry data to another backend where you didn't have to manage all of your own telemetry data?

Well, the amazing contributors to OpenTelemetry have come up with a solution to fix this!

Group 1792

The OpenTelemetry Collector is a way for developers to receive, process and export telemetry data to multiple backends. It supports multiple open-source observability data formats like Zipkin, Jaeger, Prometheus, Fluent Bit sending it to one or more open-source or commercial back-ends.

New Relic

New Relic is a platform for you to analyze, store, and use your telemetry data for Free, forever. Sign up now!

image

Configuring the OpenTelemetry Collector with New Relic

Clone the OpenTelemetry Collector with New Relic Exporter and spin up the docker container, making sure to export the New Relic API key.

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

💡 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/api/v2/spans',
+ url: 'http://localhost:9411',
  serviceName: 'movies-service'
})
Enter fullscreen mode Exit fullscreen mode

Step 5: Look at your ✨ beautiful data ✨

Navigate to the "Explorer" tab on New Relic One.

New Relic One Dashboard

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

OTel Traces

Final Thoughts

Instrumenting your app with Open Telemetry makes it easy to figure out what is going wrong when parts of your application is slow, broken, or both. With the collector, you can forward your data anywhere, so you are never locked into a vendor. 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 journey to instrument EVERYTHING!

Discussion (0)