Alerty Blog

A Complete Guide To Opentelemetry Browser Instrumentation

Written by Jack Dwyer | Sep 8, 2024 9:04:52 AM

Web applications are complex. As a result, performance issues can stem from many different sources. A slow website could be caused by inefficient code running in the backend, poorly optimized database queries, or rendering issues with a web application’s frontend JavaScript. Without the right front end monitoring tools, it can be extremely challenging to pinpoint the exact cause of a web application’s performance issues, especially when they manifest for users in real-time. OpenTelemetry, a framework for collecting and transporting telemetry data, can help you understand how your web applications perform and why. The OpenTelemetry Browser, in particular, focuses on collecting telemetry data from the frontend of web applications, allowing you to monitor performance issues and understand what is happening inside your users’ browsers. 

This blog will discuss how OpenTelemetry works, why you should care, and how to start with the OpenTelemetry Browser. Before we get started, let’s talk about the benefits of frontend monitoring solutions.

Table of Contents

What Is Opentelemetry?

OpenTelemetry, also referred to as OTel, is an open-source observability framework that boasts a collection of:

  • Software development kits (SDKs)
  • Vendor-neutral or vendor-agnostic APIs
  • Instrumentation tools

This technology generates, collects, exports, and instruments telemetry data to analyze your platform's:

  • Behavior 
  • Performance

Telemetry Standardization

OpenTelemetry aims to help organizations reach their business goals by providing a standardized process for collecting telemetry data, which allows for a better understanding of system behaviors.

Why is OpenTelemetry so Important?

IT groups and DevOps professionals must use instrumentation to create an observable system in cloud-native applications. Instrumentation code used to be varied, making it difficult for companies to change backends.

OpenTelemetry Origins

Switching tools took a lot of work because they would need to reinstrument their code and reconfigure new agents to send telemetry data to their new devices. After seeing the need for a standardized system, the Cloud Native Computing Foundation (CNCF) sponsored the OpenTelemetry project to create a standardized way to:

  • Send
  • Collect
  • Transfer telemetry data to backend observability platforms

OpenTelemetry was born from combining the distributed tracing technology of:

  • OpenCensus 
  • OpenTracing into one tool

Related Reading

Key Benefits Of Opentelemetry

Consistency: A Solid Foundation for OpenTelemetry

OpenTelemetry offers a consistent framework for collecting telemetry data across multiple applications. This consistency creates a solid foundation for the following:

  • Observability 
  • Monitoring

Unified Observability

Before the advent of OpenTelemetry, DevOps teams struggled with compatibility issues when using different tools and standards. OpenTelemetry gives you a unified approach for:

  • Collecting
  • Processing
  • Exporting telemetry data regardless of your tech stack

As a result, you can:

  • Save valuable time
  • Improve your observability
  • Make a smoother transition to container deployment

Simplified Observability with OpenTelemetry

OpenTelemetry simplifies observability. It collects telemetry data without changing your code or metadata. With OpenTelemetry, developers don’t have to stick to specific backends or vendors. You can use OpenTelemetry with any observability tool, whether a commercial product or an open-source solution.

Flexibility: OpenTelemetry Adapts to Your Operations

OpenTelemetry is flexible. You can monitor performance metrics and usage from any web browser or device. The convenience of observing your application from any location makes it easier to track your analytics in real-time.

3 Types Of Telemetry Data Used by Opentelemetry

To better understand OpenTelemetry, let’s examine telemetry data and how your organization can use it. 

A key part of successful application performance is being observable through access to data. IT professionals use telemetry data to determine an application's health and performance.

Telemetry Data

OpenTelemetry creates a standard for collecting and transferring telemetry data in cloud-native applications. Your organization can then analyze and monitor these metrics to improve your platforms. 

Telemetry data comprises outputs collected from logs, metrics, and traces, often referred to as the three pillars of observability.

1. Logs

Logs are a timestamp or record of events in your application. The critical events identified using logs show errors or unpredictable behaviors within your system.

This information signals to your internal teams that a problem has occurred so you can fix it before more users experience the error. 

2. Metrics

Metrics are typically where you’ll see the first sign of an issue in your system. These give you numerical values or measurements showing your resource utilization and application performance. The three main types of metrics are:

  • Delta
  • Gauge 
  • Cumulative

3. Traces

Traces evaluate how requests move through a server in distributed cloud environments by monitoring how an operation transfers from node to node. Because they solely focus on application layers, traces can only provide limited visibility into application health.

Monitoring Metrics

Monitoring your metrics and logs is essential to get a complete picture of what is happening in your system.

Collecting telemetry data is an important step in the OpenTelemetry and observability process. Next, we’ll discuss how OpenTelemetry is used in a dispersed cloud environment.

Opentelemetry Architecture And Components

OpenTelemetry's Application Programming Interface (API) defines operations for logging, metrics, and tracing data. More specifically, it provides a way for software components to communicate. 

This decouples applications from the underlying telemetry infrastructure, thus allowing for greater flexibility. Should an organization want to replace the server that runs their cloud, OTel APIs would make it easier. OpenTelemetry APIs are language-specific, such as:

  • Java
  • Ruby
  • JavaScript
  • Python

OpenTelemetry SDK: The Telemetry Data Language Translator

Software Development Kits (SDKs) are language-specific, and DevOps professionals can use them to allow OpenTelemetry APIs to generate telemetry data in the language of their choice. Once the data is generated, it can be exported to a desired backend.

OpenTelemetry SDKs bridge the gap between APIs and collectors, making it possible to connect shared libraries' manual instrumentation with applications' manual instrumentation.

OpenTelemetry Collector: The Telemetry Data Processing Pipeline

The OpenTelemetry Collector is comprised of:

  • Receivers
  • Processors
  • Exporters
  • Aggregators for telemetry data

It can support:

  • Prometheus
  • OpenTelemetry Protocol (OTLP)
  • Jaeger
  • Zipkin
  • Other proprietary tools

Collector Function

The collector can take telemetry data and send it to multiple observability backends. It can assist your organization as a processing pipeline and filter your data before exporting, which helps troubleshoot potential issues more quickly.

Automatic Instrumentation: Reducing the Burden of Telemetry Data Collection

Automatic instrumentation differs between programming languages, which takes numerous tedious manual coding out of the equation.

This allows developers to collect telemetry data and get back to solving the business problems at hand.

 

3 Common Challenges Of Opentelemetry

OpenTelemetry is a critical enabler of observability for many organizations. It is not without its challenges. When you start working with OpenTelemetry, you may find that the types of data that can be collected and processed are limited.

OpenTelemetry supports a defined set of data types: traces, metrics, and logs. It does not natively support other data types.

Data Limitations

If you need to gather and analyze a type of data that OpenTelemetry doesn't support, you might have to rely on other tools or systems to:

  • Collect 
  • Analyze this data

This goes against the main tenet of OpenTelemetry, which aims to provide one set of observability APIs.

The second challenge you'll encounter with OpenTelemetry is its complexity. OpenTelemetry can have a steep learning curve and might be difficult for developers without expertise in observability. Setting up and configuring OpenTelemetry is also a non-trivial effort. You must configure numerous components, including the:

  • Collector
  • Exporters
  • Instrumentation

The project is evolving rapidly, adding new features and updates regularly. This can make it difficult for you to keep up with the changes.

Maintenance: OpenTelemetry and the Challenges of Large-Scale Operations

OpenTelemetry becomes more challenging to configure and manage at a large scale. Managing large-scale OpenTelemetry deployments requires close monitoring of their:

  • Health
  • Troubleshooting
  • Ongoing adjustment of configurations

This can be a challenge for smaller teams and a burden for larger ones.

Opentelemetry vs Prometheus

OpenTelemetry and Prometheus are two open-source projects that share many similarities and are often used together. They have different goals and approaches. OpenTelemetry is a framework for collecting telemetry data, while Prometheus is a monitoring tool specializing in time-series data. 

OpenTelemetry can export telemetry data in a format that Prometheus understands, allowing you to visualize OpenTelemetry metrics in Prometheus.

Metrics vs. Telemetry Data

Prometheus is explicitly designed for gathering and processing metrics, while OpenTelemetry collects metrics along with:

  • Traces 
  • Logs

Telemetry Benefits

When you instrument your application with OpenTelemetry, you'll get all three types of telemetry data. The metrics can then be exported to Prometheus for:

  • Storage 
  • Visualization

The traces and logs provide context for the metrics, helping you better understand your application's performance.

Opentelemetry Browser Instrumentation

OpenTelemetry provides libraries that enable the collection of telemetry data from web browsers using the OpenTelemetry API. You can collect performance metrics, traces, and telemetry data from client-side applications running in the browser. The collected data can be exported to an observability backend.

Telemetry Benefits

By using OpenTelemetry Browser Instrumentation, developers can gain valuable insights into how their web applications are performing and identify opportunities for optimization, leading to a better user experience. OpenTelemetry is backed by CNCF and continuously evolves to improve software system observability.

OpenTelemetry provides an instrumentation layer; you would need a backend to store and analyze data. Let’s learn how to instrument a React browser application with OpenTelemetry.

OpenTelemetry Is a Game Changer for Debugging React Apps

Instrumenting a React browser application with OpenTelemetry (OTel) involves setting up OTel to capture:

  • Traces
  • Metrics
  • Logs within your application

OpenTelemetry provides a standardized way to gather telemetry data across distributed systems, which helps monitor and debug your app.

Step-By-Step Guide to Using OpenTelemetry With React

Here’s a step-by-step guide to instrument a React browser application with OpenTelemetry:

1. Install OpenTelemetry Packages

First, install the necessary OpenTelemetry libraries for browser-based applications:

```bash
npm install @opentelemetry/api @opentelemetry/sdk-trace-web @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources
```

  • @opentelemetry/api`: Core OpenTelemetry API..
  • `@opentelemetry/sdk-trace-web`: Web tracing SDK.
  • `@opentelemetry/exporter-trace-otlp-http`: OTLP HTTP exporter to send traces to a collector or backend.
  • `@opentelemetry/resources`: Helps to define and collect resource information like service name.

2. Set Up OpenTelemetry in Your React Application

You’ll want to initialize OpenTelemetry as early as possible in your application, usually in your entry point (index.js or App.js).

```javascript
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';

Step 1: Set up the tracer provider
const provider = new WebTracerProvider({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: 'react-app', // Name your service
  }),
});

Step 2: Configure an exporter (console exporter for testing, OTLP for production)
const exporter = new OTLPTraceExporter({
  // The endpoint where you want to send telemetry data (to a collector or observability backend)
  url: 'http://localhost:4318/v1/traces', // Example URL for local OpenTelemetry Collector
});

Step 3: Add span processor (Batch processor is preferred in production)
provider.addSpanProcessor(new SimpleSpanProcessor(exporter));

Optional: Add a ConsoleSpanExporter for debugging purposes
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));

Step 4: Register the provider
provider.register();

Now OpenTelemetry is initialized and will start collecting traces.
```

Tracer Provider: The core component that manages traces.
Exporters: Used to send trace data to a collector (e.g., the OTLP HTTP Exporter).
Span Processors: Responsible for processing spans before they’re exported (e.g., batch processing for optimized performance).
Service name: This helps to identify your application in observability backends.

3. Instrument Application Components

OpenTelemetry can automatically instrument browser events (like page loads and navigation) and manual spans for React components or functions.

Automatically Instrumenting Browser Events

The `@opentelemetry/sdk-trace-web` library can automatically capture page load and navigation events. It was initialized when you registered the tracer provider.

Manually Instrumenting React Components

You can create custom spans to track specific parts of your application.

```javascript
import { trace } from '@opentelemetry/api';

const MyComponent = () => {
  // Get the current tracer
  const tracer = trace.getTracer('react-app-tracer');

  // Create a new span
  const span = tracer.startSpan('render_my_component');
 
  // Perform any task or render logic here...

  // End the span once the task is done
  span.end();

  return (
    <div>
      <h1>My Component</h1>
    </div>
  );
};
```

startSpan: Marks the start of a traceable operation.
span.end(): Ends the span and sends it for processing/export.

You can also wrap API calls, database queries, or user interactions with custom spans to trace the lifecycle of these operations.

5. Set Up a Backend Collector (Optional)

For production applications, sending telemetry data to an OpenTelemetry Collector or a backend observability tool is common. If you’re using the OTLP exporter, you must set up an OpenTelemetry Collector or direct your data to a SaaS observability solution that supports OpenTelemetry.

Example for running an OpenTelemetry Collector locally (via Docker):

```bash
docker run --rm -p 4317:4317 -p 4318:4318 otel/opentelemetry-collector-contrib
```

This collector will receive traces at the URL http://localhost:4318/v1/traces (as used in the example above).

6. Monitor and Debug

After setting up instrumentation, you can see telemetry data flow through your system. If using the ConsoleSpanExporter, you can debug trace spans directly in the browser’s console. With an OTLP exporter, view traces in your collector or backend system.

Related Reading


5 Opentelemetry Best Practices

1. Use Attributes for Enhanced Performance Monitoring

Attributes are key-value pairs that provide context for:

Resources represent the component that emits telemetry, like a process in a container.

Attribute Power

Attributes enable teams to capture additional data to find meaningful correlations, e.g., in the face of performance changes. Whether for root cause analysis or forward-looking performance optimization, attributes can help:

  • Filter
  • Search
  • Visualize
  • Aggregate telemetry data 

Attribute Types

Here are a few types of attributes you can use to improve observability:

  • User-specific attributes: Provide context about the application user involved in a session or transaction.
  • Software-related attributes: Provide information about the software involved in an activity.
  • Data-related attributes: Provide context about the data used or transferred in a session or activity.
  • Infrastructure-related attributes: Provide context about the infrastructure involved in an activity.

2. Consistency is Key When Using Attributes

If you use attributes in an organization with multiple teams and codebases, it is crucial to adopt attributes consistently. Without this standardization, troubleshooting issues across team and codebase boundaries becomes far more complex and confusing.

3. Assess Cardinality Before Adding Attributes

Cardinality measures the number of dimensions in which telemetry data is likely to be:

  • Recorded 
  • Queried

Attribute values and their indexing are the largest sources of increased cardinality. Depending on the backend storing the data, they may require much more storage or significantly slow down queries.

4. Keep Initialization Separate from Instrumentation

One of OpenTelemetry's biggest benefits is that it enables vendor-agnostic instrumentation. Your application makes all telemetry calls through the vendor-independent OpenTelemetry API. To maintain this vendor independence, it is important to keep the provider configuration at the top level of your application or service (usually at the entry point). 

This decouples the OpenTelemetry instrumentation from instrumentation calls, allowing you to choose the tracing framework that best suits your use case without changing your instrumentation code. Decoupling provider configuration from instrumentation also allows you to switch providers easily using flags or environment variables.

Provider Flexibility

In a continuous integration (CI) environment where you run integration tests, you may not want to run a tracing provider at all to reduce:

  • Cost 
  • Complexity

In local development, it might be enough to trace metrics using an in-memory export, while in production, a hosted SaaS service is necessary. Separating provider initialization from instrumentation makes it easy to switch providers based on your environment.

5. Unit Test Tracing Using Memory Span Exporters

In most cases, unit tests focus on program logic and ignore telemetry, which can make telemetry unusable when you need it most. OpenTelemetry SDKs provide in-memory exporters, which let you query telemetry data collected during unit tests. 

These constructs are not documented in most languages, so the best place to find examples of their use is in the OpenTelemetry unit tests for each project.

Catch Issues Before They Affect Your Users with Alerty's Free APM Solution

Alerty is a cloud monitoring service for developers and early-stage startups. It offers:

  • Application performance monitoring
  • Database monitoring
  • Incident management

Alerty is designed for ease of use, allowing quick setup, and integrates with tools like Sentry. Its quick incident management helps developers and small teams optimize user experience.

Related Reading