Observability-Driven Root Cause Analysis: Beyond the "Restart-and-Apologize" Playbook

    When an incident occurs, "We restarted the service and monitoring looks normal" is often treated as a resolution. This article argues that such responses address surface symptoms rather than the root cause. It explains how observability turns "whether to trust the explanation" into "what the evidence shows," covering metrics, logs, and traces; foundations for reliable evidence; structured logging and context propagation; alert layering; root-cause closure; measurement; and common implementation pitfalls. It also describes how Baidu AI Cloud capabilities can support these practices.

    1. From a “Routine Apology” to an Engineering Metaphor

    During an incident, the most typical response is often something like:

    “We restarted the service, it is recovered, and monitoring looks normal. Let us observe for a while.”

    This kind of statement feels uncomfortable not because it is impolite, but because it avoids the only meaningful question: Why did the incident happen, and what guarantees that it will not happen again?

    This is structurally similar to a child hearing a parent say: “Mom was wrong. It won’t happen next time.” The child’s response is often praised as “clear-headed” because it challenges a distinction that adults often prefer to avoid: an apology is a matter of attitude, while root cause is a matter of fact. One cannot substitute for the other.

    In an engineering context, this substitution appears as three common anti-patterns:

    Anti-pattern Surface action Hidden fact
    Restart-style handling Restart instances or roll back to the previous version The trigger condition still exists; it has simply not been triggered again yet
    Scaling-style handling Add machines or raise quotas Resources are not the bottleneck; lock contention or slow queries may be the real issue
    Cleanup-style handling Delete logs, disable alerts, or lower log levels Evidence is destroyed, and the next time an incident occurs, the team may not even be able to answer “what happened”

    These approaches have one thing in common: they optimize for “can we get through this incident,” not “will the incident happen again.”

    The value of observability is precisely to shift the discussion from “should we believe this explanation” to “what does the evidence show.”

    2. The Three Pillars of an Evidence Chain: Metrics, Logs, and Traces

    A mature observability system is usually built from three types of data. They are not redundant; they answer different levels of the question:

    • Metrics: Low cost and highly aggregated. They answer questions such as “Is there an anomaly, and in which dimension?” They are suitable for triggering alerts and observing trends, but because they are aggregated, they cannot answer “which specific request caused the problem.”

    • Logs: High detail and traceable. They answer “what specifically happened at that time.” Their limitation is that they do not naturally support time-series aggregation, so their usefulness depends on structure and indexing quality.

    • Traces: Cross-service and cross-process. They answer “where was time spent, and which hop failed?” They are the key mechanism for translating “users complain that the service is slow” into “one database call in the inventory service took 2.3 seconds.”

    A repeatedly verified lesson is that no single data source alone can complete root cause localization. Metrics may show that the error rate began rising at 10:03. Traces may show that errors are concentrated on the third hop when calling the payment service. Logs may show that the exception on that hop was “connection pool wait timeout.” If any one of these is missing, the conclusion remains at the level of speculation.

    3. Foundations: Making Data Admissible as Evidence

    3.1 Unified Time Baseline

    Clocks across all nodes must be aligned to a unified time source. Otherwise, cross-service troubleshooting may produce absurd conclusions, such as “the upstream request happened before the downstream service processed it.”

    The practical approach is to deploy a unified clock synchronization mechanism and to use sufficiently wide evaluation windows in alert rules, such as 3 minutes or more, to avoid false positives caused by clock drift.

    3.2 Structured Logs and Fixed Fields

    The first requirement for logs is searchability, not readability. Plain-text logs become almost impossible to navigate at the scale of hundreds of thousands of lines. Therefore, logs should be emitted in a structured format with stable core fields:

    1. import json, logging, os
    2. class JsonFormatter(logging.Formatter):
    3. """Render each log entry as a single-line JSON object with stable fields."""
    4. def format(self, record):
    5. return json.dumps({
    6. "ts": record.created, # Unified timestamp with millisecond precision
    7. "level": record.levelname,
    8. "service": os.getenv("APP_NAME", "unknown"), # Service identifier
    9. "env": os.getenv("APP_ENV", "dev"),
    10. "version": os.getenv("BUILD_VERSION", "n/a"),
    11. "trace_id": getattr(record, "trace_id", None),
    12. "span_id": getattr(record, "span_id", None),
    13. "event": record.getMessage(), # Event name: use a fixed enum rather than free text
    14. "detail": getattr(record, "detail", {}),
    15. }, ensure_ascii=False)

    Two easily overlooked conventions:

    1. The event field should be enumerable. Event names such as “order creation succeeded” or “inventory deduction failed” should be reduced to a finite set. Otherwise, log searching degrades into full-text search, and aggregation becomes difficult.

    2. Sensitive fields must be masked. User identifiers, phone numbers, addresses, and similar data should be hashed or masked before being written to storage. Even when logs are centrally stored, they remain data assets and are subject to equivalent security requirements.

    3.2.1 The High-Cardinality Label Trap

    The cardinality of labels directly determines the cost and usability of a monitoring system. A common mistake is using user_id as a metric label. Values in the millions will cause time-series explosion, degrading both storage and queries.

    A simple rule of thumb: any dimension with more than 10,000 possible values should only appear in logs, not in metric labels. Metric labels should remain limited to bounded dimensions such as service, env, status_code, and api.

    3.3 Cross-Process Context Propagation

    This is the most fragile part of asynchronous architectures. There are three common breakpoints:

    • Thread pool or coroutine switches: When a task is submitted to a worker thread, the context from the original thread is lost.

    • Message queue decoupling: The producer and consumer do not share process memory, so the context must be carried with the message payload.

    • Retries and looped calls: The same request ID may be reused, making it impossible to distinguish which attempt is which.

    The correct approach is to pass the request identifier explicitly as a parameter through the call chain, rather than relying on implicit thread-local variables:

    1. import contextvars, uuid, logging
    2. # Created when the request enters, then explicitly carried by all downstream calls.
    3. _trace_ctx = contextvars.ContextVar("trace_ctx", default={})
    4. def new_trace(ctx=None):
    5. ctx = ctx or {}
    6. ctx.setdefault("trace_id", uuid.uuid4().hex)
    7. return ctx
    8. def call_downstream(url, ctx):
    9. headers = {
    10. # Use a standard tracing header; do not bind to a vendor-specific format.
    11. "traceparent": f"00-{ctx['trace_id']}-{uuid.uuid4().hex[:16]}-01",
    12. }
    13. return http_get(url, headers=headers, timeout=1.0)
    14. def handle_async_task(payload):
    15. # Async tasks must restore context from the message payload rather than create a new one.
    16. ctx = new_trace(payload.get("trace_ctx"))
    17. logging.info("task start", extra={"trace_id": ctx["trace_id"]})

    For sampling strategy, a layered combination is recommended: retain 100% of error requests, retain 100% of slow requests that exceed the P99 threshold, and sample normal requests at a ratio such as 1%. This controls cost while ensuring that evidence is always available when something goes wrong.

    3.4 Metric Design: RED and USE Perspectives

    • RED, for online services: Rate, Errors, Duration.
    • USE, for resources and infrastructure: Utilization, Saturation, Errors.

    For duration metrics, do not rely on averages. Collect P50, P95, and P99 percentiles instead. An average can dilute the experience of the 1% of users who wait 10 seconds into a claim that “the system is generally healthy,” while user complaints often come precisely from that long tail.

    4. Alert Layering: From Noise to Signal

    The most common failure in alerting is not missing an alert, but letting noise drown out the signal. This leads to alert fatigue and eventually to the cleanup-style anti-pattern described earlier.

    An effective approach is to distinguish between two types of alerts:

    • Symptom alerts: User-perceivable phenomena, such as a rising API error rate or a higher order failure rate. These alerts should directly reach the on-call responder and have a high severity level.

    • Cause alerts: Resource or infrastructure anomalies, such as sustained high CPU usage or a connection pool approaching its limit. These alerts are used to support diagnosis and should have lower severity, be aggregated, and not directly wake up the on-call responder.

    A practical alert rule example:

    1. rules:
    2. - alert: HighErrorRate
    3. expr: |
    4. sum(rate(http_requests_total{status=~"5.."}[5m]))
    5. / sum(rate(http_requests_total[5m])) > 0.01
    6. for: 3m # Trigger only after persisting for 3 minutes to filter transient spikes
    7. labels:
    8. severity: P1
    9. category: symptom # Symptom alert: notify on-call directly
    10. annotations:
    11. impact: "5xx ratio remains above 1%, affecting the order flow"
    12. runbook: "Investigation order: ingress -> service instances -> downstream dependencies -> infrastructure"

    Combining for windows, alert grouping, inhibition rules, and silence windows for maintenance periods can significantly reduce noise. Alert rules should also include a runbook link, so the person receiving the alert does not need to spend time figuring out where to start investigating.

    5. Closing the Loop: From Apology to Remediation List

    If root cause analysis stops at “a parameter was configured incorrectly,” the postmortem has little value. A widely used method is the 5 Whys approach. The point is not how many questions are asked, but that each answer must be verifiable:

    Symptom: API P99 latency rose to 8 seconds.
    Why? Slow database queries rose to 60% of queries.
    Why were they slow? A composite index was missing, causing full table scans.
    Why was the index missing? The table’s DDL change was not included in the review process.
    Why was it not included? The change management standard covered application code but not schemas.
    Systemic root cause: the scope of change control was incompletely defined.

    Only at this point can effective remediation actions be formed: expand the scope of change control, establish routine inspection for slow queries, and add automated schema-change checks in CI.

    A qualified incident postmortem document should consistently include six sections:

    1. Timeline: Discovery time, response time, and recovery time, precise to the minute and reconstructed from monitoring data rather than memory.

    2. Impact: Affected APIs, user scale, and error distribution.

    3. Root cause: Distinguish the trigger from the underlying root cause.

    4. Why it was not detected earlier: Whether monitoring has blind spots. This is often the most valuable question.

    5. Remediation actions: Each action should have an owner and a deadline, along with the metric used to verify completion.

    6. Verification conclusion: What data proves that the remediation was effective.

    6. Measurement: Using Data to Judge Whether the System Improved

    If it cannot be measured, it cannot be improved. At minimum, track the following four metrics:

    • MTTD, mean time to detect: Reflects monitoring coverage.

    • MTTR, mean time to recover: Reflects response efficiency and runbook quality.

    • Incident recurrence rate: The percentage of incidents caused by the same root cause within 90 days. This directly tests whether remediation was effective.

    • Alert effectiveness rate: The percentage of alerts that were handled and confirmed to represent real problems. This reflects the level of noise.

    7. Common Implementation Pitfalls

    • Deploying tools without changing processes: Data is collected, but no one owns SLO definition or runbook maintenance, so the data eventually becomes dormant.

    • No log-level policy: Printing everything at INFO level harms both cost and searchability. Log levels should be configured by environment.

    • Tracing instrumentation invades business code: Instrumentation statements scattered throughout business logic become difficult to maintain. They should be consolidated through a unified observability wrapper or library.

    • Alert metrics lack business semantics: Monitoring only CPU and memory, while failing to monitor business golden signals such as “order success rate” or “payment callback success rate.”

    Conclusion

    Returning to the original metaphor: people dislike the parent’s routine apology because it substitutes attitude for fact. In the same way, “it recovered after a restart” is unsettling for the same reason.

    Engineering maturity is not demonstrated by the absence of incidents. It is demonstrated by the ability to clearly explain each incident and concretely fix it.

    On Baidu AI Cloud, these practices can be supported by a combination of general cloud capabilities: log services can handle centralized log collection, search, and long-term archiving; monitoring and alerting capabilities can support metric dashboards and layered alert policies; container platforms can support standardized service deployment and version rollback; message queues can decouple asynchronous chains; and cold data can be moved to object storage to control long-term costs.

    Tools determine whether data can be collected. What ultimately determines effectiveness is whether the team is willing to keep asking the least comfortable question: This time, why exactly did it happen?