Capstone - Ride Telemetry Analytics Platform

Article · 7:00

Continuous aggregates, retention and a recovery drill, with the invariants checked rather than asserted.

The system. A ride telemetry analytics platform: a fleet of vehicles emitting position, speed, battery state and events at high frequency; trips as first-class entities joined to vehicles, drivers and fleets; dashboards from live status to year-long trends; multi-tenant access where a fleet operator sees only its own vehicles; and devices that lose connectivity and upload buffered data hours later.

Three invariants must hold:

  1. Every continuous aggregate agrees with its source, verified by a scheduled drift query, including after late data has arrived - which means the refresh policy's start_offset exceeds the fleet's measured lateness distribution, with a monitored counter for anything beyond it.
  2. Retention never destroys unmaterialised data. Raw retention exceeds every aggregate's start_offset with margin, the relationship is documented next to both policies, and a test proves the ordering holds.
  3. Tenant isolation holds on aggregates as well as on raw data, verified by querying every aggregate as a restricted tenant - because RLS on the raw table does not imply it on the aggregate.

Invariant 3 is this capstone's distinguishing requirement. It is the one failure in this course that is a security failure rather than a correctness or cost failure, it is not obvious from the mechanism, and a capstone that has not queried every aggregate as a restricted tenant has not demonstrated it.

What is assessed. 20% knowledge checks, 35% laboratory portfolio, 15% troubleshooting practical, 30% capstone. Three things carry the capstone.

Aggregate correctness under late data, demonstrated. The measured lateness distribution, the start_offset chosen against it with margin, the drift query on a schedule, the beyond-window counter, and a demonstration of the divergence appearing when the offset is too small and resolving when it is not.

A timed recovery drill with verification. Not a backup configuration - a drill: destroy something while the system is under load, recover to a chosen point, and verify with per-chunk counts, recomputed aggregates and foreign key integrity, with every phase timed. You have PostgreSQL's recovery machinery, which is the best in this programme; a capstone that does not use it is leaving the main advantage on the table.

A priced storage lifecycle with the WAL archive in it. Four configurations, the chosen one, and the product-facing sentence stating the resolution available at each age and the PITR window.

Deliverables: architecture diagram including the aggregate cascade and the replication topology; the schema with hypertable, normalised dimensions, foreign keys and the chunk interval arithmetic; the continuous aggregate definitions with justified offsets; compression configuration with the segmentby measurement behind it; source code including the ingestion path, the lateness counter and the drift monitor; the telemetry generator; benchmark report with plans, planning time and the realistic ingestion number; security review including the RLS aggregate finding; the timed recovery drill with verification output; the storage lifecycle cost model including WAL; and a short design defence.

-- ================= Invariants, as runnable checks ==================

-- 1. *** EVERY CONTINUOUS AGGREGATE AGREES WITH ITS SOURCE -
--    *** INCLUDING AFTER LATE DATA. ***
SELECT c.bucket, c.vehicle_id, c.avg_speed AS stored, x.recomputed,
       ABS(c.avg_speed - x.recomputed) AS drift
FROM telemetry_1m c
JOIN (SELECT time_bucket(INTERVAL '1 minute', time) AS bucket,
             vehicle_id, AVG(speed_kph) AS recomputed
      FROM vehicle_telemetry
      WHERE time >= now() - INTERVAL '7 days'
      GROUP BY 1, 2) x
  ON x.bucket = c.bucket AND x.vehicle_id = c.vehicle_id
WHERE ABS(c.avg_speed - x.recomputed) > 0.0001;
--   Expected: no rows. *** ON A SCHEDULE. ***

-- and the cascade level, SAMPLE-WEIGHTED so the check is exact:
SELECT h.bucket, h.vehicle_id, h.avg_speed AS stored, m.recomputed
FROM telemetry_1h h
JOIN (SELECT time_bucket(INTERVAL '1 hour', bucket) AS bucket, vehicle_id,
             SUM(avg_speed * samples) / SUM(samples) AS recomputed
      FROM telemetry_1m
      WHERE bucket >= now() - INTERVAL '30 days'
      GROUP BY 1, 2) m
  ON m.bucket = h.bucket AND m.vehicle_id = h.vehicle_id
WHERE ABS(h.avg_speed - m.recomputed) > 0.0001;
--   Expected: no rows.

-- *** THE OFFSET MUST EXCEED THE MEASURED LATENESS, WITH MARGIN: ***
--   measured fleet lateness:
--     p50 1.2 s | p95 14 s | p99 6 min | p99.9 4 h | *** max 31 h ***
--   -> start_offset = 3 days          (2.3x the observed max)
--   -> and the COUNTER for anything beyond it, alerted on:
SELECT COUNT(*) AS beyond_window
FROM vehicle_telemetry
WHERE time < now() - INTERVAL '3 days'
  AND ingested_at > now() - INTERVAL '1 hour';
--   (carry an ingested_at DEFAULT now() column to make this
--    answerable at all - a small cost, and the only way to know.)

-- 2. *** RETENTION NEVER DESTROYS UNMATERIALISED DATA. ***
--   raw retention              90 days
--   telemetry_1m start_offset   3 days      -> *** 30x MARGIN ***
--   telemetry_1m retention     13 months
--   telemetry_1h retention      5 years
--   telemetry_1d retention     10 years
SELECT hypertable_name, proc_name, config
FROM timescaledb_information.jobs
WHERE proc_name IN ('policy_retention',
                    'policy_refresh_continuous_aggregate')
ORDER BY hypertable_name;
--   *** ASSERT THE ORDERING IN A TEST, not in a comment: *** parse
--   both configs and fail the build if raw retention <= any
--   aggregate's start_offset. *** THE NEXT PERSON TO SHORTEN
--   RETENTION WILL NOT KNOW THE RELATIONSHIP *** - and the damage is
--   silent and permanent.

-- and prove the aggregates have no holes:
SELECT b.bucket FROM generate_series(
         now() - INTERVAL '30 days', now() - INTERVAL '1 day',
         INTERVAL '1 hour') AS b(bucket)
LEFT JOIN telemetry_1h t ON t.bucket = b.bucket
WHERE t.bucket IS NULL;
--   Expected: no rows (outside known outages).

-- 3. *** TENANT ISOLATION HOLDS ON AGGREGATES AS WELL AS ON RAW
--    *** DATA. THIS CAPSTONE'S DISTINGUISHING REQUIREMENT, AND THE
--    *** ONE SECURITY FAILURE IN THE COURSE. ***
SET app.fleet_id = '7';
SELECT COUNT(DISTINCT fleet_id) FROM vehicle_telemetry;   -- 1
SELECT COUNT(DISTINCT fleet_id) FROM telemetry_1m_tenant; -- *** 1 ***
SELECT COUNT(DISTINCT fleet_id) FROM telemetry_1h_tenant; -- *** 1 ***
SELECT COUNT(DISTINCT fleet_id) FROM telemetry_1d_tenant; -- *** 1 ***
RESET app.fleet_id;
--   *** A CAPSTONE THAT HAS NOT QUERIED EVERY AGGREGATE AS A
--   *** RESTRICTED TENANT HAS NOT DEMONSTRATED THIS. *** RLS on the
--   raw table DOES NOT IMPLY IT ON THE AGGREGATE, because the
--   aggregate was materialised by a background job.

-- ================= Declare the baseline BEFORE measuring ==========
--
--   Versions:   PostgreSQL 17.x + TimescaleDB 2.x   <- BOTH, exactly
--   Schema:     vehicle_telemetry hypertable, 5-minute chunks
--                 (arithmetic: 57 MB/s x 300 s = 17 GB/chunk;
--                  3 active chunks = 51 GB <= 25% of 256 GB)
--               NORMALISED dimensions with REAL FOREIGN KEYS
--               PRIMARY KEY (vehicle_id, time)
--               index (vehicle_id, time DESC); (trip_id, time DESC)
--   Compression: segmentby vehicle_id, orderby time DESC, after 1 day
--                 (MEASURED: 3 ms vs 3,400 ms on the characteristic
--                  query; 11.8x ratio)
--   Aggregates: 1m -> 1h -> 1d, cascaded, sample-weighted means,
--               start_offset 3 days, end_offset 1 minute
--               real-time aggregation ON for live dashboards,
--               materialized_only for the year-long charts
--               -> *** AND IT IS STATED WHICH IS WHICH ***
--   Tenancy:    RLS on raw AND on every aggregate, fleet_id in each
--               GROUP BY
--   Roles:      ingest (INSERT only, NO SELECT) / dashboard (SELECT
--               on aggregates only) / analyst / admin
--   Recovery:   pgBackRest, WAL archiving, 6-hourly base backups,
--               async streaming replica
--
--   Claim:
--     sustained ingest, FULL workload   > 300,000 rows/s
--     live status (raw, last 5 min)     p99 <  20 ms  + planning
--     1-day trend (1m aggregate)        p99 <  40 ms
--     1-year trend (1d aggregate)       p99 < 200 ms
--     one vehicle, 7 days, compressed   p99 <  10 ms
--     aggregate drift                   = 0, continuously
--     tenant leakage                    = 0, every aggregate tested
--     replication lag                   p95 < 3 s   (= RPO)
--     *** RTO, MEASURED IN A DRILL      < 35 min ***
--     PITR window                       48 hours
--
--   *** AND THE STORAGE LIFECYCLE, PRICED, WITH THE WAL ARCHIVE
--   *** IN IT: ***
--     raw uncompressed  1 d                      4.9 TB
--     raw compressed   29 d / 11.8x             11.8 TB
--     aggregates                                 0.4 TB
--     *** WAL archive   2 d                     16.4 TB ***
--     TOTAL                                     33.5 TB
--     (compare: compress after 7 d, 30 d WAL = 314 TB. *** 9.4x. ***
--      And note the coupling: compressing after 1 day REQUIRES the
--      lateness window to be under a day - THE POLICIES ARE NOT
--      INDEPENDENT.)
--
--   Product statement:
--     "Full-resolution telemetry for 30 days; 1-minute resolution
--      for 13 months; 1-hour for 5 years. Point-in-time recovery to
--      any moment in the last 48 hours."

-- ================= Failure modes ==================================
--   *** late data beyond start_offset  THE AGGREGATE IS PERMANENTLY
--                                      WRONG. Nothing reports it.
--                                      Invariant 1. ***
--   *** retention shorter than         DATA GONE FROM BOTH RAW AND
--       start_offset                   AGGREGATE, PERMANENTLY.
--                                      Invariant 2. ***
--   *** RLS on raw only                CROSS-TENANT LEAK THROUGH THE
--                                      AGGREGATES. Invariant 3, and
--                                      a SECURITY failure. ***
--   AVG(avg) in the cascade            subtly wrong means. Weight by
--                                      samples.
--   no time predicate                  every chunk. Hidden in views
--                                      and ORM queries.
--   a VOLATILE function in WHERE       no chunk exclusion.
--   a time predicate on a JOINED       no exclusion - the planner
--   table's column only                cannot correlate it. ADD the
--                                      hypertable's own predicate.
--   segmentby not matching the filter  decompresses everything.
--   chunk interval too small           PLANNING TIME dominates. Read
--                                      it separately.
--   locf on a fault code               asserts a fault that cleared.
--   a failed background job            SILENT. Uncompressed chunks
--                                      accumulate; the disk fills.
--                                      Alert on job_stats.
--   a long-running transaction         blocks vacuum AND chunk
--                                      operations. Bloat.
--   real-time aggregation assumed      a dashboard silently missing
--   either way                         its newest bucket, or slower
--                                      than expected. State it.
--   WAL archive omitted from the       the largest line in the bill,
--   cost model                         unbudgeted.
--   pg_restore without                 catalogue errors; a
--   timescaledb_pre_restore()          hypertable that is not one.
--   pg_upgrade with a mismatched       fails PARTWAY. Test on a
--   extension version                  restored copy first.
--   multi-node assumed available       it was REMOVED. Scale up.
--
-- Verify after every recovery with the three invariants - not with a
-- row count. A restored database that starts is not a verified
-- restore.

Where to go from here

Longer reading about this subject, written alongside the course.

Course guide How to work through this course Why to do PostgreSQL first, the four decisions that matter, the two experiments worth doing properly, and what to skip. 4 min read

Discussion

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