Learning center

Latency spikes every few minutes. Which timer is firing?

Latency that spikes at a regular interval points to something on a timer. Candidates are a scheduled job, garbage collection or compaction, cache entries that expire together, a connection pool retiring connections at their maximum lifetime, and the metrics pipeline itself. Measure the exact period and the phase, meaning where in the wall-clock minute each spike starts and whether every instance spikes at the same moment. A cron job spikes at the same wall-clock second everywhere; a timer that starts with the process spikes at a different moment on each instance; garbage collection changes its period when traffic changes.

The symptom and five explanations#

A fictional quotes-api service runs on two instances, quotes-1 and quotes-2. Since about 09:00 UTC its p99 latency has sat near 80 ms with a jump to 150 ms or more for about half a minute, roughly every five minutes. Request rate is flat. The explanations in the incident channel:

  • A scheduled job. A cron entry or timer runs a report, a backup or a cleanup every five minutes and competes for CPU, disk or the database.
  • Garbage collection or compaction. The runtime's collector, or a storage engine's compaction, runs when enough work has built up.
  • Cache entries expiring together. A cache was filled at one moment with one TTL, so its entries expire together and the misses go to the database at once.
  • The connection pool's maximum lifetime. The pool opened its connections at startup and closes them all when they reach the configured age, so requests wait for new connections.
  • The telemetry. The spike is in how latency is aggregated or scraped, not in what requests experienced.

The same spike pattern on a dashboard fits all five. The period alone rarely decides, because five minutes is a common default for many of them. PostgreSQL's checkpoint_timeout, for instance, defaults to five minutes. PostgreSQL WAL configuration

What each explanation predicts#

ObservationScheduled jobGC or compactionSynced cache expiryPool max lifetimeTelemetry artefact
Perioda schedule value, exactlyvaries with loadthe TTLabout the max lifetimethe scrape or rule interval, or a multiple
Phase against the wall clockfixed, often on the minutenoneset by when the cache was filledset by when the process startedset by scrape times
Same moment on every instanceyes, if every host runs the job or they share what it loadsnoyes for a shared cache, no for a per-process onenodepends on the pipeline
Period when traffic doublesunchangedshorterunchangedunchangedunchanged
Visible in request logs or client timingyesyesyesyesno

The phase rows separate the clock-driven explanations from the process-driven ones, which the period cannot do. The traffic row picks out garbage collection, and the last row picks out the telemetry. Each needs only the latency series split by instance and a few known start times.

The lab: find the period and the phase#

The script makes two hours of p99 samples, one every 10 seconds, for two instances that started at 09:01:40 and 09:03:10. Each sample is noisy (about 80 ms with a standard deviation of 25 ms) and a spike adds about 60 ms for 30 seconds, small enough to be hard to see by eye. In the cron world the spike comes from a */5 * * * * schedule on both hosts; in the timer world it comes from a five-minute timer that starts when the process does. The script finds the period by autocorrelation (how well the series matches itself shifted by each lag) and the phase by folding the series at that period. It needs Python 3.8 or later.

import random, statistics, sys

STEP = 10                 # seconds per sample
HOURS = 2

def series(world, started_at, seed):
    """p99 latency in ms, one sample per 10 s, for one instance from 09:00:00 UTC."""
    rng = random.Random(seed)
    out = []
    for i in range(HOURS * 3600 // STEP):
        t = i * STEP                                   # seconds since 09:00:00
        ms = rng.gauss(80, 25)
        if world == "cron":                            # */5 * * * * on every host
            spike = t % 300 < 30
        else:                                          # timer that starts with the process
            spike = (t - started_at) % 300 < 30
        out.append(ms + (rng.gauss(60, 20) if spike else 0))
    return out

def autocorr(xs, lag):
    m = statistics.fmean(xs)
    num = sum((xs[i] - m) * (xs[i + lag] - m) for i in range(len(xs) - lag))
    return num / sum((x - m) ** 2 for x in xs)

def period_and_phase(xs):
    r = {lag: autocorr(xs, lag) for lag in range(6, 61)}   # lags of 1 to 10 minutes
    best = min(lag for lag in r if r[lag] >= 0.7 * max(r.values()))  # shortest peak, not a multiple
    while best + 1 in r and r[best + 1] > r[best]:
        best += 1
    folded = [statistics.fmean(xs[k::best]) for k in range(best)]
    high = (max(folded) + min(folded)) / 2
    rise = next(k for k in range(best) if folded[k] > high >= folded[k - 1])
    return best * STEP, rise * STEP, r[best]

if len(sys.argv) < 2 or sys.argv[1] not in ("cron", "timer"):
    sys.exit("usage: python3 period.py cron|timer")
world = sys.argv[1]
for name, started_at, seed in (("quotes-1", 100, 1), ("quotes-2", 190, 2)):
    period, phase, rr = period_and_phase(series(world, started_at, seed))
    print(f"{world:5} {name}: started 09:{started_at // 60:02d}:{started_at % 60:02d}  "
          f"period {period} s (r={rr:.2f})  spikes start {phase // 60}:{phase % 60:02d} into each period after 09:00")

Save it as period.py. Write down, before running, whether the two instances will report the same phase in each world. Then:

for w in cron timer; do python3 period.py "$w"; done

Python 3.11 printed:

cron  quotes-1: started 09:01:40  period 300 s (r=0.38)  spikes start 0:00 into each period after 09:00
cron  quotes-2: started 09:03:10  period 300 s (r=0.29)  spikes start 0:00 into each period after 09:00
timer quotes-1: started 09:01:40  period 300 s (r=0.31)  spikes start 1:40 into each period after 09:00
timer quotes-2: started 09:03:10  period 300 s (r=0.28)  spikes start 3:10 into each period after 09:00

Both worlds have the same 300-second period. In the cron world both instances spike at 0:00 into each five-minute block, on the wall-clock boundary. In the timer world each instance's phase equals its start time modulo five minutes. The prediction fails if the timer world gives the two instances one shared phase, or the cron world gives each its own. Change the seeds in the last loop to repeat it; with 5 and 15 the phases came out the same.

The while loop and the 0.7 threshold are there because autocorrelation also peaks at multiples of the period, and a 30-second spike sampled every 10 seconds correlates almost as well at 290 seconds as at 300. Without them, a noisy series can report 600 or 290 seconds. Check a reported period against the raw series before trusting it.

Read it on a real system#

Pull the latency series per instance at a step shorter than the spike, then run the same two functions on it. Prometheus serves a range query over HTTP with an explicit step. Prometheus HTTP API

curl -sG 'http://prometheus:9090/api/v1/query_range' \
  --data-urlencode 'query=histogram_quantile(0.99, sum by (le, instance) (rate(http_server_request_duration_seconds_bucket{service="quotes-api"}[30s])))' \
  --data-urlencode 'start=2026-11-24T09:00:00Z' --data-urlencode 'end=2026-11-24T11:00:00Z' \
  --data-urlencode 'step=10s'

The [30s] window assumes a scrape interval of 10 seconds or so. Prometheus scrapes every minute and evaluates rules every minute unless configured otherwise; at one-minute resolution a 30-second spike is averaged with the calm half minute beside it, and a period that equals either interval is a reason to suspect the pipeline. Prometheus configuration

Then compare the period and phase with the timers that exist:

crontab -l; ls /etc/cron.d/          # cron entries for this user and the system
systemctl list-timers --all          # systemd timers with their last and next run

Cron fields accept step values such as */5, which fire at minutes divisible by five, on the wall clock. crontab(5) systemctl list-timers lists each timer's last and next trigger. systemctl(1)

For a PostgreSQL dependency, log_checkpoints is on by default and logs each checkpoint with the time spent writing, and pg_stat_checkpointer (PostgreSQL 17 and later) counts checkpoints due to timeout separately from requested ones. With the default checkpoint_completion_target of 0.9, a checkpoint's writes are spread across most of the interval. log_checkpoints ยท pg_stat_checkpointer

SELECT num_timed, num_requested, write_time, sync_time FROM pg_stat_checkpointer;

For a shared Redis cache, TTL key returns a key's remaining time to live; sample a few hot keys and see whether they share one remaining time. TTL For a connection pool, read the configured maximum lifetime and the process start time. Go's SetConnMaxLifetime sets "the maximum amount of time a connection may be reused", and expired connections "may be closed lazily before reuse", so the period is near the lifetime rather than exactly on it. database/sql A garbage collector's own log gives its pause times directly. GC pause or a slow dependency?

Limits#

A clock-driven job that every instance runs is indistinguishable by phase from one shared resource that every instance waits on, such as a database that runs a job on the minute. Look at the dependency's own latency in the same seconds to tell which.

Instances that all started together, for example after a fleet-wide deploy, share their process-relative phase until restarts spread them out. A timer that started with the process then looks like cron. Compare phases after instances have restarted at different times.

Several timers can run at once with different periods, and the autocorrelation then peaks at more than one lag. Fold the series at each candidate and treat each as its own explanation. For causes tied to midnight or the top of the hour, see Errors started at a round time; for the general method, Choose the observation where explanations disagree.

Questions#

How do I find the period of latency spikes?

Export the series at a step shorter than the spike, compute its autocorrelation at each lag, and take the shortest lag with a strong peak. Then fold the series at that period to find where each spike starts. Check the answer against the raw graph, because multiples of the period also correlate.

Why does every instance spike at a different moment?

Their timers started at different moments. A cache filled at startup, a pool that opened its connections at startup or a per-process timer all fire relative to when that process started. Subtract each instance's start time from its spike time; a constant remainder points to a timer in the process.

Could the spikes be caused by monitoring itself?

Yes, in two ways. A scrape or rule evaluation that coincides with the spike can be an artefact of aggregation, in which case request logs and client-side timing show no spike. Or the scrape itself costs the service work, in which case requests are really slower at scrape time and the logs show it too.

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