Trending

World technology news

→
Build an SQLite and D1 error-rate report that exposes missing hours
Software Engineering · 2026
Software Engineering

Build an SQLite and D1 error-rate report that exposes missing hours

Generate an hourly spine with a recursive CTE, distinguish verified zero traffic from missing telemetry, and calculate a weighted three-hour error rate.

Developer's JournalPublished: Nov 27, 20266 min read
Reading progress0%
In this article
  1. What zero means in an hourly error chart
  2. Set up two hours that explain the difference
  3. Create one UTC row for every hour
  4. Weight the three-hour rate by traffic
  5. Run and operate the query in D1
  6. Test the boundaries and show coverage to readers

What zero means in an hourly error chart

A service does not produce the same number of telemetry records every hour. Overnight it may handle no traffic. At other times a source file can arrive late or a collector can finish only part of a transfer. If both conditions appear as zero in a dashboard, a misleading drop in the error rate can look like a recovery. It may actually reflect a gap in measurement. This example uses two kinds of evidence. request_batches contains batches of counters observed at particular times. completed_hours records the independently established fact that all expected data for an hour is available. A production collector could mark an hour complete once it has checked the source’s expected row count or checksum, for example. Time passing and collection completing are separate events. A late batch remains provisional until the source’s completion condition is met.

Set up two hours that explain the difference

Run the setup in an empty SQLite database. Each row contains counts for its own batch. The two batches at 08:00 add up to 120 calls and two errors. At 10:00 there are no batch rows, and the collector has marked the hour complete. This produces zero calls and zero errors. At 12:00, by contrast, one batch of 50 calls and eight errors has arrived while the completion record is absent. The report leaves that hour’s totals blank. The input row at 16:00 tests the exclusive upper bound. The requested interval begins at 08:00 and ends before 16:00. An adjacent report that starts at 16:00 can include the boundary row without counting it twice. The schema also refuses negative counters and error counts above the number of calls, which protects the denominator before the reporting query runs.

Database access flowConceptual sketch · summary of the article's technical flow
CREATE TABLE request_batches (
    batch_id INTEGER PRIMARY KEY,
    occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),
    calls INTEGER NOT NULL CHECK (calls >= 0),
    errors INTEGER NOT NULL CHECK (errors BETWEEN 0 AND calls)
);

CREATE INDEX request_batches_by_time
    ON request_batches(occurred_at);

CREATE TABLE completed_hours (
    hour_utc INTEGER PRIMARY KEY CHECK (hour_utc % 3600 = 0)
);

INSERT INTO request_batches (occurred_at, calls, errors) VALUES
    (unixepoch('2026-11-27 08:10:00'), 100, 2),
    (unixepoch('2026-11-27 08:45:00'), 20, 0),
    (unixepoch('2026-11-27 09:15:00'), 10, 1),
    (unixepoch('2026-11-27 11:00:00'), 200, 6),
    (unixepoch('2026-11-27 12:05:00'), 50, 8),
    (unixepoch('2026-11-27 13:05:00'), 80, 4),
    (unixepoch('2026-11-27 14:30:00'), 40, 0),
    (unixepoch('2026-11-27 15:04:00'), 100, 1),
    (unixepoch('2026-11-27 16:00:00'), 400, 150);

INSERT INTO completed_hours (hour_utc) VALUES
    (unixepoch('2026-11-27 08:00:00')),
    (unixepoch('2026-11-27 09:00:00')),
    (unixepoch('2026-11-27 10:00:00')),
    (unixepoch('2026-11-27 11:00:00')),
    (unixepoch('2026-11-27 13:00:00')),
    (unixepoch('2026-11-27 14:00:00')),
    (unixepoch('2026-11-27 15:00:00'));

Create one UTC row for every hour

Bind the two interval boundaries as Unix seconds. The bounds CTE names them once. The recursive hours CTE emits the starting hour and adds 3,600 seconds while the result is still inside the interval. Its seed is restricted to exact hour boundaries and a positive interval. This prevents a mistyped start time from silently creating a series of shifted hours. The totals CTE applies the interval to the raw timestamp and then groups the remaining rows by hour. The timestamp index gives the engine an option to read only the requested range. Use the query plan and representative data to establish whether it does. The next CTE joins hourly totals and completion records onto the hour series. It retains every clock hour. Only completed hours receive a numeric total, with zero used when no batch exists. A missing hour receives NULL counters and a separate missing status.

WITH RECURSIVE
bounds(start_utc, end_utc) AS (
    VALUES (?1, ?2)
),
hours(hour_utc) AS (
    SELECT start_utc
    FROM bounds
    WHERE end_utc > start_utc
      AND start_utc >= 0
      AND start_utc % 3600 = 0
      AND end_utc % 3600 = 0
    UNION ALL
    SELECT h.hour_utc + 3600
    FROM hours AS h
    CROSS JOIN bounds AS b
    WHERE h.hour_utc + 3600 < b.end_utc
),
totals AS (
    SELECT occurred_at - (occurred_at % 3600) AS hour_utc,
           SUM(calls) AS calls,
           SUM(errors) AS errors
    FROM request_batches
    WHERE occurred_at >= (SELECT start_utc FROM bounds)
      AND occurred_at <  (SELECT end_utc FROM bounds)
    GROUP BY 1
),
hourly AS (
    SELECT h.hour_utc,
           CASE WHEN c.hour_utc IS NULL THEN 0 ELSE 1 END AS coverage,
           CASE WHEN c.hour_utc IS NOT NULL THEN COALESCE(t.calls, 0) END AS calls,
           CASE WHEN c.hour_utc IS NOT NULL THEN COALESCE(t.errors, 0) END AS errors
    FROM hours AS h
    LEFT JOIN totals AS t USING (hour_utc)
    LEFT JOIN completed_hours AS c USING (hour_utc)
),
rolling AS (
    SELECT hour_utc, coverage, calls, errors,
           SUM(coverage) OVER recent AS covered_hours,
           SUM(calls) OVER recent AS window_calls,
           SUM(errors) OVER recent AS window_errors
    FROM hourly
    WINDOW recent AS (
        ORDER BY hour_utc ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
    )
)
SELECT strftime('%H:%M', hour_utc, 'unixepoch') AS utc_hour,
       CASE coverage WHEN 1 THEN 'complete' ELSE 'missing' END AS status,
       calls,
       errors,
       CASE WHEN covered_hours = 3
            THEN ROUND(100.0 * window_errors / NULLIF(window_calls, 0), 2)
       END AS rate_3h_pct
FROM rolling
ORDER BY hour_utc;

Weight the three-hour rate by traffic

The named window contains the current row and the two preceding rows. Each row stands for a consecutive hour because the hour series was built first. SUM(coverage) confirms when all three hours are complete. At 11:00, the window covers 09:00, 10:00 and 11:00. It contains 210 calls and seven errors, yielding 3.33 percent. Dividing the sums gives the proper influence to a busy hour and to a quiet hour. An arithmetic mean of hourly percentages would weight hours equally. The first two rows have a shorter history. The missing 12:00 hour also affects the three windows that contain it. A fully observed rate returns at 15:00, where five errors out of 220 calls give 2.27 percent. A complete window containing zero calls has no rate to report. NULLIF keeps the result at NULL in that case, and the coverage column still shows the status of the current hour.

The UTC timeline shows verified zero traffic and missing data as separate states.
utc_hour  status    calls  errors  rate_3h_pct
08:00     complete  120    2       NULL
09:00     complete  10     1       NULL
10:00     complete  0      0       2.31
11:00     complete  200    6       3.33
12:00     missing   NULL   NULL    NULL
13:00     complete  80     4       NULL
14:00     complete  40     0       NULL
15:00     complete  100    1       2.27

Run and operate the query in D1

In a Worker with a D1 binding, prepare the SQL and bind the two integer values after validating the input. A bounded range keeps work predictable. A dashboard for the last seven days can generate up to 168 hourly rows, for example. A long reporting period may warrant a separate table of completed hourly aggregates to reduce repeated reads of the raw batches. Check the actual workload before deciding which representation is appropriate. To display a full three-hour window on the first visible hour, begin the calculation two hours earlier and apply the visible range filter after window calculation. An earlier filter would remove the rows needed for the window. Decide how a delayed batch updates the aggregates and when the completion marker is safe to create. A resumed import can use a stable source batch identifier to avoid including the same batch twice. The local primary key in the example establishes row identity. The production process needs a policy for replaying the same source batch.

Test the boundaries and show coverage to readers

Test several outcomes independently. Two batches in the same hour must be added. A complete empty hour produces zero calls and errors. An incomplete hour makes each containing window unknown. A batch exactly at the upper bound is assigned to the following interval. Three complete, zero-traffic hours produce a NULL rate. After a missing hour is completed, rerun the affected hour and all later windows that include it. A small fixture with these cases catches mistakes that can stay hidden in a weekly average. Keep the underlying keys in UTC even if the dashboard uses local labels. Convert the chosen start and end using the rules of the relevant time zone. A local day can have more or fewer than 24 hours where daylight saving applies. In multi-day results, retain a date or an unambiguous UTC timestamp in addition to the short hour label used by this example.

Further reading / Referencehttps://sqlite.org/lang_with.html ↗
Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

Which bottleneck would you expect as this solution scales?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.