Correlation Analysis

Comprehensive guide to correlation analysis for production observability and monitoring systems.

Correlation Analysis is the process of identifying, aligning, and interpreting signals across multiple observability sources—metrics, logs, traces, and events—to understand why a system behaves as it does. It matters when symptoms appear in one service, but the root cause lies in another, or when a single alert fails to explain a complex incident. It is essential during incident response, root-cause analysis, and proactive system health monitoring.

Identifying Correlated Signals

Correlation analysis begins with finding signals that move together over time. The key is to align data from different sources by a common time axis and shared context, such as a request ID, transaction ID, or a service-specific identifier.

The most common way to correlate metrics and logs is by embedding a shared identifier in the data stream. A trace ID from a distributed trace is typically propagated through all services via HTTP headers or message metadata. Logs in each service include the trace ID, enabling aggregation across services.

For example, when a request arrives at a gateway service, it is assigned a trace_id:

{
  "trace_id": "a1b2c3d4-e5f6-7890-g1h2-i3j4k5l6m7n8",
  "request_id": "r001",
  "timestamp": "2024-03-15T10:23:45.123Z"
}

All downstream services append this trace_id to their logs and metrics. A database service logs a query with the same trace_id, and a metrics system records a db.query.duration metric with the same trace_id as a tag.

To correlate metrics and logs, you extract all log entries and metric samples that share a trace_id and align them by time.

SELECT
  l.timestamp,
  l.service,
  l.message,
  m.value,
  m.metric_name,
  m.tags
FROM logs l
JOIN metrics m ON l.trace_id = m.trace_id
WHERE l.timestamp >= '2024-03-15T10:23:00Z'
  AND l.timestamp < '2024-03-15T10:24:00Z'
  AND m.timestamp >= '2024-03-15T10:23:00Z'
  AND m.timestamp < '2024-03-15T10:24:00Z'
ORDER BY l.timestamp ASC;

This query yields a timeline of events across services, showing when a request was processed, when a database call occurred, and how long it took.

Aligning Data Across Sources

Time alignment is critical. Data from different sources often arrive at different sampling rates and with different clock drifts. Without alignment, a latency spike in a service might appear unrelated to a database delay, even when they are tightly coupled.

The core technique is time-windowed joining. Each signal is projected into a time window, and overlapping windows are used to find correlated events.

For instance, a latency alert in a service may trigger when avg(response_time) > 2s over 5 minutes. To investigate, you query for all logs and metrics during the alert window, then group all events by trace_id.

{
  "alert_id": "latency-2024-03-15-10-23",
  "start_time": "2024-03-15T10:23:00Z",
  "end_time": "2024-03-15T10:28:00Z",
  "triggered_by": "service-gateway",
  "metric": "response_time",
  "threshold": 2.0,
  "value": 2.34
}

You then run a query that pulls all logs from start_time to end_time and all metric samples from the same window, joining them on trace_id.

A common mistake is assuming that time in logs and metrics is synchronized. But logs may be generated at 10:23:45.123Z, while metrics are batched every 30 seconds and recorded at 10:23:30.000Z, 10:24:00.000Z, etc. The mismatch leads to time drift errors.

To correct for this, use time interpolation. When a metric sample is at 10:23:30.000Z but a log entry is at 10:23:45.123Z, you interpolate the metric value to the log timestamp:

def interpolate_metric(metric_samples, target_time):
    # metric_samples: list of (timestamp, value, tags)
    # target_time: datetime
    # Return interpolated value at target_time
    # Find the two nearest samples
    prev = None
    next = None
    for sample in metric_samples:
        if sample['timestamp'] <= target_time:
            prev = sample
        else:
            next = sample
            break
    if not prev:
        return next['value']
    if not next:
        return prev['value']
    
    t0, v0 = prev['timestamp'], prev['value']
    t1, v1 = next['timestamp'], next['value']
    ratio = (target_time - t0) / (t1 - t0)
    return v0 + ratio * (v1 - v0)

This ensures that metric values are aligned with log timestamps, reducing false correlations.

Discovering Root Causes Through Pattern Matching

Once aligned, signals are analyzed for patterns that suggest causality. The most common patterns are:

To detect these, use cross-service correlation matrices. Each row represents a service, each column a metric or log event. A cell contains the correlation coefficient between the service’s metric and another service’s signal.

For example, you might compute the correlation between gateway.response_time and user-service.db.query.duration:


def correlation(series_a, series_b):
    # series_a and series_b are lists of (timestamp, value)
    # both series assumed to be aligned by time
    # return Pearson correlation coefficient
    # assume series are padded with nulls for missing timestamps
    # use only pairs where both series have non-null values
    # return float between -1 and 1
    # 1: perfect positive correlation, -1: perfect negative
    # use scipy.stats.pearsonr or equivalent
    return pearsonr(
        [a[1] for a in series_a if a[1] is not None],
        [b[1] for b in series_b if b[1] is not None]
    )

A correlation coefficient above 0.7 between user-service.db.query.duration and gateway.response_time suggests that user service database delays are a primary driver of gateway latency.

A common failure mode is misaligned windows. If you compute correlation over a 10-minute window but the signal of interest has a 30-second lag, the correlation will appear weaker or even negative.

To address this, use lagged correlation:

def lagged_correlation(series_a, series_b, lag_seconds):
    # Shift series_b by lag_seconds
    # Compute correlation between series_a and shifted series_b
    # Return correlation coefficient
    shifted_b = shift(series_b, lag_seconds)
    return correlation(series_a, shifted_b)

You can then compute the correlation for multiple lags:

{
  "lag": -30,
  "correlation": 0.62
},
{
  "lag": 0,
  "correlation": 0.41
},
{
  "lag": 30,
  "correlation": 0.75
},
{
  "lag": 60,
  "correlation": 0.58
}

The peak correlation at lag +30 seconds indicates that user-service.db.query.duration leads gateway.response_time by 30 seconds—suggesting that database delays in the user service cause gateway delays with a 30-second delay.

Detecting and Diagnosing Anomalies

Anomalies are signals that deviate significantly from the norm. Correlation analysis helps distinguish between system-wide anomalies and localized anomalies.

A system-wide anomaly affects multiple services simultaneously. For example, a sudden increase in error rates across all services may indicate a network partition or a database outage.

A localized anomaly affects only one or a few services. For instance, a spike in payment-service.cpu.usage with no corresponding change in other metrics may point to a resource bottleneck in that service.

To detect anomalies, use z-score detection:

def detect_anomalies(series, window_minutes=10, threshold=2.0):
    # series: list of (timestamp, value)
    # window_minutes: size of rolling window for mean and std
    # threshold: z-score threshold for anomaly
    # return list of (timestamp, value, z_score, is_anomaly)
    window_size = window_minutes * 60  # seconds
    results = []
    for i, point in enumerate(series):
        start_time = point['timestamp'] - timedelta(seconds=window_size)
        window_data = [p for p in series if p['timestamp'] >= start_time]
        mean = sum(p['value'] for p in window_data) / len(window_data)
        std = (sum((p['value'] - mean) ** 2 for p in window_data) / len(window_data)) ** 0.5
        z_score = (point['value'] - mean) / std
        is_anomaly = z_score > threshold
        results.append({
            'timestamp': point['timestamp'],
            'value': point['value'],
            'z_score': z_score,
            'is_anomaly': is_anomaly
        })
    return results

When an anomaly is detected, correlate it with other signals to diagnose its cause.

For example, a high z_score in payment-service.cpu.usage correlates with a rise in payment-service.db.query.duration and a spike in message-queue.latency. This suggests that CPU pressure in the payment service is caused by long-running queries, which in turn are due to a backlog in the message queue.

Resolving Confusion and Silent Failures

Several silent failures undermine correlation analysis:

  {
    "timestamp": "2024-03-15T10:23:45.123Z"
  }

vs.

  {
    "timestamp": 1710545025.123
  }

The join condition l.timestamp = m.timestamp fails because one is a string, the other a float.

To prevent these, enforce a correlation contract:

Use a correlation validation query to check for common failures:

SELECT
  COUNT(*) as total_logs,
  COUNT(trace_id) as logs_with_trace_id,
  COUNT(DISTINCT trace_id) as unique_traces,
  COUNT(DISTINCT service) as services_with_logs,
  AVG(duration) as avg_log_duration,
  MIN(timestamp) as earliest_log,
  MAX(timestamp) as latest_log
FROM logs
WHERE timestamp BETWEEN '2024-03-15T10:23:00Z' AND '2024-03-15T10:24:00Z'
  AND service = 'gateway';

SELECT
  service,
  COUNT(*) as metric_samples,
  AVG(value) as avg_value,
  MIN(timestamp) as min_time,
  MAX(timestamp) as max_time,
  COUNT(trace_id) as tagged_with_trace_id
FROM metrics
WHERE metric_name = 'response_time'
  AND timestamp BETWEEN '2024-03-15T10:23:00Z' AND '2024-03-15T10:24:00Z'
GROUP BY service;

This validation helps catch missing trace IDs, misaligned timestamps, and inconsistent tagging before they cause confusion.

Automating Correlation Analysis

Correlation analysis is not a one-off activity. To scale, automate it.

Use correlation pipelines that run on a schedule or in response to alerts. A typical pipeline:

  1. Trigger on alert or anomaly detection.
  2. Extract trace_id from the alert.
  3. Query logs and metrics for all data in the alert window.
  4. Compute cross-service correlation matrices.
  5. Identify leading and lagging signals.
  6. Generate a summary report.

The report includes:

This enables teams to move from reactive incident response to proactive system understanding.

This page was rewritten on 17 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.