Windowing, Downsampling, Retention and Late Data

Article · 10:00

Window functions and gap handling, building downsampling rollups, retention and what expiry removes, and handling late-arriving points correctly.

Downsampling is not an optimisation, it is the architecture. Raw telemetry at one-second resolution for a year is a volume nobody queries and nobody can afford to keep. The standard shape is a cascade: keep raw data for days, one-minute rollups for weeks, one-hour rollups for months and one-day rollups for years, with each level computed from the one above. A dashboard then queries the level matching its time range, and a year-long chart reads 365 rows rather than 31 million points.

Building the cascade differs by generation and this is where the version choice bites hardest. In 2.x a task is a Flux script on a schedule that reads a window, aggregates it and writes to a rollup bucket - a clean, self-contained mechanism. In 3.x the mechanism depends on edition and version, and the portable answer is an external scheduler running a SQL INSERT INTO ... SELECT, which is more plumbing and more explicit. Either way, the discipline is the same: the rollup is derived data, so it must be recomputable, and a rollup you cannot rebuild from raw data is a liability.

Retention is per bucket in 2.x and per database or table in 3.x, and it is not a delete. Expiry drops whole time-partitioned blocks, which is why it is nearly free and why it is coarse: you cannot retain some series longer than others within the same bucket. That constraint is a modelling input - if two kinds of data need different retention, they belong in different buckets or databases, which is another argument for splitting measurements.

Late data is the problem that defines time-series engineering, and it is this module's centre. A point arriving with a timestamp in the past is normal: a device was offline and has buffered, a gateway retried, a clock was wrong, a batch upload ran. Three things follow.

First, a rollup already computed for that window is now wrong. The hourly mean for 14:00 was computed at 15:00; a point timestamped 14:30 arrives at 16:00; the stored mean no longer matches the raw data. Nothing tells you.

Second, retention can have already dropped the window the point belongs to, in which case the write succeeds and the data is immediately unreachable - or is rejected, depending on version and configuration. Either way the point is lost and no error reaches the device.

Third, "how late is too late" is a product decision that must be made explicitly. The answers: a lateness window during which rollups are recomputed, after which late points are accepted into raw data but do not change the rollups; recomputing affected rollup windows on arrival, which is correct and expensive; or rejecting points older than a threshold, which is honest and loses data.

The practical design: a lateness window of hours to a day, rollups recomputed over a trailing window on each run rather than only the newest one, and a counter of points arriving later than the window - because that counter is the only thing that tells you the policy is wrong.

Gaps are the smaller sibling. A window with no data produces no row, so a chart shows a line jumping across the gap rather than a hole. createEmpty in Flux and a generated time series joined in SQL are the two answers, and which is correct depends on whether absent means zero or means unknown - a decision worth stating per measurement.

Laboratory exercise 3 - rollups and late data.

Build a telemetry ingestion service and run at least 100 concurrent writers.

Build the full downsampling cascade: raw to one-minute to one-hour to one-day, with each level computed from the one above, in your chosen generation's mechanism.

Measure what it buys: a year-long chart from raw data and from the daily rollup, recording rows scanned, bytes read and latency for each.

Then the late-data laboratory, which is the module's centre. Use your generator's late-point capability to inject points into a window whose rollup is already computed. Demonstrate the divergence: show the stored rollup and the recomputed value from raw data disagreeing, with nothing having reported it. Then implement a trailing recomputation window and show the divergence resolved. Then inject a point outside the window and show it accepted into raw data without changing the rollup, with the counter incrementing.

Demonstrate the retention interaction: inject a point older than the retention period and record what happens - accepted and immediately unreachable, or rejected.

Implement gap filling both ways and show the difference on a chart with a real outage in it.

Deliverable: the service, the full cascade with its mechanism documented, the raw-against-rollup measurements, the divergence demonstrated and resolved, the out-of-window counter, the retention interaction result, both gap-filling approaches, and a written lateness policy with the number in it.

-- ==================================================================
-- *** DOWNSAMPLING IS NOT AN OPTIMISATION, IT IS THE ARCHITECTURE. ***
-- ==================================================================
--   raw      1 second     keep  7 days
--   1m       1 minute     keep 90 days   (computed from raw)
--   1h       1 hour       keep  2 years  (computed from 1m)
--   1d       1 day        keep 10 years  (computed from 1h)
--
-- A dashboard queries THE LEVEL MATCHING ITS TIME RANGE. A
-- year-long chart reads 365 ROWS instead of 31,000,000 POINTS.

-- 3.x: the portable mechanism is an EXTERNAL SCHEDULER running
-- INSERT INTO ... SELECT. More plumbing, and explicit:
INSERT INTO machine_telemetry_1m
SELECT
    date_bin(INTERVAL '1 minute', time) AS time,
    site, machine, sensor,
    AVG(value)   AS mean_value,
    MIN(value)   AS min_value,
    MAX(value)   AS max_value,
    COUNT(*)     AS samples,
    SUM(CASE WHEN fault THEN 1 ELSE 0 END) AS faults
FROM machine_telemetry
WHERE time >= $window_start AND time < $window_end
GROUP BY 1, site, machine, sensor;

-- *** STORE COUNT AND SUM, NOT JUST THE MEAN. *** A mean cannot be
-- re-aggregated correctly (the mean of means is wrong when the
-- windows have different sample counts), and with count and sum the
-- next level up is exact:
INSERT INTO machine_telemetry_1h
SELECT
    date_bin(INTERVAL '1 hour', time) AS time,
    site, machine, sensor,
    SUM(mean_value * samples) / SUM(samples) AS mean_value,  -- EXACT
    MIN(min_value) AS min_value,
    MAX(max_value) AS max_value,
    SUM(samples)   AS samples,
    SUM(faults)    AS faults
FROM machine_telemetry_1m
WHERE time >= $window_start AND time < $window_end
GROUP BY 1, site, machine, sensor;
--   That one line - SUM(mean * samples) / SUM(samples) - is the
--   difference between a correct cascade and a subtly wrong one, and
--   it is why the schema carries `samples`.

-- 2.x: a TASK, in Flux. A cleaner mechanism, self-contained:
--   option task = {name: "downsample_1m", every: 1m, offset: 30s}
--
--   from(bucket: "telemetry")
--     |> range(start: -2m, stop: -1m)          // a trailing window
--     |> filter(fn: (r) => r._measurement == "machine_telemetry")
--     |> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
--     |> set(key: "_measurement", value: "machine_telemetry_1m")
--     |> to(bucket: "telemetry_1m")
--
--   `offset` delays the run so points written slightly late are
--   included - which is the simplest form of the lateness handling
--   below.

-- *** THE ROLLUP IS DERIVED DATA, SO IT MUST BE RECOMPUTABLE. *** A
-- rollup you cannot rebuild from raw data is a liability - and the
-- recomputation script is the same INSERT with a different window,
-- which is why it is worth writing it parameterised from the start.

-- ==================================================================
-- RETENTION: *** NOT A DELETE, AND COARSE. ***
-- ==================================================================
--   2.x: per BUCKET
--     influx bucket update -n telemetry --retention 7d
--     influx bucket create -n telemetry_1m --retention 90d
--     influx bucket create -n telemetry_1h --retention 730d
--
--   3.x: per DATABASE (and per table on some editions)
--     influxdb3 create database telemetry --retention-period 7d
--
-- *** EXPIRY DROPS WHOLE TIME-PARTITIONED BLOCKS ***, which is why
-- it is nearly FREE - and why it is COARSE: *** YOU CANNOT RETAIN
-- SOME SERIES LONGER THAN OTHERS WITHIN THE SAME BUCKET. ***
--
-- THAT CONSTRAINT IS A MODELLING INPUT: if two kinds of data need
-- different retention, THEY BELONG IN DIFFERENT BUCKETS OR
-- DATABASES - which is another argument for splitting measurements
-- (Module 2).

-- ==================================================================
-- *** LATE DATA. The problem that defines time-series engineering. ***
-- ==================================================================
-- A point arriving with a timestamp IN THE PAST is NORMAL:
--   a device was offline and has BUFFERED
--   a gateway RETRIED
--   a clock was WRONG
--   a BATCH UPLOAD ran
--
-- THREE THINGS FOLLOW.

-- *** (1) A ROLLUP ALREADY COMPUTED FOR THAT WINDOW IS NOW WRONG. ***
--   14:00-15:00 hourly mean computed at 15:05      -> 72.4
--   a point timestamped 14:30 arrives at 16:00
--   the stored rollup still says                   -> 72.4
--   recomputed from raw it is                      -> 73.1
--   *** NOTHING TELLS YOU. *** Detect it:
SELECT r.time, r.machine, r.mean_value AS stored,
       x.recomputed, ABS(r.mean_value - x.recomputed) AS drift
FROM machine_telemetry_1h r
JOIN (
  SELECT date_bin(INTERVAL '1 hour', time) AS time, machine,
         AVG(value) AS recomputed
  FROM machine_telemetry
  WHERE time >= now() - INTERVAL '48 hours'
  GROUP BY 1, machine
) x ON x.time = r.time AND x.machine = r.machine
WHERE ABS(r.mean_value - x.recomputed) > 0.001;
--   *** RUN THIS ON A SCHEDULE. It is the only thing that detects a
--   *** rollup diverging from its source. ***

-- THE FIX: *** RECOMPUTE A TRAILING WINDOW ON EVERY RUN, NOT ONLY
-- *** THE NEWEST ONE: ***
DELETE FROM machine_telemetry_1h
WHERE time >= now() - INTERVAL '24 hours';         -- the LATENESS WINDOW
INSERT INTO machine_telemetry_1h
SELECT date_bin(INTERVAL '1 hour', time) AS time, site, machine, sensor,
       AVG(value), MIN(value), MAX(value), COUNT(*),
       SUM(CASE WHEN fault THEN 1 ELSE 0 END)
FROM machine_telemetry
WHERE time >= now() - INTERVAL '24 hours'
GROUP BY 1, site, machine, sensor;
--   Delete-and-reinsert over the trailing window is idempotent and
--   simple. It costs recomputing 24 hours every run, which is cheap
--   against the alternative of silently wrong dashboards.

-- *** (2) RETENTION MAY HAVE ALREADY DROPPED THE WINDOW. *** The
--   write SUCCEEDS and the data is IMMEDIATELY UNREACHABLE - or is
--   REJECTED, depending on version and configuration. *** EITHER WAY
--   THE POINT IS LOST AND NO ERROR REACHES THE DEVICE. *** Test
--   yours; do not assume.

-- *** (3) "HOW LATE IS TOO LATE" IS A PRODUCT DECISION. *** Make it
--   explicitly. The options:
--     a LATENESS WINDOW during which rollups are recomputed; later
--       points land in raw data and DO NOT change the rollups
--     RECOMPUTE AFFECTED WINDOWS ON ARRIVAL - correct, and expensive
--     REJECT points older than a threshold - honest, and loses data
--
--   *** THE PRACTICAL DESIGN: a lateness window of HOURS TO A DAY,
--   *** rollups recomputed over a TRAILING WINDOW, and A COUNTER OF
--   *** POINTS ARRIVING LATER THAN THE WINDOW *** - because that
--   counter is THE ONLY THING THAT TELLS YOU THE POLICY IS WRONG:
--     if ingest_time - point_time > LATENESS_WINDOW:
--         metrics.increment("influx.points.beyond_lateness_window",
--                           tags={"site": site})
--   Alert on it. A rising count means devices are offline longer
--   than you designed for, which is operational news.

-- ==================================================================
-- GAPS: the smaller sibling, and the decision is semantic.
-- ==================================================================
-- A window with NO DATA produces NO ROW, so a chart draws a LINE
-- ACROSS THE GAP rather than a HOLE.
--
-- SQL: generate the buckets and LEFT JOIN:
SELECT b.bucket, t.machine, t.mean_value
FROM generate_series(
       now() - INTERVAL '24 hours', now(), INTERVAL '1 hour'
     ) AS b(bucket)
LEFT JOIN machine_telemetry_1h t
       ON t.time = b.bucket AND t.machine = 'press-07'
ORDER BY b.bucket;
--   Flux: aggregateWindow(every: 1h, fn: mean, createEmpty: true)
--
-- *** AND WHICH IS CORRECT DEPENDS ON WHETHER ABSENT MEANS ZERO OR
-- *** MEANS UNKNOWN: ***
--   a REQUEST COUNT with no data        -> 0 requests. Fill with 0.
--   a TEMPERATURE with no data          -> UNKNOWN. Leave NULL, and
--                                          draw the hole.
--   filling a missing temperature with 0 puts a 0 degree reading on
--   your chart and into any alert threshold that reads it.
-- *** STATE THIS PER MEASUREMENT. *** It is a semantic decision, not
-- a charting preference.

Discussion

No questions on this topic yet. Sign in to ask the first one.