โ† Back to list

๐Ÿ“Š Measuring RTT in React using OpenTelemetry and Grafana ๐Ÿš€

In modern web applications, performance measurement is essential for delivering a responsive user experience. One effective way to monitorโ€ฆ

Ali Eren ร‡elebi ยท 2024-11-13 08:04 ยท 0 claps ยท 3.7 min read
#react #opentelemetry #grafa #monitoring #typescript
Open on Medium โ†—
Wiki topics: UX ยท UI/UX Design ๐ŸŒ ยท Web Development

๐Ÿ“Š Measuring RTT in React using OpenTelemetry and Grafana ๐Ÿš€

In modern web applications, performance measurement is essential for delivering a responsive user experience. One effective way to monitor performance is by tracking Round Trip Time (RTT) for key operations using OpenTelemetry and visualizing the data with Grafana and Jaeger.

In this guide, weโ€™ll walk through setting up OpenTelemetry in a React application, tracking spans, and visualizing them in Grafana with Jaeger as the backend.

What is RTT?

Round Trip Time (RTT) refers to the time it takes for a request to go from the client to the server and back. Itโ€™s a critical metric for understanding the responsiveness of your application, especially when making API calls. By tracking RTT, you can optimize your systemโ€™s performance and improve user satisfaction.

๐Ÿ› ๏ธ Technologies Used

Before diving into the code, hereโ€™s a quick overview of the technologies weโ€™ll be using in this guide:

  • React: A popular front-end JavaScript library for building user interfaces.
  • OpenTelemetry: A set of APIs and tools designed for observability to collect traces and metrics from your application.
  • OTLP (OpenTelemetry Protocol): A protocol for exporting telemetry data (like traces) from your application.
  • Jaeger: An open-source, end-to-end distributed tracing system used for monitoring and troubleshooting microservices.
  • Grafana: A powerful open-source visualization tool that allows you to create, explore, and share dashboards.

Step 1: Setting Up OpenTelemetry in React

To get started, you need to install the necessary OpenTelemetry packages:

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

Weโ€™ll configure OpenTelemetry to measure RTT and export traces for visualization.

Initialize OpenTelemetry Tracer

Create a file named openTelemetry.ts

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

export const tracer = trace.getTracer('react-app-tracer');

export const initializeTracer = () => {
  const exporter = new OTLPTraceExporter({
    url: 'http://localhost:4318/v1/traces'
  });

  const provider = new WebTracerProvider({
    resource: new Resource({
      [SemanticResourceAttributes.SERVICE_NAME]: 'ReactApp'
    })
  });

  provider.addSpanProcessor(new SimpleSpanProcessor(exporter));
  provider.register();
};

export const startTrace = (spanName: string, additionalAttributes?: Attributes) => {
  const span = tracer.startSpan(spanName);
  if (additionalAttributes) {
    span.setAttributes(additionalAttributes);
  }

  return {
    addEvent: (eventName: string, eventAttributes?: Attributes) => {
      span.addEvent(eventName, eventAttributes);
    },
    end: () => span.end()
  };
};

Explanation

  • initializeTracer() sets up a tracer provider and registers it.
  • startTrace() creates a new span to measure RTT for a specific operation.
  • addEvent() allows you to log custom events within the span.

Step 2: Integrating OpenTelemetry in React Components

Now that we have our tracer set up, letโ€™s measure RTT in a React component that performs an API call.

Using OpenTelemetry in a Component

import { useEffect, useState } from 'react';
import { Button, CircularProgress } from '@mui/material';
import { startTrace } from './openTelemetry';
const fetchData = async () => {
 // Simulating an API call
 return new Promise((resolve) => setTimeout(() => resolve("Data loaded"), 1000));
};
export const DataFetcher = () => {
 const [loading, setLoading] = useState(false);
 const [data, setData] = useState<string | null>(null);
const handleFetchData = async () => {
 setLoading(true);
// Start a trace for measuring RTT
 const trace = startTrace('FetchData');

 try {
 const result = await fetchData();
 trace.addEvent('data-fetch-success');
 setData(result as string);
 } catch (error) {
 trace.addEvent('data-fetch-failed', { error: error.message });
 } finally {
 trace.end();
 setLoading(false);
 }
 };
return (
 <div>
 <Button onClick={handleFetchData} disabled={loading}>
 {loading ? <CircularProgress size={24} /> : 'Fetch Data'}
 </Button>
 {data && <div>Data: {data}</div>}
 </div>
 );
};

Explanation

  • handleFetchData() starts a trace when the button is clicked.
  • addEvent() logs custom events like successful or failed data fetching.
  • The trace ends after the API call completes.

Step 3: Visualizing Traces in Grafana with Jaeger

Once your traces are being sent to your OpenTelemetry backend, you can visualize them in Grafana using Jaeger as your data source.

How to Visualize in Grafana

1. Add Jaeger as a Data Source in Grafana:

  • Go to Settings > Data Sources.
  • Select Jaeger and configure the endpoint.

2. Create Dashboards:

  • Create a new dashboard and use Jaeger queries to filter traces by span names (e.g., FetchData).
  • Visualize RTT and other metrics to analyze your applicationโ€™s performance.

Tips for Effective RTT Monitoring

  1. Use Attributes for Context

Add context to your spans using attributes to make it easier to filter and analyze traces.

const trace = startTrace('APIRequest', { userId: '1234', env: 'production' });

2. Log Custom Events

Use addEvent() to track significant milestones within your spans:

trace.addEvent('API-call-started');
trace.addEvent('API-call-completed');

3. Ensure Accurate Span Durations

Make sure spans start and end at the correct points to get precise RTT measurements.

๐ŸŽฏConclusion

By using OpenTelemetry to measure RTT in a React application and visualizing the results with Grafana and Jaeger, you can gain valuable insights into your applicationโ€™s performance. This allows you to identify bottlenecks, optimize response times, and improve the user experience.

Feel free to adapt the provided code to your projectโ€™s needs. Happy tracing!

๐Ÿ“šFurther Reading


๋ฉ”ํƒ€๋ฐ์ดํ„ฐ
post_id
b3d533acf2e3
slug
measuring-rtt-round-trip-time-in-react-using-opentelemetry-grafana-and-jaeger-b3d533acf2e3
url
https://medium.com/@celebialieren/measuring-rtt-round-trip-time-in-react-using-opentelemetry-grafana-and-jaeger-b3d533acf2e3
canonical_url
https://medium.com/@celebialieren/measuring-rtt-round-trip-time-in-react-using-opentelemetry-grafana-and-jaeger-b3d533acf2e3
author_url
https://medium.com/@celebialieren
status
ok
fetched_at
2026-07-22 05:00:42