Actuator and observability
The difference between "the service is down" and "the p99 on /api/books tripled
after the 14:02 deploy" is about twenty lines of configuration.
Setup
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> <scope>runtime</scope> </dependency>
management:
server:
port: 9090 # separate port — do not expose this publicly
endpoints:
web:
exposure:
include: health,info,metrics,prometheus,loggers
base-path: /actuator
endpoint:
health:
show-details: when-authorized
probes:
enabled: true # adds /health/liveness and /health/readiness
loggers:
access: unrestricted # change log levels without a restart
metrics:
tags:
application: ${spring.application.name}
env: ${ENVIRONMENT:local}
observations:
key-values:
application: ${spring.application.name}
info:
app:
name: ${spring.application.name}
version: '@project.version@'
/env and /configprops print your configuration.
/heapdump downloads the entire heap — including every string in memory, so
passwords and tokens. /threaddump and /loggers are useful to an
attacker mapping your system. Use management.server.port to bind actuator to
an internal port, and additionally require a role
(chapter 10). include: "*" in production is a
genuine incident waiting to happen.
The endpoints worth knowing
| Endpoint | Gives you | Expose? |
|---|---|---|
/health | Aggregated up/down plus component detail | Yes (liveness/readiness publicly, details restricted) |
/info | Build version, git commit | Yes |
/metrics | Browse individual metrics | Internal |
/prometheus | Scrape format for Prometheus | Internal |
/loggers | Read and change log levels at runtime | Internal, admin only |
/beans | Every bean, its type and dependencies | Internal |
/conditions | The auto-configuration report | Internal |
/mappings | Every URL and its handler method | Internal |
/configprops | Bound @ConfigurationProperties | Internal only |
/env | Every property and its source | Internal only |
/threaddump | Full thread dump | Internal only |
/heapdump | Downloads a heap dump file | Disable in production |
/scheduledtasks | All @Scheduled methods | Internal |
/startup | Per-bean startup timings | Internal, needs a buffering recorder |
Health checks that mean something
Boot auto-registers indicators for the data source, Redis, Kafka, disk space and more, and aggregates them. The key insight is the liveness vs readiness distinction.
| Probe | Question | If it fails |
|---|---|---|
/health/liveness | Is the process broken beyond recovery? | Kubernetes restarts the pod |
/health/readiness | Can it serve traffic right now? | Kubernetes removes it from the load balancer |
If the database has a brief hiccup, a database-backed liveness probe makes Kubernetes restart every single pod simultaneously — turning a 30-second blip into a full outage with a thundering-herd reconnect. Databases belong in readiness. Liveness should answer only "is this JVM wedged?".
management:
endpoint:
health:
probes:
enabled: true
group:
liveness:
include: livenessState # nothing external
readiness:
include: readinessState,db,inventoryService
show-details: always
@Component("inventoryService")
public class InventoryHealthIndicator implements HealthIndicator {
private final InventoryClient client;
public InventoryHealthIndicator(InventoryClient client) {
this.client = client;
}
@Override
public Health health() {
try {
long start = System.nanoTime();
client.ping();
long millis = (System.nanoTime() - start) / 1_000_000;
return millis < 500
? Health.up().withDetail("latencyMs", millis).build()
: Health.status("DEGRADED").withDetail("latencyMs", millis).build();
} catch (Exception e) {
return Health.down(e).build();
}
}
}
{
"status": "UP",
"components": {
"db": { "status": "UP", "details": { "database": "PostgreSQL", "validationQuery": "isValid()" } },
"diskSpace": { "status": "UP", "details": { "total": 494384795648, "free": 216287453184 } },
"inventoryService": { "status": "UP", "details": { "latencyMs": 34 } },
"livenessState": { "status": "UP" },
"readinessState": { "status": "UP" }
}
}
Metrics with Micrometer
Micrometer is a facade over metric backends — you instrument once and export to Prometheus, Datadog, CloudWatch or anything else by swapping a dependency.
@Service
public class BookService {
private final Counter booksCreated;
private final Timer searchTimer;
private final DistributionSummary orderValue;
public BookService(MeterRegistry registry, BookRepository repository) {
this.booksCreated = Counter.builder("bookstore.books.created")
.description("Books created since startup")
.tag("source", "api")
.register(registry);
this.searchTimer = Timer.builder("bookstore.search.duration")
.publishPercentiles(0.5, 0.95, 0.99)
.publishPercentileHistogram()
.register(registry);
this.orderValue = DistributionSummary.builder("bookstore.order.value")
.baseUnit("EUR")
.register(registry);
// a gauge observes something continuously — no manual updates
Gauge.builder("bookstore.books.total", repository, JpaRepository::count)
.description("Books currently in the catalogue")
.register(registry);
}
public Book create(CreateBookCommand command) {
Book book = repository.save(Book.from(command));
booksCreated.increment();
return book;
}
public Page<Book> search(BookSearchFilter filter, Pageable pageable) {
return searchTimer.record(() -> repository.findAll(toSpec(filter), pageable));
}
}
| Instrument | Use for | Example |
|---|---|---|
Counter | Things that only increase | orders placed, errors |
Timer | Duration + count together | request latency |
Gauge | A value that goes up and down | queue depth, cache size |
DistributionSummary | Non-time distributions | payload size, order value |
LongTaskTimer | Work still in progress | a running import job |
.tag("userId", userId) or .tag("bookId", id) creates one time
series per distinct value. A million users means a million series, and you will take down
your metrics backend before you notice. Tags must have low, bounded cardinality:
status, method, outcome, region.
@Observed — one annotation for metrics and traces
@Configuration
public class ObservationConfig {
@Bean
ObservedAspect observedAspect(ObservationRegistry registry) {
return new ObservedAspect(registry);
}
}
@Service
public class PricingService {
@Observed(name = "pricing.calculate",
contextualName = "calculate-order-total",
lowCardinalityKeyValues = {"tier", "standard"})
public Money calculate(Order order) {
// produces a timer AND a trace span from one annotation
}
}
Distributed tracing
<dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-tracing-bridge-otel</artifactId> </dependency> <dependency> <groupId>io.opentelemetry</groupId> <artifactId>opentelemetry-exporter-otlp</artifactId> </dependency>
management:
tracing:
sampling:
probability: 0.1 # 10% in production; 1.0 in dev
otlp:
tracing:
endpoint: http://otel-collector:4318/v1/traces
logging:
pattern:
level: "%5p [${spring.application.name},%X{traceId:-},%X{spanId:-}]"
Trace and span ids are placed in the logging MDC automatically, so every log line can be
correlated with a trace — and with the traceId you returned in the
ProblemDetail back in chapter 7.
Structured logging
Boot 3.4 can emit JSON logs natively — no Logback encoder dependency required.
logging:
structured:
format:
console: ecs # or: logstash, gelf
level:
root: INFO
com.bitsnippets.bookstore: INFO
{
"@timestamp": "2026-08-17T10:24:31.882Z",
"log.level": "INFO",
"service.name": "bookstore",
"trace.id": "3f2a1c9e5b7d4a10",
"span.id": "a1b2c3d4",
"message": "Book created id=1042",
"log.logger": "com.bitsnippets.bookstore.catalog.BookService"
}
Passwords, tokens, full card numbers, national identifiers, session cookies, and complete request bodies on user endpoints. Logs are copied into aggregation systems that many more people can read than your database. When in doubt, log an identifier and look the record up.
What to actually alert on
| Metric | Alert when | Means |
|---|---|---|
http.server.requests 5xx rate | > 1% for 5 min | Something is broken |
http.server.requests p99 | > 2× baseline | Degradation before it becomes an outage |
hikaricp.connections.pending | > 0 for 1 min | Pool exhausted — slow queries or a leak |
jvm.memory.used / max (old gen) | > 85% sustained | Heading for OOM |
jvm.gc.pause | p99 > 1s | GC pressure |
application.ready.time | > 2× previous release | A startup regression |
| Custom business counter | drops to zero | Often the earliest real signal |
That last row matters more than people expect: "orders placed per minute went to zero" is usually detected before any infrastructure metric moves.
A custom actuator endpoint
@Component
@Endpoint(id = "cachestats")
public class CacheStatsEndpoint {
private final CacheManager cacheManager;
@ReadOperation
public Map<String, Object> stats() {
return cacheManager.getCacheNames().stream()
.collect(Collectors.toMap(name -> name, this::statsFor));
}
@WriteOperation
public void evict(@Selector String cacheName) {
Optional.ofNullable(cacheManager.getCache(cacheName)).ifPresent(Cache::clear);
}
}
Available at GET /actuator/cachestats and
POST /actuator/cachestats/{cacheName}, once added to the exposure list.
Checklist
- Actuator on a separate port, and role-protected.
includelists explicit endpoints — never"*"in production.- Liveness has no external dependencies; readiness has the ones you cannot serve without.
- Prometheus scraping, with
applicationandenvtags. - No high-cardinality metric tags.
- Trace ids in logs and in error responses.
- Alerts on error rate, latency, pool saturation and at least one business metric.
- Heap dump endpoint disabled outside development.
Why should the database not be part of the liveness probe?
Liveness failure means "restart me". Restarting will not fix a database that is down — it just adds a mass reconnect storm on top of the original problem. Dependencies belong in readiness, which removes the instance from the load balancer until it can serve again.