Learning center

Two metrics rose together. Does one cause the other?

When database CPU and app latency rise together, the database may slow the app, the app may add database work, or traffic may drive both. Three readings separate them: database CPU per request, the rate of first attempts as distinct from retries, and which metric moved first at the finest resolution you have. Changing one side alone and watching the other confirms the answer.

The symptom and three explanations#

The example is illustrative. A fictional orders-api service runs on a PostgreSQL instance. At 14:30 UTC the one-minute dashboard showed database CPU rising from about 50% and the service's mean latency rising with it, both in the same minute. The database team and the service team each pointed at the other.

  • The database slows the application. Each query got more expensive, from a plan change, a table that outgrew its index or a competing job on the database. Queries queue, and every request waits longer.
  • The application adds database work. A downstream call inside the service got slow, some requests ran past the clients' timeout, and the clients retried. Every retry runs the request's queries again.
  • More traffic drives both. More requests arrived, each costing the database the same, and the extra load raised both CPU and queueing.

All three predict the graph on the dashboard. Choose the observation where explanations disagree

What each explanation predicts#

ObservationDatabase slows the appApp adds database workMore traffic drives both
Database CPU and latency, one-minute graphboth riseboth riseboth rise
First attempts per secondflatflatrise
Requests per second, retries includedflatriserise
Database CPU per 1,000 requestsrisesflatflat
Which moved first, one-second resolutionCPU and latency togetherlatency, then requests and CPU one client timeout laterrequests, CPU and latency together

The one-minute graph is the observation everyone had, and it separates nothing. Per-request CPU separates the database explanation from the other two. It cannot separate retries from real traffic, because a retry is a request and costs what a request costs. Two readings split those two: whether first attempts rose, and whether latency rose before the requests did.

Ratios like these show association within a window. The test of causation is to change one side alone. If making the expensive query cheaper brings latency down, the database was the cause. If removing the slow downstream call brings database CPU down, the application was.

The lab: three causal structures#

The script simulates an hour at one-second resolution, from 14:00 to 15:00, with a change at 14:30. Database CPU is proportional to requests times the cost per request, and latency includes a queueing term that grows with CPU utilization. In the db world the cost per request rises by half. In the app world a downstream call adds 2.2 s to 20% of requests, and clients retry those after a 2-second timeout. In the load world first attempts rise from 200 to 300 per second. Every reading gets 3% noise. It needs Python 3.8 or later.

import random, statistics, sys

T0, END, TIMEOUT = 1800, 3600, 2      # 14:00 to 15:00, the change at 14:30:00; clients retry after a 2 s timeout

def simulate(world, rng):
    rows = []
    for t in range(END):
        users = 300 if (world == "load" and t >= T0) else 200      # first attempts per second
        retries = 0.2 * 200 if (world == "app" and t >= T0 + TIMEOUT) else 0
        requests = users + retries                                 # what the server counts
        cost = 0.375 if (world == "db" and t >= T0) else 0.25      # DB CPU % per request
        cpu = min(95.0, requests * cost)
        u = cpu / 100
        latency = 40 + 20 * u / (1 - u)                            # ms, queueing in the database
        if world == "app" and t >= T0:
            latency += 0.2 * 2200                                  # a slow downstream call, 20% of requests
        n = lambda: rng.uniform(0.97, 1.03)
        rows.append({"first attempts": users * n(), "requests": requests * n(),
                     "db cpu %": cpu * n(), "latency ms": latency * n()})
    for r in rows:
        r["db cpu per 1k req"] = 1000 * r["db cpu %"] / r["requests"]
    return rows

def onset(rows, key, step):
    """First bin of `step` seconds whose mean is 10% above the pre-change mean."""
    base = statistics.mean(r[key] for r in rows[:T0])
    for start in range(0, END, step):
        if statistics.mean(r[key] for r in rows[start:start + step]) > 1.1 * base:
            return start
    return None

if len(sys.argv) not in (2, 3) or sys.argv[1] not in ("db", "app", "load"):
    sys.exit("usage: python3 common_cause.py db|app|load [seed]")
world = sys.argv[1]
rows = simulate(world, random.Random(int(sys.argv[2]) if len(sys.argv) > 2 else 2))
print(f"world={world}             after/before  onset (1 s bins)  onset (1 min bins)")
for key in rows[0]:
    before = statistics.mean(r[key] for r in rows[T0 - 600:T0])
    after = statistics.mean(r[key] for r in rows[T0 + 60:T0 + 660])
    o1, o60 = onset(rows, key, 1), onset(rows, key, 60)
    fmt = lambda o: "-" if o is None else f"14:{o // 60:02d}:{o % 60:02d}"
    print(f"  {key:18s} {after / before:10.2f} {fmt(o1):>17s} {fmt(o60):>19s}")

Save it as common_cause.py. Before running it, fill in the table above with your predictions for each world: which ratios move, and which onset comes first at one second. The prediction is that per-request CPU moves only in db, first attempts only in load, and that only app shows an onset gap of about the client timeout at one second and none at one minute.

for w in db app load; do python3 common_cause.py "$w"; done

Python 3.11 printed:

world=db             after/before  onset (1 s bins)  onset (1 min bins)
  first attempts           1.00                 -                   -
  requests                 1.00                 -                   -
  db cpu %                 1.50          14:30:00            14:30:00
  latency ms               1.66          14:30:00            14:30:00
  db cpu per 1k req        1.50          14:30:00            14:30:00
world=app             after/before  onset (1 s bins)  onset (1 min bins)
  first attempts           1.00                 -                   -
  requests                 1.20          14:30:02            14:30:00
  db cpu %                 1.20          14:30:02            14:30:00
  latency ms               8.48          14:30:00            14:30:00
  db cpu per 1k req        1.00                 -                   -
world=load             after/before  onset (1 s bins)  onset (1 min bins)
  first attempts           1.50          14:30:00            14:30:00
  requests                 1.50          14:30:00            14:30:00
  db cpu %                 1.50          14:30:00            14:30:00
  latency ms               1.66          14:30:00            14:30:00
  db cpu per 1k req        1.00                 -                   -

The db and load worlds produced the same rise in CPU and latency, 1.50 and 1.66, and were told apart by two columns: per-request CPU rose only in db, first attempts only in load. The app world had flat per-request CPU, like load, and would have been read as a traffic increase from the request count alone. Its first attempts stayed flat, and at one second its latency led requests and CPU by two seconds, the client timeout. At one minute, every onset in every world landed on 14:30:00.

The prediction would have failed if per-request CPU had moved in app or load, or if the one-second onsets in app had matched. Pass a seed as the second argument to repeat it; the onsets do not move, because the changes are steps much larger than the noise. Set TIMEOUT to 20 and the app gap grows to 20 seconds, still inside the one-minute bin.

Read it on a real system#

Per-request CPU needs the database CPU and your service's request rate over the same window. With both in Prometheus, divide one by the other; the CPU metric's name depends on the exporter, so db_cpu_percent below stands for yours. rate

1000 * avg(db_cpu_percent{instance="orders-db"})
  / sum(rate(http_server_request_duration_seconds_count{service="orders-api"}[1m]))

Inside PostgreSQL, pg_stat_statements keeps cumulative calls and total_exec_time per statement. Read it twice a minute apart and subtract: more calls at the same time per call is more work arriving, and the same calls at more time per call is each query getting dearer. pg_stat_statements

SELECT queryid, calls, total_exec_time, left(query, 60) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

First attempts and retries are often indistinguishable at the server. OpenTelemetry's HTTP client spans record http.request.resend_count on each resent request, so the callers' traces can separate them where callers are instrumented. HTTP spans Retries that rise while first attempts stay flat are the pattern the AWS Builders' Library describes: retries against a system that is timing out because it is overloaded add load and make the overload worse. Timeouts, retries and backoff The same per-request reading, applied to a release that changed how much work each request asks of the database, is in Did our deploy overload a dependency?

For which moved first, use the finest resolution each source has. Metrics from AWS services in CloudWatch are standard resolution, one-minute granularity, by default. RDS Enhanced Monitoring can collect operating system metrics every 1, 5, 10, 15, 30 or 60 seconds. Metric resolution ยท Enhanced Monitoring granularity Request traces and logs carry timestamps to the millisecond, so a histogram of request start times per second is often the sharpest series you have. On Google Cloud, the same comparison runs between Cloud SQL's metrics and the service's. Is the latency in Cloud SQL or in Cloud Run?

The confirming step changes production: turning off the slow downstream call behind a flag, capping client retries, or cancelling the expensive query. Make one change, then read the other metric.

Where the readings mislead#

Real systems have feedback. A slower database makes requests slower, which can make clients retry, which adds database work, so a database cause can produce rising requests a few seconds later. When both per-request CPU and retries rise, look at which rose first and which one a change alone undoes.

A coarse resolution erases the order. Two series that move within the same scrape or the same minute have no readable order, and averaging over that interval cannot recover it. If the finest common resolution is a minute, rely on the ratios and the intervention.

Per-request CPU assumes every request costs about the same. A shift in the mix toward expensive routes raises per-request CPU with no query getting dearer. Split the ratio by route before blaming the database.

Questions#

How do I tell whether database CPU is causing high latency or the other way round?

Divide database CPU by the request rate. If CPU per request rose, each request costs the database more and the database is the likely cause. If it stayed flat, the extra CPU comes from more requests, and you then need to know whether those were new users or retries.

Can correlation between two metrics show causation?

Not by itself. Correlation over the same minutes fits a cause in either direction and a common cause. The order at fine resolution narrows it, and changing one metric's cause alone and watching the other is the test.

Why did request count rise if traffic did not?

Retries, health checks, or a client looping on errors can all add requests without adding users. Compare the request rate with a count of distinct first attempts, such as requests without a retry marker, or user sessions.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading