Cheat SheetsSpring BootActuator & Ops

Actuator & Ops — Cheat Sheet

Spring Boot · 4 topics. Download the PDF or the Instagram carousel and share it.

Cheat Sheet · AiCanCode.org
Actuator & Ops
Spring Boot4 topicsQuick revision reference
1

Spring Boot Actuator

Actuator exposes operational endpoints (/health, /info, /metrics, /env) over HTTP or JMX, enabling real-time insight into a running application.

  • Add spring-boot-starter-actuator; by default only /health and /info are exposed — explicitly include others in management.endpoints.web.exposure.include.
  • Bind actuator to a separate management port (management.server.port) so it is not reachable via the public load balancer.
  • /health/liveness and /health/readiness map to K8s probes — liveness for dead-pod restart, readiness for traffic routing.
  • Never mark liveness DOWN for a slow DB; only mark it DOWN for truly unrecoverable application state (deadlock, corruption).
  • /loggers lets you change log levels at runtime without restart — indispensable during production incident investigation.
  • Pair Actuator with Micrometer (micrometer-registry-prometheus) to expose /actuator/prometheus for Prometheus scraping.
YAML — Actuator Configuration
# application.yml — Actuator configuration
management:
  endpoints:
    web:
      exposure:
        include: "health,info,metrics,loggers,env,prometheus"
        # use "*" to expose everything (not recommended in production)
      base-path: /actuator    # default; change to obscure from public

  endpoint:
    health:
      show-details: when-authorized  # show component details only to authenticated users
      show-components: always

  # Bind management endpoints to a separate internal port
  server:
    port: 8081  # expose actuator on internal port, block 8081 from public LB

# Kubernetes health probes — point to actuator
# spec.containers[].livenessProbe:
#   httpGet:
#     path: /actuator/health/liveness
#     port: 8081
# spec.containers[].readinessProbe:
#   httpGet:
#     path: /actuator/health/readiness
#     port: 8081
2

Health Indicators

Built-in health indicators report the status of DB, Kafka, Redis, and disk; custom indicators implement HealthIndicator and are aggregated into a composite UP/DOWN.

  • Liveness probe: is the JVM alive? Should only check in-process state. Down → pod restarts.
  • Readiness probe: can the pod serve traffic? Should check DB, Redis, Kafka. Down → pod removed from LB.
  • Never include database in liveness — a slow DB query would restart healthy pods.
  • show-details=when_authorized requires the caller to be authenticated; use this in production to hide internals.
  • Custom HealthIndicators are auto-discovered as Spring beans; name the component to control the JSON key.
  • Health status aggregation: one DOWN component makes the composite status DOWN unless explicitly excluded.
Properties + YAML — health endpoint + K8s probes
# application.properties
management.endpoint.health.enabled=true
management.endpoints.web.exposure.include=health,info,metrics,prometheus

# Show full health details (component breakdown)
# Restrict to ADMIN role in production; "when_authorized" uses security
management.endpoint.health.show-details=always
# Or: only show details for authenticated ADMIN users
# management.endpoint.health.show-details=when_authorized

# Kubernetes liveness and readiness probes
management.endpoint.health.probes.enabled=true
management.health.livenessstate.enabled=true
management.health.readinessstate.enabled=true

# /actuator/health/liveness  → {status: "LIVE" or "BROKEN"}
# /actuator/health/readiness → {status: "ACCEPTING_TRAFFIC" or "REFUSING_TRAFFIC"}

# Kubernetes probe config (deployment.yaml)
# livenessProbe:
#   httpGet: { path: /actuator/health/liveness, port: 8080 }
#   initialDelaySeconds: 30
#   periodSeconds: 10
# readinessProbe:
#   httpGet: { path: /actuator/health/readiness, port: 8080 }
#   initialDelaySeconds: 10
#   periodSeconds: 5
3

Metrics with Micrometer

Micrometer provides a vendor-neutral metrics facade; counters, gauges, and timers feed Prometheus, Datadog, or CloudWatch with dimensional time-series data.

  • Micrometer is a vendor-neutral facade — same code instruments Prometheus, Datadog, CloudWatch
  • Counter: monotonically increasing (events); Timer: duration + count; Gauge: current snapshot value
  • Always add tags (dimensions) to slice metrics by status, region, service, method
  • /actuator/prometheus exposes metrics for Prometheus scraping (requires micrometer-registry-prometheus)
  • Spring Boot auto-instruments HTTP, JVM, HikariCP, Kafka — dozens of metrics with zero code
  • management.metrics.tags.application=name adds a global tag to every metric from this service
Spring Boot — Counter, Timer, and Gauge with tags
@Service
@RequiredArgsConstructor
class OrderService {
    private final MeterRegistry registry;

    // Counter — increments on each call
    public Order place(CreateOrderRequest req) {
        Order order = orderRepo.save(new Order(req));
        registry.counter("orders.placed",
            "status",   "success",
            "region",   req.getRegion()
        ).increment();
        return order;
    }

    // Timer — records duration + count
    public PaymentResult charge(Order order) {
        return Timer.builder("payment.latency")
            .tag("provider", "stripe")
            .register(registry)
            .record(() -> stripeClient.charge(order));
    }
}

// Gauge — tracks a current value (register once, reads lambda on each scrape)
@Bean
MeterBinder queueDepthGauge(OrderQueue queue) {
    return registry -> Gauge.builder("orders.queue.depth", queue, OrderQueue::size)
            .description("Current orders waiting to be processed")
            .register(registry);
}
4

Spring Boot Logging

Logback is the default logging framework; configure log levels per package in application.properties and output structured JSON logs for log-aggregation pipelines.

  • Spring Boot auto-configures Logback with INFO/WARN defaults; change levels via logging.level.<package> without any XML
  • logging.group lets you bulk-control levels: logging.level.web=DEBUG toggles all Spring MVC packages at once
  • logback-spring.xml (not logback.xml) allows Spring-specific features like <springProfile> and <springProperty>
  • Logstash encoder emits JSON with automatic MDC field inclusion — essential for ELK, Loki, and Splunk pipelines
  • Always MDC.clear() in a finally block to prevent stale context leaking across thread-pool reuse
  • Micrometer Tracing (Boot 3) auto-populates MDC with traceId/spanId, enabling distributed trace correlation
Properties — log level and file configuration
# application.properties
logging.level.root=WARN
logging.level.com.example=DEBUG
logging.level.org.springframework.web=INFO
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql=TRACE

# Built-in groups
logging.level.web=DEBUG   # covers web-related Spring packages
logging.level.sql=DEBUG   # covers Hibernate SQL packages

# File output
logging.file.name=/var/log/myapp/app.log
logging.logback.rollingpolicy.max-file-size=10MB
logging.logback.rollingpolicy.max-history=7
Learn this free with Aria, your AI tutor → AiCanCode.org/learn/spring-boot