Production Readiness: Monitoring and Observability
10 min read
You have successfully built your application, tested the APIs, and everything works flawlessly on your local machine. But deploying to production is entirely different terrain. Once your application is running on a remote server, it essentially becomes a black box.
If the system crashes, runs out of memory, or a user complains that checking out their cart took 15 seconds, how do you know what went wrong? You need tools to observe the internal state, track application health, format your logs cleanly, and trace user journeys across microservices.
This guide will walk you through the industry standards for observing and monitoring a Spring Boot application.
1. Taking the Pulse: Introducing Spring Boot Actuator 🩺
Definition: Spring Boot Actuator is a built-in framework module that exposes operational information about a running application via HTTP endpoints or JMX beans. It provides real-time insights into metrics, health status, and internal application configurations.
The Problem: When an application is deployed, operations teams need to know if it is healthy. If a database goes offline, the application might sit in the server throwing errors endlessly. Without an explicit way to check its internal state, automated systems (like Kubernetes or AWS Auto Scaling) cannot know if the app needs to be restarted.
The Solution: Actuator solves this by automatically providing predefined endpoints. Instead of you manually writing custom API controllers to verify database connections or check available disk space, Actuator generates production-ready endpoints like /actuator/health and /actuator/metrics straight out of the box.
Interesting Fact: Actuator was introduced in April 2014 with the very first Spring Boot release. It is the literal definition of "Production-Ready" in the Spring ecosystem. Without it, you are flying blind in production.
Hands-on Setup
Adding Actuator requires zero configuration to start. You simply add the dependency.
Maven (pom.xml):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>Gradle (build.gradle):
implementation 'org.springframework.boot:spring-boot-starter-actuator'Important Endpoints Used in the Industry
By default, Spring Boot 3.x only exposes /actuator/health over HTTP for security reasons. Here are the most practically used endpoints:
/actuator/health: Returns the health status of the app (UP,DOWN,OUT_OF_SERVICE). It automatically checks connected databases, message brokers, and disk space./actuator/info: Displays arbitrary application information (like a Git commit hash, build version, or custom descriptions)./actuator/metrics: Shows raw metrics like JVM memory usage, CPU load, and HTTP request timings./actuator/env: Returns all environment properties and variables actively loaded in the application./actuator/heapdump: Downloads a binary gzip heap dump. (An absolute lifesaver for debugging memory leaks)./actuator/prometheus: Formats metrics specifically for Prometheus monitoring scrapers.
Under the hood: Actuator uses an internal mechanism called EndpointDiscoverer to scan your application context for classes annotated with @Endpoint. It then automatically wires these up as standard HTTP request handlers under the /actuator base path.
2. Securing and Exposing Health, Metrics, and Info Endpoints 🔒
Definition: Endpoint exposure determines which Actuator endpoints are accessible via network protocols (like HTTP). Securing them involves enforcing authentication and authorization rules so only permitted users or automated scrapers can view the data.
The Problem: Actuator endpoints contain highly sensitive operational data. If /actuator/env is publicly exposed, anyone on the internet can read your database passwords, secret keys, and AWS credentials. If /actuator/heapdump is left open, attackers can download your server's memory, which often contains raw user sessions and unencrypted passwords.
The Solution: You restrict exposure in your configuration file to only what is necessary, and you lock down the HTTP paths using Spring Security.
Industry Standard Configuration
Never expose * (everything) over the web in production unless the app is strictly running behind an isolated internal network.
application.yml:
management:
endpoints:
web:
exposure:
# Selectively expose only the endpoints your monitoring tools need
include: health, info, metrics, prometheus
endpoint:
health:
# Show detailed health components (like "Database is UP") only to authorized users
show-details: when_authorized
info:
env:
enabled: trueSecuring with Spring Security
In enterprise architectures, Actuator endpoints are usually protected using a SecurityFilterChain. It is common to leave basic health checks public (so load balancers can hit them easily) while locking everything else behind an ADMIN role.
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class ActuatorSecurityConfig {
@Bean
public SecurityFilterChain actuatorSecurity(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
// Allow public access to the basic health check
.requestMatchers(EndpointRequest.to("health")).permitAll()
// Require 'ADMIN' authority for all other actuator endpoints
.requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
// Apply standard rules for the rest of your APIs
.anyRequest().authenticated()
)
.httpBasic(); // Or configure OAuth2/JWT depending on your system
return http.build();
}
}Funny Exaggeration: Leaving /actuator/env exposed to the public internet without security is like pasting your production database credentials on a billboard in Times Square and hoping nobody passing by knows how to read.
3. Logging Best Practices: Slf4j, Logback Configurations, and MDC 📝
Definition:
- SLF4J (Simple Logging Facade for Java): An abstraction API for logging frameworks. It allows you to write log statements without hardcoding a specific logging engine.
- Logback: The actual logging implementation (the engine that writes the logs to the console or file).
- MDC (Mapped Diagnostic Context): A dictionary (map) managed by the logging framework on a per-thread basis to supply contextual information to logs.
The Problem: In a busy application, hundreds of users make requests simultaneously. The server handles these concurrently using threads. If you look at a standard log file, you will see a chaotic, intertwined mess of database queries, API calls, and logic processing from 50 different users. If a user named Alice complains her payment failed at 10:05 AM, finding her exact error in a file with 20,000 lines generated in that specific minute is like finding a needle in a haystack.
The Solution: MDC solves the concurrency problem by allowing you to attach a unique "Request ID" to the specific thread handling Alice's request. Every log generated by that thread will automatically inject Alice's Request ID into the text.
The Analogy for MDC
Imagine you manage a massive fast-food kitchen. You have 10 chefs (threads) cooking hundreds of meals (requests) concurrently. If a chef yells, "The fries are burned!", you have no idea which customer is getting ruined fries.
MDC is like assigning an order ticket number to every meal. Now the chef yells, "Order #404: The fries are burned!" You instantly know exactly which transaction failed and who to refund.
Setting Up Logback
Spring Boot uses SLF4J and Logback automatically. You do not need new dependencies. While you can configure basic logs in application.yml, industry standard mandates using an XML file for advanced routing (like saving logs to rolling files or formatting them as JSON for tools like Datadog or ELK).
Create a logback-spring.xml in src/main/resources:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- Import Spring Boot's default console formats -->
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<!-- Define a custom pattern that extracts our MDC 'requestId' -->
<property name="CONSOLE_LOG_PATTERN"
value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr([%15.15t]){faint} %clr([%X{requestId}]){blue} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>Notice the %X{requestId} in the pattern. The %X syntax instructs Logback to extract the value from the MDC map.
Using MDC in Java
We typically use a Servlet Filter to generate a unique ID as soon as an HTTP request touches the application.
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import jakarta.servlet.*;
import java.io.IOException;
import java.util.UUID;
@Component
public class RequestLoggingFilter implements Filter {
private static final String REQUEST_ID = "requestId";
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
// Generate a unique ID and put it in the MDC thread context
String uniqueId = UUID.randomUUID().toString();
MDC.put(REQUEST_ID, uniqueId);
// Continue processing the request down the chain
chain.doFilter(request, response);
} finally {
// CRITICAL: Always clear the MDC in a finally block!
// Threads are pooled. If you don't clear this, the next user who borrows
// this thread will inherit the previous user's Request ID!
MDC.remove(REQUEST_ID);
}
}
}Now, even if you just write log.info("Processing payment"); deep inside a nested service layer, the console will print:2026-02-25 10:00:00.000 INFO [http-nio-8080-exec-1] [a1b2c3d4...] com.service.PaymentService : Processing payment
4. Tracing the Flow: Centralized Observability Basics (Micrometer) 🕸️
Definition: Distributed tracing is a methodology to track application requests as they traverse across multiple independent services.
- Trace: The complete, end-to-end journey of a request across your entire system.
- Span: A single logical unit of work within that trace (e.g., an HTTP call to another microservice, or a database query).
- Micrometer Tracing: A tracing facade in Spring Boot 3.x that provides a vendor-neutral API for recording traces.
The Problem: MDC is fantastic for tracking requests inside a single monolithic application. But in a modern microservices architecture, a user clicks "Checkout", which hits Service A (Order). Service A then calls Service B (Inventory), which subsequently calls Service C (Payment).
If the user's request fails, which service caused it? If it took 10 seconds, which service was the bottleneck? Searching through individual logs on three separate servers manually is practically impossible.
The Solution: Distributed Tracing assigns a global Trace ID to the very first request. When Service A calls Service B, it passes this Trace ID along via HTTP headers (a concept known as Context Propagation). Service B continues the tradition, passing it to Service C. A centralized visualization tool (like Jaeger, Zipkin, or OpenTelemetry Collector) gathers these spans and stitches them together into an interactive timeline graph.
Important Note: If you learned tracing in Spring Boot 2.x, you likely used Spring Cloud Sleuth. In Spring Boot 3.x, Sleuth has been deprecated and entirely replaced by Micrometer Tracing.
Hands-on Setup: Micrometer with OpenTelemetry
Spring Boot uses Micrometer Tracing as the API facade, but you need a concrete implementation underneath. The industry standard has heavily shifted towards OpenTelemetry (OTel).
Dependencies (pom.xml):
<!-- The Micrometer Tracing API and OpenTelemetry Bridge -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-tracing-bridge-otel</artifactId>
</dependency>
<!-- Optional: Exporter to send traces to a visualization backend (like Zipkin or Jaeger) -->
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-exporter-zipkin</artifactId>
</dependency>Context Propagation (How it travels)
When you add the dependency above, Spring Boot automatically configures your application to inject and extract trace context into HTTP headers.
By default, it uses the W3C Trace Context specification. It injects HTTP headers that look like this:
traceparent:00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
(This compact string contains the global Trace ID, the parent Span ID, and sampling flags)
If you make external API calls using Spring's RestTemplate, WebClient, or RestClient, Spring Boot intercepts the outgoing request and seamlessly attaches this header. No extra code is required on your part!
Configuration (application.yml):
management:
tracing:
sampling:
# 1.0 means 100% of requests are traced.
# In massive production systems handling millions of requests,
# this is usually set to 0.1 (10%) to save storage space.
probability: 1.0
zipkin:
tracing:
# Where to send the tracing data for visualization
endpoint: "http://localhost:9411/api/v2/spans"Under the Hood
When an HTTP request arrives at your Tomcat server, Micrometer triggers a listener. It creates a new Span, generates a Trace ID, and automatically injects it into your SLF4J MDC. This means your logs organically get [traceId=..., spanId=...] attached to them without you writing a single filter. When the request completes, Micrometer closes the Span and fires it off asynchronously over the network to your tracing backend, completely decoupled from the main application thread.
References & Further Reading 📚
Challenge
Challenge: Secure Spring Boot Actuator for Production
You are responsible for deploying a new Spring Boot microservice. To ensure it's production-ready, you must configure its Actuator endpoints with proper security. Your task is to modify both the configuration file and the security configuration class to meet the following requirements:
Part 1: application.yml Configuration
- Configure the application to expose only three specific web endpoints:
health,info, andprometheus. All other Actuator endpoints should remain disabled over HTTP.
Part 2: Java Security Configuration (SecurityConfig.java)
- Implement a
SecurityFilterChainbean to define the following authorization rules:- The
/actuator/healthendpoint must be publicly accessible without authentication, as it will be used by a load balancer. - All other exposed Actuator endpoints (
/actuator/infoand/actuator/prometheus) must be accessible only to users with theADMINrole. - All other requests to the application (i.e., non-actuator endpoints) must require users to be authenticated.
- The
Expected result
Expected application.yml
The include property should list the specified endpoints as a comma-separated string.
management:
endpoints:
web:
exposure:
include: "health,info,prometheus"Expected SecurityConfig.java
The securityFilterChain bean should be implemented using EndpointRequest matchers to correctly apply the required permissions.
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authz -> authz
.requestMatchers(EndpointRequest.to("health")).permitAll()
.requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
.anyRequest().authenticated()
);
return http.build();
}
}