OpenTelemetry with Spring Boot [Step-by-Step]
Monitoring distributed applications is a critical part of modern software development. Spring Boot, as one of the most popular Java frameworks, requires effective observability tools to ensure optimal performance. This guide will show you how to integrate OpenTelemetry with Spring Boot applications and leverage Uptrace to gain valuable insights into your application's behavior and performance.
What is OpenTelemetry?
OpenTelemetry is an open-source observability framework that aims to standardize and simplify the collection, processing, and export of telemetry data from applications and systems.
OpenTelemetry supports multiple programming languages and platforms, making it suitable for a wide range of applications and environments.
OpenTelemetry enables developers to instrument their code and collect telemetry data, which can then be exported to various OpenTelemetry backends or observability platforms for analysis and visualization.
For Spring Boot developers, it offers several key advantages:
- Framework Agnostic: Works seamlessly with Spring Boot and other Java frameworks
- Vendor Neutral: Not tied to any specific backend system
- Comprehensive Data Collection: Captures traces, metrics, and logs through a unified API
- Automatic Instrumentation: Requires minimal configuration to start collecting data
OpenTelemetry vs Micrometer
When developing Spring Boot applications, you'll need to choose between these two observability frameworks. While Micrometer comes integrated with Spring Boot, OpenTelemetry offers some distinct advantages for distributed tracing in Spring environments. Here's a quick comparison:
Feature | OpenTelemetry | Micrometer |
---|---|---|
Scope | Traces, Metrics, Logs | Primarily Metrics |
Integration | Framework agnostic | Spring ecosystem |
Backend Support | Any OTLP-compatible backend | Limited to specific systems |
Standardization | Industry standard | Spring-specific |
Distributed Tracing | First-class support | Limited support |
While Micrometer provides excellent metrics collection within the Spring ecosystem, OpenTelemetry offers a more comprehensive solution that includes powerful distributed tracing capabilities.
Integration Options
Spring Boot applications can be instrumented with OpenTelemetry using two main approaches, each with different advantages:
- OpenTelemetry Java Agent (recommended): Zero-code approach that uses bytecode instrumentation
- Spring Boot Starter: Manual integration through Spring Boot's dependency management
This guide focuses on the Java Agent approach as it requires no code changes and provides comprehensive instrumentation out-of-the-box.
Setting Up Demo Application
To demonstrate OpenTelemetry integration, we'll use the "Conduit" application from the RealWorld project - a full-stack application with Spring Boot backend and React frontend.
About the Demo Application
The RealWorld project offers a Spring Boot implementation that serves as an excellent test case for OpenTelemetry integration, showcasing how traces flow through different Spring Boot components.
The RealWorld example app (Conduit) is a Medium.com clone that provides an ideal environment for testing distributed tracing concepts:
- Backend: Uses Spring Boot to provide a RESTful API
- Frontend: React + Redux application consuming the API
- Features: Authentication, article creation, comments, profiles, and more
This combination creates an ideal environment to demonstrate how OpenTelemetry traces requests from the frontend through various backend services.
Step 1: Backend Setup
First, we need to prepare our Spring Boot backend application. This involves downloading the Spring Boot RealWorld example and configuring it for OpenTelemetry instrumentation.
Let's start by downloading and configuring the backend:
git clone https://github.com/gothinkster/spring-boot-realworld-example-app.git
cd spring-boot-realworld-example-app
The app uses Gradle as its build tool. Build the application JAR:
./gradlew bootJar
If you encounter a dependency issue with snakeyaml, apply this fix to build.gradle
:
diff --git a/build.gradle b/build.gradle
index 12781f0..52a8f71 100644
--- a/build.gradle
+++ b/build.gradle
@@ -33,6 +33,7 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt:0.9.1'
implementation 'joda-time:joda-time:2.10.6'
implementation 'org.xerial:sqlite-jdbc:3.34.0'
+ implementation 'org.yaml:snakeyaml:1.28'
After fixing any dependency issues, rebuild the JAR:
./gradlew bootJar
Verify the backend by running it without instrumentation first:
java -jar build/libs/spring-boot-realworld-example-app-0.0.1-SNAPSHOT.jar
Test the API with:
curl http://localhost:8080/tags
{"tags":[]}
Once confirmed working, stop the application with CTRL+C.
Step 2: Java Agent
The OpenTelemetry Java Agent is a powerful tool that automatically instruments your Spring Boot application without requiring code changes.
How the Java Agent Works
The agent operates by:
- Attaching to the JVM at startup
- Using bytecode instrumentation to inject OpenTelemetry code
- Intercepting method calls to collect telemetry data
- Exporting data to your configured backend
Key Benefits
The OpenTelemetry Java Agent provides several advantages specifically for Spring Boot applications, including automatic instrumentation of Spring MVC controllers, Spring Data repositories, and other Spring components.
- Zero Code Changes: Instrument your application without modifying source code
- Automatic Framework Detection: Recognizes and instruments Spring Boot automatically
- Comprehensive Coverage: Captures data from Spring MVC, Spring WebFlux, JDBC, Hibernate, etc.
- Minimal Performance Impact: Designed for production use with low overhead
Downloading the Java Agent
Get the latest version of the OpenTelemetry Java Agent:
wget https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar
Step 3: Uptrace Configuration
Now we'll configure OpenTelemetry in our Spring Boot application to send telemetry data to Uptrace for storage and visualization.
Uptrace is an open source APM tool that supports OpenTelemetry tracing, OpenTelemetry metrics, and OpenTelemetry logs. You can use it to monitor applications and set up alerts to receive notifications via email, Slack, Telegram, and more.
Why Choose Uptrace?
When monitoring Spring Boot applications, Uptrace offers several compelling advantages:
- Easy Integration: Works seamlessly with the OpenTelemetry Java Agent
- Powerful Trace Explorer: Analyze complex request flows across services
- Spring Framework Awareness: Understands Spring-specific components in traces
- Low Overhead: Designed for production environments with minimal impact
- Open Source Core: Aligns with Spring's open-source philosophy
Connection Setup
To enable your Spring Boot application to send OpenTelemetry data to Uptrace, you'll need to configure several environment variables that control how telemetry is collected and exported.
To configure the OpenTelemetry Java Agent to send data to Uptrace, use these environment variables:
export OTEL_RESOURCE_ATTRIBUTES=service.name=spring-realworld,service.version=1.0.0
export OTEL_TRACES_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_COMPRESSION=gzip
export OTEL_EXPORTER_OTLP_ENDPOINT=https://api.uptrace.dev:4317
export OTEL_EXPORTER_OTLP_HEADERS=uptrace-dsn=<your_uptrace_dsn>
export OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA
export OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=BASE2_EXPONENTIAL_BUCKET_HISTOGRAM
Replace <your_uptrace_dsn>
with your actual Uptrace DSN, which you can obtain after installing Uptrace and creating a project.
Fine-Tuning Your Setup
The OpenTelemetry Java Agent accepts numerous configuration options. Here are some useful options for Spring Boot applications:
Configuration | Description | Recommended Value |
---|---|---|
otel.instrumentation.spring-webmvc.enabled | Enables/disables Spring Web MVC instrumentation | true |
otel.instrumentation.jdbc.enabled | Enables/disables JDBC instrumentation | true |
otel.javaagent.debug | Enables debug logging for the agent | false (production), true (troubleshooting) |
otel.traces.sampler | Configures sampling strategy | parentbased_always_on (development), parentbased_traceidratio (production) |
otel.traces.sampler.arg | Sampling probability when using traceidratio | 0.1 to 1.0 |
These options can be set as environment variables with the OTEL_
prefix or as system properties with the -D
flag.
Step 4: Running the Instrumented App
Now, let's run the Spring Boot application with OpenTelemetry instrumentation:
java -javaagent:opentelemetry-javaagent.jar -jar build/libs/spring-boot-realworld-example-app-0.0.1-SNAPSHOT.jar
Ensure the API is still working properly:
curl http://localhost:8080/tags
{"tags":[]}
The OpenTelemetry Java Agent is now collecting telemetry data from your Spring Boot application!
Step 5: Frontend Setup
To complete our demo environment and show end-to-end tracing, we'll configure the frontend application to communicate with our OpenTelemetry-instrumented Spring Boot backend.
git clone https://github.com/gothinkster/react-redux-realworld-example-app.git
cd react-redux-realworld-example-app
npm install
Configure the frontend to connect to our Spring Boot backend by editing src/agent.js
:
const API_ROOT = 'http://localhost:8080'
Start the React application:
npm start
The UI should now be available at http://localhost:4100/register
.
Analyzing Your Traces
After interacting with the application, you'll see traces appearing in your Uptrace project. Here's what you can observe:
Understanding Your Data
Spring Boot applications generate rich telemetry data that Uptrace helps you explore. With this data, you can:
- Request Flow: Visualize how requests move through your application
- Span Details: See detailed timing for each operation
- Service Dependencies: Understand how components interact
- Error Analysis: Identify failures and exceptions
- Performance Metrics: Track latency and throughput
Components in Traces
With OpenTelemetry and Uptrace, you can see detailed information about:
- Spring Controllers: Request handling and processing time
- Database Operations: SQL queries and timing
- External HTTP Calls: APIs and third-party services
- Authentication: Security checks and token validation
- Template Rendering: View processing time
Advanced Configuration Options
While the default setup works well for development, production Spring Boot deployments require additional configuration to optimize performance and resource usage. Here are some important settings to consider:
Sampling Strategies
For high-traffic applications, implement sampling to reduce data volume:
export OTEL_TRACES_SAMPLER=parentbased_traceidratio
export OTEL_TRACES_SAMPLER_ARG=0.1 # Sample 10% of traces
Resource Detection
Enhance your traces with automatic cloud resource detection:
export OTEL_SERVICE_NAME=spring-realworld
export OTEL_RESOURCE_ATTRIBUTES=deployment.environment=production
export OTEL_JAVA_DISABLED_RESOURCE_PROVIDERS=none
Batch Export
Optimize export performance with batching:
export OTEL_BSP_SCHEDULE_DELAY=5000
export OTEL_BSP_MAX_QUEUE_SIZE=2048
export OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512
Excluding Instrumentations
Disable unnecessary instrumentation for better performance:
export OTEL_INSTRUMENTATION_COMMON_DEFAULT_ENABLED=true
export OTEL_INSTRUMENTATION_LOGBACK_APPENDER_ENABLED=false
Comparison with Other Solutions
Solution | Pros | Cons |
---|---|---|
OpenTelemetry | - Open standard - Comprehensive (traces, metrics, logs) - No vendor lock-in | - More complex initial setup - Newer ecosystem |
Spring Boot Actuator | - Built into Spring Boot - Simple setup - Good for basic metrics | - Limited distributed tracing - Basic metrics only |
Micrometer + Prometheus | - Native Spring support - Strong metrics capabilities - Mature ecosystem | - Limited tracing capabilities - Separate systems for logs |
Commercial APMs | - All-in-one solutions - Polished dashboards | - Expensive - Vendor lock-in |
OpenTelemetry with Uptrace provides the best balance of features, flexibility, and cost for most Spring Boot applications.
Conclusion
OpenTelemetry provides a powerful, standardized approach to instrumenting Spring Boot applications. By leveraging the Java Agent and Uptrace, you can gain comprehensive insights into your application's behavior with minimal effort.
Key takeaways:
- The OpenTelemetry Java Agent offers zero-code instrumentation for Spring Boot
- Uptrace provides powerful visualization and analysis of telemetry data
- The combination delivers comprehensive observability for your Spring ecosystem
Ready to get started? Sign up for a free Uptrace account and begin monitoring your Spring Boot applications today!
Additional Resources
Table of Contents