Production Readiness: Spring Boot Actuator & Observability
9 min read
Production Readiness: Spring Boot Actuator & Observability 🚀
Welcome, intrepid developer, to the crucial stage of making your Spring Boot application not just work, but work well in the real world. Think of it like this: you've built a fantastic car. Now, you need to add a dashboard with a speedometer, fuel gauge, and engine temperature, so you know what's happening under the hood while you're driving. That's what this guide is all about!
1. Exposing Application Health and Metrics with Spring Boot Actuator 🩺
The Problem: The Black Box Application
Imagine your application is running on a server somewhere. It seems to be working... or is it? Is it running out of memory? Is it connected to the database? How many requests is it handling? Without insight, your application is a "black box." When something goes wrong, you're left guessing, and that's a recipe for a very stressful on-call rotation.
The Solution: Spring Boot Actuator
Spring Boot Actuator is a sub-project of Spring Boot that provides production-ready features to help you monitor and manage your application. It pulls back the curtain on your running application by exposing a set of "endpoints" – special URLs that provide information about your app's health, metrics, configuration, and more.
Getting Started with Actuator
Let's get our hands dirty. To add Actuator to your Maven project, you just need to add one dependency to your pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>That's it! 🎉 With this single dependency, Spring Boot automatically configures Actuator.
Under the Hood: When you add this starter, Spring Boot's auto-configuration magic kicks in. It detects the Actuator library on the classpath and automatically creates and configures the necessary beans to expose the Actuator endpoints.
Now, run your application and head over to http://localhost:8080/actuator. You should see a JSON response listing the available Actuator endpoints. By default, for security reasons, only a limited set of endpoints are exposed over HTTP.
Exploring Key Actuator Endpoints
To see the full power, let's expose more endpoints. Add the following to your application.properties or application.yml file:
application.properties
management.endpoints.web.exposure.include=*application.yml
management:
endpoints:
web:
exposure:
include: "*"Disclaimer: Exposing all endpoints with * is great for learning, but in a real production environment, you'll want to be more selective for security reasons, which we'll cover in the next section.
Now, restart your application and revisit http://localhost:8080/actuator. You'll see a much longer list of endpoints. Let's look at some of the most frequently used ones:
/health: This is arguably the most important endpoint. It provides basic information about the health of your application. You'll see an overall "UP" or "DOWN" status. It can also include details about the health of connected services like your database and message queues. For example, if your application can't connect to the database, the health endpoint will report "DOWN" along with details about the database connection issue./info: This endpoint displays general information about your application. You can customize this to show things like the application name, version, and even Git commit information./metrics: This is your application's treasure trove of data. It provides a wide range of metrics, such as memory usage (heap and non-heap), garbage collection statistics, the number of threads, and HTTP request statistics. For example, you can see how many times a specific API endpoint has been called./env: This endpoint lists all the environment properties available to your application, including system properties, environment variables, and properties from yourapplication.properties/ymlfiles. This is incredibly useful for debugging configuration issues./loggers: This allows you to view and modify the logging levels of your application at runtime. Need to debug a specific part of your code? You can change the log level for a particular package fromINFOtoDEBUGwithout restarting your application.
Interesting Fact: The name "Actuator" comes from the world of mechanical engineering. An actuator is a component of a machine that is responsible for moving and controlling a mechanism or system. Similarly, Spring Boot Actuator helps you control and monitor your application.
2. Securing and Customizing Actuator Endpoints for Production 🔐
The Problem: Too Much Information
Exposing all Actuator endpoints to the public is like leaving the blueprints of your house on the front lawn. It reveals sensitive information that could be exploited by malicious actors. We need to control who can see what.
The Solution: Security and Customization
Spring Boot Actuator integrates with Spring Security to provide a robust way to secure your endpoints. You can also customize the path and port of the Actuator endpoints to further obscure them.
Securing Endpoints with Spring Security
First, add the Spring Security starter to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>By simply adding this dependency, all your application endpoints, including the Actuator endpoints, are now protected with basic authentication by default. Spring Boot will even generate a random password for the user account and print it to the console on startup.
For a more production-ready setup, you'll want to define your own security configuration. Here's a common industry practice:
Expose Actuator on a different port. This is a simple yet effective way to isolate your management endpoints from your main application traffic.
application.propertiespropertiesmanagement.server.port=8081Now, your application will run on port 8080, but the Actuator endpoints will be accessible on port 8081.
Selectively expose only the necessary endpoints. Instead of using
*, list the specific endpoints you want to expose.application.propertiespropertiesmanagement.endpoints.web.exposure.include=health,info,prometheusConfigure custom security for Actuator endpoints. You can create a Spring Security configuration to define who can access the management endpoints.
Customizing Actuator Endpoints
Beyond security, you might want to customize the base path for your Actuator endpoints.
application.properties
management.endpoints.web.base-path=/managementWith this configuration, your Actuator endpoints will be available at http://localhost:8081/management/health, http://localhost:8081/management/info, etc. This makes it easier to set up firewall rules and reverse proxies for your management endpoints.
3. Structured Logging: Configuring Logback and Managing Log Levels 📜
The Problem: A Mess of Text
Traditional logging often produces unstructured, plain text messages. While readable by humans, it's difficult for machines to parse and analyze. Imagine trying to find a specific error in a 10 GB log file by manually reading through it. It's a needle-in-a-haystack problem.
The Solution: Structured Logging with Logback
Structured logging is the practice of writing logs in a consistent, machine-readable format, typically JSON. This allows you to easily search, filter, and analyze your logs using tools like the ELK stack (Elasticsearch, Logstash, Kibana) or Splunk.
Spring Boot uses Logback as its default logging framework. We can configure Logback to output logs in a JSON format.
Configuring Logback for JSON Logging
Add the
logstash-logback-encoderdependency to yourpom.xml. This library provides a JSON encoder for Logback.xml<dependency> <groupId>net.logstash.logback</groupId> <artifactId>logstash-logback-encoder</artifactId> <version>7.4</version> <!-- Check for the latest version --> </dependency>Create a
logback-spring.xmlfile in yoursrc/main/resourcesdirectory. This file will contain your custom Logback configuration.xml<configuration> <springProperty scope="context" name="springAppName" source="spring.application.name"/> <appender name="jsonConsoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="net.logstash.logback.encoder.LogstashEncoder"> <fieldNames> <timestamp>timestamp</timestamp> <version>[ignore]</version> <level>level</level> <thread>thread</thread> <logger>logger</logger> <message>message</message> <stackTrace>stack_trace</stackTrace> </fieldNames> <customFields>{"application_name":"${springAppName:-}"}</customFields> </encoder> </appender> <root level="INFO"> <appender-ref ref="jsonConsoleAppender"/> </root> </configuration>
What's happening here?
- We're defining an appender named
jsonConsoleAppenderthat writes to the console. - We're using the
LogstashEncoderto format the log messages as JSON. - We've customized some of the field names and added a custom field for the application name.
- The
<root level="INFO">sets the default log level for the entire application toINFO.
Now, when you run your application, your logs will be printed to the console in a structured JSON format, making them much easier to process.
Managing Log Levels at Runtime
One of the most powerful features of Actuator is the /loggers endpoint. As mentioned earlier, you can use this to change log levels on the fly without restarting your application. This is a lifesaver when you need to debug a specific issue in production.
For example, to change the log level for a specific package to DEBUG, you can send a POST request to the /loggers/{name} endpoint:
curl -i -X POST -H "Content-Type: application/json" -d '{"configuredLevel": "DEBUG"}' http://localhost:8081/actuator/loggers/com.example.yourpackage4. Distributed Tracing Basics: Tracking Requests with Micrometer ιχνηλάτης
The Problem: The Journey of a Request
In modern microservices architectures, a single user request can travel through multiple services before a response is returned. If a request is slow or fails, how do you pinpoint which service is the culprit? It's like trying to find a lost package without a tracking number.
The Solution: Distributed Tracing with Micrometer
Distributed tracing provides a way to track a request as it flows through multiple services. It assigns a unique "trace ID" to each request. As the request passes through different services, this trace ID is propagated, and each service adds its own "span ID" to create a complete picture of the request's journey.
Micrometer is a vendor-neutral application metrics facade that Spring Boot uses. It integrates with various monitoring systems, including distributed tracing systems like Zipkin and Jaeger.
Getting Started with Micrometer Tracing
Add the necessary dependencies to your
pom.xml. We'll use Zipkin as our tracing system.xml<dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-tracing-bridge-brave</artifactId> </dependency> <dependency> <groupId>io.zipkin.reporter2</groupId> <artifactId>zipkin-reporter-brave</artifactId> </dependency>Add a Zipkin exporter dependency if you want to send traces to a Zipkin server.
xml<dependency> <groupId>io.zipkin.reporter2</groupId> <artifactId>zipkin-sender-urlconnection</artifactId> </dependency>Configure your
application.propertiesto tell Micrometer where to send the traces.application.propertiespropertiesmanagement.tracing.sampling.probability=1.0 # Trace all requests for developmentThe
management.tracing.sampling.probabilityproperty controls what percentage of requests are traced. For development,1.0(100%) is fine. In production, you might set this to a lower value like0.1(10%) to reduce overhead.
Under the Hood: When you make a request, Micrometer's tracing instrumentation (which is now part of Spring Boot) intercepts it. It checks for an existing trace ID in the request headers. If one doesn't exist, it generates a new one. It then creates a new span for the work being done in the current service and adds the trace ID and span ID to the logging context. When this service calls another service, it injects the trace ID into the outgoing request's headers.
This allows a tracing system like Zipkin or Jaeger to stitch together the individual spans from each service into a complete trace, giving you a detailed view of the request's journey, including the time spent in each service.
A Fun Analogy: Think of a distributed trace as a relay race. The baton is the trace ID. Each runner is a microservice. When a runner gets the baton, they run their leg of the race (process the request) and then pass the baton to the next runner. Each runner's time is recorded (a span), and at the end, you can see the total time and the split times for each runner.
Further Reading and Resources 📚
- Spring Boot Actuator Documentation: https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html
- Micrometer Documentation: https://micrometer.io/docs
- Logback Project: https://logback.qos.ch/
- Zipkin Distributed Tracing: https://zipkin.io/
Challenge
You are tasked with preparing a Spring Boot microservice for deployment into a production environment. To ensure proper observability and security, you must configure its application.properties file.
Your configuration must achieve the following:
- Set the application's name to
user-serviceso it can be correctly identified in monitoring and service discovery tools. - Isolate the management endpoints by running them on a separate port:
9091. - To avoid path conflicts and improve organization, set a custom base path for all management endpoints to
/management. - For security reasons, expose only the
health,info, andprometheusActuator endpoints. All other endpoints must remain inaccessible over the web. - Enable distributed tracing and configure the sampler to trace 50% of all incoming requests.
- Configure the application to send its tracing data to a Zipkin server running at
http://localhost:9411/api/v2/spans.
Expected result
Your application.properties file should contain the following configurations, in addition to the initial properties:
- A property to set the application name to
user-service. - A property to run the management server on port
9091. - A property to set the base path for web-exposed management endpoints to
/management. - A property that explicitly includes only the
health,info, andprometheusendpoints for web exposure. - A property to set the tracing sampling probability to
0.5. - A property to define the Zipkin tracing endpoint URL as
http://localhost:9411/api/v2/spans.