← Math
Math

Sampling, frequency, and aliasing

Where does the four-minute wave on the dashboard come from?

Choose sampling and rollup rules that preserve the signal needed for the decision.

Outcome

Predict the period an undersampled pattern appears to have, choose a scrape interval by the Nyquist limit, and downsample with averages and maxima instead of dropping points.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Sample rate
How often a value is observed: a 15-second scrape interval is 1/15 samples per second.
Frequency and period
A pattern that repeats every P seconds has frequency 1/P per second.
Aliasing
A pattern faster than the samples can follow appears as a slower one: its frequency folds to the nearest multiple of the sample rate.
Nyquist limit
Uniform sampling must exceed twice the highest sinusoidal frequency present in a band-limited signal for phase-independent reconstruction.
Downsampling
Reducing resolution; a bucket average smooths, while a maximum preserves recorded extremes. Neither can recover events missed by the original samples.

Why this matters

Every metric, sensor reading and frame of video is a sample of something that changes between samples. Sampling too slowly does not just lose detail: it shows patterns that are not there. Reducing resolution later, for dashboards and long-term storage, has the same problem unless each kept point summarises the ones it replaces.

This lesson assumes fractions, periods and averages.

What sampling preserves

A sample records a signal at one instant. Frequency counts cycles per second and is the reciprocal of period; the sampling rate counts observations per second. Aliasing occurs when different changing signals produce the same samples, so a fast variation can appear to be slower.

Downsampling makes a second choice about the evidence to retain. A mean describes a bucket’s trend, while a maximum preserves whether any recorded value crossed a limit. Neither can recover an event that was never observed. A sampling bound for one sinusoidal component also leaves sharper changes with higher frequencies to consider.

01A scrape is a sample

A scrape is a sample

Your team scrapes CPU gauges every 15 seconds and separately records a latency summary each second. The CPU panel for the cache service shows a slow wave with a four-minute period that nobody can explain, and the latency alert, evaluated on 10-second rollups, did not fire during a spike that customers noticed.

A gauge such as CPU usage is read once per scrape; whatever happens between scrapes is not recorded. The cache service refreshes for about 4 seconds every 16 seconds. A 15 s scrape interval sees one point per cycle, each 1 s earlier modulo 16 than the last.

prom-client exposes counters and histograms from Node.js; the scrape interval is set in Prometheus, not in the service.

02The wave that is not there

The wave that is not there

Predict both rows.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A job is busy for the first 4 s of every 16 s. Mark each scrape that lands while it is busy.
for (const every of [15, 5]) {
  let row = "";

  for (let k = 0; k < 33; k++) row += (every * k) % 16 < 4 ? "#" : ".";

  console.log(`every ${String(every).padStart(2)} s: ${row}`);
}

At 15 s the busy scrapes come in runs of four every 16 scrapes: a pattern with a 240-second period. To isolate the frequency arithmetic, the lab models one sinusoidal component rather than the whole pulse. Frequencies f and f − m f_s produce the same sampled phase advances, for integer m and sample rate f_s. Choose m nearest to f/f_s so the leftover has the smallest magnitude; invert its magnitude for the apparent period, or report flat when it is zero. For the 16 s fundamental,1/16 per second folds to the nearest multiple of the scrape rate, 1/15, and the leftover 1/16 − 1/15 = −1/240 is what the dashboard draws. At 5 s the busy points are usually 15 or 20 s apart, giving better evidence for the 16 s schedule. The complete sampled busy/quiet sequence repeats only after 80 s; sharper pulse edges contain higher frequencies, so even5s sampling does not reconstruct the original rectangular pulse.

For A and N, the configured ideal periods and scrape intervals are decimal seconds from 0.0001 to 1,000,000, with at most four fractional digits. The supplied period4 helper converts them to integer units of 0.0001 seconds; within these bounds that conversion recovers the configured integer exactly. Choose the nearest whole cycle count from those integers, then subtract its whole-cycle advance. A half-cycle tie has the same residual magnitude on either side. Zero integer residual means flat: a 0.1-second component scraped every 0.3 seconds returns to the same phase exactly.

A nonzero residual gives an approximate displayed period: convert the integer periods and residual back to binary64 seconds, multiply the two periods, then divide by the residual. The supplied formatter rounds that represented value to one decimal with halfway ties to even; 1.25 prints as 1.2. Classification uses the configured periods, rather than interpreting a binary representation artifact as a new physical wave. A and N lists contain 1..10,000 items.

03More than two samples per cycle

More than two samples per cycle

For a sinusoidal component with frequency f, uniform sampling must be faster than 2f to distinguish it from lower-frequency aliases regardless of phase. More generally the signal must be band-limited below half the sampling rate. The16s fundamental therefore needs a scrape interval under 8 s; it does not bound the faster content of a 4 s pulse or guarantee catching every spike. At exactly two samples per sine cycle, opposite zero crossings can both readzero and draw a flat line. A 60 s sinusoidal component sampled every 15 s is below the limit. N tests twice the integer scrape interval strictly below the integer period, so the exact decimal equality is aliased. Its displayed bound is the smallest integer period divided by 20,000, approximately in seconds.

A job runs every 61 s and is scraped every 60 s. What period appears?

04Downsampling needs a choice

Downsampling needs a choice

30 s of p99 latency rolled up to 10 s buckets, alert above 500 ms
Each bucket keepsBuckets (ms)Alert
The last sample121, 119, 121none
The average120.0, 356.9, 120.2none
The maximum123, 950, 123bucket 2

Here each value is an independently recorded one-second p99 summary in ms, not the 15 s CPU gauge. The middle bucket is120,119,121,900,950,880,122,118,120,119: sum 3569, mean 356.9, maximum 950. The other two buckets sum 1200 and 1202. These means and maxima summarize reported p99 values; neither reconstructs p99 for a combined request distribution. Keeping every tenth point is downsampling with no model of what happened in between, and a three-second spike disappears. A box average reduces fast variation and suits this trend view, but it is not an ideal anti-alias filter. This alert’s rule is any recorded sample above 500 ms, so it needs the bucket maximum. Prometheus provides avg_over_time and max_over_time for this. R receives measured binary64 latencies, separately from the configured decimal periods: sum each bucket from zero in input order, divide by its actual sample count and apply the same one-decimal formatter. The alert compares the unformatted maximum strictly above the parsed limit; equality does not alert. Series length and bucket size are integers from 1 to 10,000; values and limit are finite in [0, 10¹²] ms. These bounds keep sums and averages finite. These averages approximate the measured inputs; they are not exact configured periods.

05What a sampled series cannot tell you

What a sampled series cannot tell you

06Fix the dashboard

Fix the dashboard

Explain the cache panel’s false slow frequency, check the resolved frequency range, then preserve the latency alert’s any-sample rule when storing coarser buckets.

In the frontend Min-max decimation for a chart in Next.js and Svelte Optional

A chart has far fewer pixels than points. Drawing each pixel’s minimum and maximum keeps spikes that every-nth-point drawing would skip.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// The latency chart has 600 px for 86,400 points. Keep each pixel’s minimum and maximum
// instead of every 144th point, so a spike between kept points still shows.
export function minMaxPerPixel(values: number[], width: number): [number, number][] {
  const per = Math.ceil(values.length / width);
  const out: [number, number][] = [];

  for (let i = 0; i < values.length; i += per) {
    const bucket = values.slice(i, i + per);
    out.push([Math.min(...bucket), Math.max(...bucket)]);
  }

  return out;
}

export function LatencyBars({ values }: { values: number[] }) {
  return (
    <svg width={600} height={100}>
      {minMaxPerPixel(values, 600).map(([lo, hi], x) => (
        <line
          key={x}
          x1={x}
          x2={x}
          y1={100 - lo / 10}
          y2={100 - hi / 10}
          stroke="currentColor"
        />
      ))}
    </svg>
  );
}

Check this idea later
What uniform scrape interval is below the Nyquist bound for a20s sinusoidal component?
You keep one point per minute from per-second data for an alert dashboard. What should each point be?
Sources

Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The services, jobs and latencies are a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.