Observability: Seeing Inside the System

Observability: Seeing Inside the System in Java: In a monolith, debugging means reading one log file.

Concept Explanation

In a monolith, debugging means reading one log file. Across twelve services, a single user request touches five of them, and none of the logs alone tells the story.

Observability rests on three pillars:

  • Logs — what happened, in detail.
  • Metrics — how much and how fast, aggregated.
  • Traces — the path of one request across every service.

Structured Logging

private static final Logger log = LoggerFactory.getLogger(OrderService.class);

log.info("Order placed id={} total={} customer={}",
         order.getId(), order.getTotal(), order.getCustomerId());

Use placeholders, not concatenation — the string is only built if that level is enabled.

Correlation ids are what make distributed logs usable. Put one in the MDC and every log line in the request carries it:

MDC.put("traceId", traceId);
try {
    // all logging inside here is tagged
} finally {
    MDC.clear();          // essential: threads are pooled and reused
}

Now grep traceId=abc123 across all services reconstructs the entire request.


Metrics with Actuator

management.endpoints.web.exposure.include=health,info,metrics,prometheus
management.endpoint.health.show-details=when-authorized

Custom metrics:

@Service
public class OrderService {

    private final Counter placed;
    private final Timer checkout;

    public OrderService(MeterRegistry registry) {
        this.placed   = registry.counter("orders.placed");
        this.checkout = registry.timer("orders.checkout.duration");
    }

    public Order place(OrderRequest req) {
        return checkout.record(() -> {
            Order o = doPlace(req);
            placed.increment();
            return o;
        });
    }
}

Prometheus scrapes /actuator/prometheus; Grafana draws the dashboards.


Health Checks

@Component
public class QueueHealth implements HealthIndicator {

    @Override
    public Health health() {
        int depth = queue.depth();
        return depth < 1000
             ? Health.up().withDetail("depth", depth).build()
             : Health.down().withDetail("depth", depth).build();
    }
}

Kubernetes probes this endpoint to decide whether to route traffic to the instance or restart it.


Distributed Tracing

Micrometer Tracing propagates a trace id across service boundaries automatically. In Zipkin or Jaeger you then see one request as a waterfall:

gateway        ├──────────────────────────────┤ 240ms
  order-svc      ├────────────────────────┤     210ms
    inventory      ├──────┤                      45ms
    pricing            ├──────────────┤         120ms   <- the bottleneck

This turns "the checkout feels slow" into "pricing takes 120ms" in seconds.


Common Mistakes

  1. Logging secrets: Passwords and tokens in log aggregators are a breach waiting to be found.
  2. Logging everything at INFO: Volume becomes noise, costs money, and hides the real signal.
  3. No correlation id: Distributed debugging without one is guesswork.
  4. Forgetting MDC.clear(): Pooled threads leak the previous request's id into the next one.
  5. Alerting on CPU instead of user impact: Alert on error rate and latency — the things users actually feel.

Best Practices

  • Log levels with meaning: ERROR needs a human; WARN is suspicious; INFO is a business event; DEBUG is for development.
  • One correlation id per request, generated at the gateway and propagated everywhere.
  • Track the four golden signals: latency, traffic, errors, saturation.
  • Separate liveness from readiness: "is it alive" and "can it serve traffic" are different questions.

Practice Exercises

  1. The Correlation Id: Add an MDC trace id in a filter and confirm every log line in the request carries it.
  2. The Custom Metric: Register a timer around a slow method and read it from /actuator/metrics.
  3. The Health Indicator: Write a health indicator that reports DOWN when a dependency is unreachable, and watch /actuator/health change.