Security here is PostgreSQL security, which means it is the most capable in this programme and that the work is to use it properly rather than to work around its absence. Roles, GRANT at table and column level, SECURITY DEFINER functions, pg_hba.conf host-based access control, SCRAM authentication, TLS with client certificates, and row-level security - all of it applies to hypertables.
The role design for a telemetry platform is a short list worth building and testing: an ingest role with INSERT on the hypertable and nothing else - no SELECT, which means a compromised collector cannot read your history; a dashboard role with SELECT on the continuous aggregates only, not on raw data; an analyst role with SELECT on raw and aggregates; and an admin role for policies and schema. Test every denial, because an untested grant is a guess, and pg_hba.conf should restrict each role to the network it legitimately comes from.
Row-level security works on hypertables, and it has one interaction that genuinely surprises people. A continuous aggregate is materialised by a background job, not by the querying user - so the rows that go into it are not filtered by the querying user's RLS policy. A tenant querying an aggregate can therefore see data aggregated across tenants unless the aggregate itself is partitioned by tenant - which means including the tenant key in the aggregate's GROUP BY and applying RLS to the aggregate as well. This is a real multi-tenant data leak, it is not obvious, and it will pass a review by someone who has only checked that RLS is enabled on the raw table. Test it: query an aggregate as a restricted tenant and verify what comes back.
Monitoring. The PostgreSQL set first, because it is where the problems are: connection count against max_connections, transaction age and the oldest transaction - a long-running transaction holds back vacuum and bloats everything, and on a time-series workload it also blocks chunk operations; dead tuples and autovacuum activity per chunk; replication lag; checkpoint frequency, where checkpoints_req substantially exceeding checkpoints_timed means max_wal_size is too small; cache hit ratio; and pg_stat_statements for the actual query cost distribution.
Then the TimescaleDB-specific set: background job health, because a failed compression or refresh job is silent and its consequences accumulate - check job_stats for last_run_status and total_failures; the chunk count per hypertable, which is the planning-time predictor; the compression ratio and the number of uncompressed chunks older than the policy, which tells you compression is falling behind; continuous aggregate drift, from Module 3's query; and the lateness counter.
The storage lifecycle is the cost model and the arithmetic is worth doing properly, because it has more levers than the previous course. Raw uncompressed for the lateness window; raw compressed at ten to twenty times for the operational window; continuous aggregates, which are small; and archived WAL, which people forget and which is not small - a write-heavy database generates WAL at a substantial multiple of its data rate, and a long archive retention for PITR is a real line in the bill. Put all four in the model, and state the resolution available at each age as a product fact.
Upgrades have an order and getting it wrong is painful. Within TimescaleDB, ALTER EXTENSION timescaledb UPDATE must run in a fresh session with nothing else from the extension touched first, and should be done one minor version at a time with the release notes read - the compression and continuous aggregate internals have changed in ways that matter. For a PostgreSQL major version upgrade, the extension must be available for the new version before you start, and the supported ordering is to upgrade the extension to a version compatible with both, then upgrade PostgreSQL, then upgrade the extension again if needed. pg_upgrade with TimescaleDB requires the extension installed in the new cluster at the same version, and a mismatch fails partway, which is exactly the failure you do not want. Test the whole sequence on a restored copy of production, always.
Laboratory exercise 6 - make it defensible.
Configure TLS with client certificates, SCRAM authentication, and a pg_hba.conf restricting each role to its legitimate network.
Build and test the four-role design, with every denial verified: ingest cannot SELECT, dashboard cannot read raw data, analyst cannot write, and none but admin can alter policies.
Then the row-level security laboratory, which is the module's centre. Implement multi-tenant RLS on the raw hypertable and verify a tenant sees only its own rows. Then query a continuous aggregate as that tenant and show the cross-tenant leak. Fix it by including the tenant key in the aggregate's GROUP BY and applying RLS to the aggregate, and verify again. Write this up as a security finding, because it is one.
Configure monitoring with every metric above. Then demonstrate why job health matters: deliberately fail a compression job, let it stay failed, and record what accumulates - uncompressed chunks, storage growth, and query latency degradation - with nothing alerting unless you added the alert.
Produce the storage lifecycle cost model with all four components including WAL archive, for four lifecycle configurations, and state the product-facing resolution-by-age sentence for your chosen one.
Finally, perform both upgrades on a restored copy: a TimescaleDB minor version upgrade in a fresh session, and a PostgreSQL major version upgrade in the correct order. Document the sequence as a runbook with the verification steps, and record what happened when you deliberately did the extension and PostgreSQL steps in the wrong order.
Deliverable: the security configuration, the four-role design with every denial tested, the RLS continuous aggregate leak demonstrated and fixed and written up as a finding, the monitoring and alert definitions, the failed-job accumulation demonstration, the four-way storage lifecycle model including WAL, the two upgrade runbooks, and the wrong-order failure recorded.
-- ==================================================================
-- *** SECURITY HERE IS POSTGRESQL SECURITY - the most capable in the
-- *** programme. The work is to USE IT PROPERLY. ***
-- ==================================================================
-- THE ROLE DESIGN for a telemetry platform:
CREATE ROLE telemetry_ingest LOGIN PASSWORD '...';
GRANT INSERT ON vehicle_telemetry TO telemetry_ingest;
GRANT USAGE ON SCHEMA public TO telemetry_ingest;
-- *** NO SELECT. A COMPROMISED COLLECTOR CANNOT READ YOUR
-- *** HISTORY. *** That one omission is the whole security review.
CREATE ROLE telemetry_dashboard LOGIN PASSWORD '...';
GRANT SELECT ON telemetry_1m, telemetry_1h, telemetry_1d
TO telemetry_dashboard;
-- *** NOT on vehicle_telemetry. *** The dashboard reads AGGREGATES.
CREATE ROLE telemetry_analyst LOGIN PASSWORD '...';
GRANT SELECT ON vehicle_telemetry, telemetry_1m, telemetry_1h,
vehicles, trips, models TO telemetry_analyst;
CREATE ROLE telemetry_admin LOGIN PASSWORD '...';
GRANT ALL ON ALL TABLES IN SCHEMA public TO telemetry_admin;
-- *** TEST EVERY DENIAL. AN UNTESTED GRANT IS A GUESS: ***
-- SET ROLE telemetry_ingest;
-- SELECT * FROM vehicle_telemetry LIMIT 1; -- *** DENIED ***
-- SET ROLE telemetry_dashboard;
-- SELECT * FROM vehicle_telemetry LIMIT 1; -- *** DENIED ***
-- INSERT INTO vehicle_telemetry ... -- *** DENIED ***
-- SET ROLE telemetry_analyst;
-- SELECT add_retention_policy(...); -- *** DENIED ***
--
-- And pg_hba.conf - *** RESTRICT EACH ROLE TO THE NETWORK IT
-- *** LEGITIMATELY COMES FROM: ***
-- hostssl telemetry telemetry_ingest 10.20.0.0/16 scram-sha-256
-- hostssl telemetry telemetry_dashboard 10.30.0.0/16 scram-sha-256
-- hostssl telemetry telemetry_admin 10.40.0.5/32 cert
-- ssl = on / ssl_min_protocol_version = 'TLSv1.3'
-- ==================================================================
-- *** ROW-LEVEL SECURITY, AND THE INTERACTION THAT GENUINELY
-- *** SURPRISES PEOPLE. THIS IS A REAL MULTI-TENANT DATA LEAK. ***
-- ==================================================================
ALTER TABLE vehicle_telemetry ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON vehicle_telemetry
USING (fleet_id = current_setting('app.fleet_id')::INT);
-- SET app.fleet_id = '7';
-- SELECT COUNT(*) FROM vehicle_telemetry; -- only fleet 7. GOOD.
-- *** NOW THE LEAK: ***
-- SET app.fleet_id = '7';
-- SELECT * FROM telemetry_1h; -- *** ROWS AGGREGATED ACROSS
-- -- *** EVERY FLEET. ***
--
-- *** WHY: A CONTINUOUS AGGREGATE IS MATERIALISED BY A BACKGROUND
-- *** JOB, NOT BY THE QUERYING USER - so the rows that went into it
-- *** WERE NEVER FILTERED BY THE QUERYING USER'S RLS POLICY. ***
--
-- *** IT IS NOT OBVIOUS, AND IT WILL PASS A REVIEW BY SOMEONE WHO
-- *** HAS ONLY CHECKED THAT RLS IS ENABLED ON THE RAW TABLE. ***
--
-- THE FIX: put the tenant key IN THE AGGREGATE, and apply RLS TO THE
-- AGGREGATE TOO:
CREATE MATERIALIZED VIEW telemetry_1h_tenant
WITH (timescaledb.continuous) AS
SELECT time_bucket(INTERVAL '1 hour', time) AS bucket,
fleet_id, -- *** REQUIRED ***
vehicle_id,
AVG(speed_kph) AS avg_speed, COUNT(*) AS samples
FROM vehicle_telemetry
GROUP BY bucket, fleet_id, vehicle_id
WITH NO DATA;
ALTER MATERIALIZED VIEW telemetry_1h_tenant ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation_agg ON telemetry_1h_tenant
USING (fleet_id = current_setting('app.fleet_id')::INT);
--
-- *** THEN TEST IT AGAIN AS A RESTRICTED TENANT AND VERIFY WHAT
-- *** COMES BACK. WRITE IT UP AS A SECURITY FINDING, BECAUSE IT IS
-- *** ONE. ***
-- ==================================================================
-- MONITORING. The PostgreSQL set first - that is where the problems
-- are.
-- ==================================================================
SELECT count(*) AS conns,
(SELECT setting::INT FROM pg_settings WHERE name='max_connections') AS max
FROM pg_stat_activity;
-- *** THE OLDEST TRANSACTION. A long-running transaction HOLDS BACK
-- *** VACUUM AND BLOATS EVERYTHING - and on a time-series workload
-- *** it also BLOCKS CHUNK OPERATIONS *** (compression, drop_chunks):
SELECT pid, usename, state, now() - xact_start AS xact_age, query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL ORDER BY xact_start LIMIT 10;
-- ALERT above a few minutes. This is the single most common cause
-- of "why is the database getting bigger".
SELECT checkpoints_timed, checkpoints_req FROM pg_stat_bgwriter;
-- *** checkpoints_req substantially exceeding checkpoints_timed
-- *** means max_wal_size IS TOO SMALL. ***
SELECT sum(heap_blks_hit)::float
/ NULLIF(sum(heap_blks_hit)+sum(heap_blks_read),0) AS cache_hit_ratio
FROM pg_statio_user_tables;
-- *** THEN THE TIMESCALEDB SET. BACKGROUND JOB HEALTH FIRST, because
-- *** A FAILED JOB IS SILENT AND ITS CONSEQUENCES ACCUMULATE: ***
SELECT job_id, proc_name, hypertable_name, last_run_status,
last_successful_finish, total_runs, total_failures,
total_successes
FROM timescaledb_information.job_stats
WHERE last_run_status <> 'Success' OR total_failures > 0;
-- *** ALERT ON ANY ROW HERE. *** A compression job that has been
-- failing for a week leaves a week of uncompressed chunks, and the
-- first symptom is the disk filling.
SELECT hypertable_name, COUNT(*) AS chunks,
COUNT(*) FILTER (WHERE NOT is_compressed) AS uncompressed,
COUNT(*) FILTER (WHERE NOT is_compressed
AND range_end < now() - INTERVAL '7 days')
AS overdue_for_compression
FROM timescaledb_information.chunks GROUP BY hypertable_name;
-- *** THAT LAST COLUMN TELLS YOU COMPRESSION IS FALLING
-- *** BEHIND. *** Anything above zero for long is the disk
-- filling up in slow motion.
-- Plus: chunk count (the PLANNING-TIME predictor), the compression
-- ratio, CONTINUOUS AGGREGATE DRIFT (Module 3's query), and the
-- LATENESS COUNTER.
-- ==================================================================
-- *** THE STORAGE LIFECYCLE IS THE COST MODEL - and it has MORE
-- *** LEVERS than the previous course. ***
-- ==================================================================
-- ingest 318,000 rows/s x 180 bytes = 57 MB/s = 4.9 TB/day raw
--
-- LIFECYCLE A - compress after 7 days, raw 90 days:
-- raw uncompressed 7 d x 4.9 TB = 34.3 TB
-- raw compressed 83 d x 4.9 TB / 12 = 33.9 TB
-- continuous aggs 13 mo = 0.4 TB
-- *** WAL ARCHIVE 30 d x 95 MB/s = 246 TB *** <-
-- TOTAL 314 TB
--
-- *** THE WAL ARCHIVE IS THE LINE PEOPLE FORGET, AND IT IS NOT
-- *** SMALL. *** A write-heavy database generates WAL at a
-- SUBSTANTIAL MULTIPLE of its data rate, and a long archive
-- retention FOR PITR IS A REAL LINE IN THE BILL.
--
-- LIFECYCLE B - compress after 1 day, raw 90 d, WAL 7 d:
-- 4.9 + 36.3 + 0.4 + 57.4 = 99 TB (3.2x less)
-- LIFECYCLE C - compress after 1 day, raw 30 d, WAL 7 d:
-- 4.9 + 11.8 + 0.4 + 57.4 = 74 TB
-- LIFECYCLE D - as C, WAL 2 d, daily base backups:
-- 4.9 + 11.8 + 0.4 + 16.4 = 33 TB
-- *** and the RTO goes DOWN too *** (less WAL to replay) at the
-- cost of more frequent base backups. Note that B through D
-- compress after 1 DAY, which requires the lateness window to be
-- under a day - *** THE POLICIES ARE COUPLED. ***
--
-- And the PRODUCT-FACING sentence, which is the deliverable:
-- "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."
-- ==================================================================
-- *** UPGRADES HAVE AN ORDER, AND GETTING IT WRONG IS PAINFUL. ***
-- ==================================================================
-- TIMESCALEDB MINOR UPGRADE - *** IN A FRESH SESSION, with nothing
-- else from the extension touched first: ***
-- psql -c "ALTER EXTENSION timescaledb UPDATE;"
SELECT extversion FROM pg_extension WHERE extname='timescaledb';
-- *** ONE MINOR VERSION AT A TIME, WITH THE RELEASE NOTES READ ***
-- - the compression and continuous aggregate internals HAVE
-- CHANGED IN WAYS THAT MATTER.
-- *** POSTGRESQL MAJOR UPGRADE - the extension MUST BE AVAILABLE FOR
-- *** THE NEW VERSION BEFORE YOU START. The supported order: ***
-- 1. upgrade TimescaleDB to a version compatible WITH BOTH
-- 2. install that SAME extension version for the NEW PostgreSQL
-- 3. pg_upgrade
-- 4. ALTER EXTENSION timescaledb UPDATE, if needed
-- 5. REINDEX / ANALYZE as the notes require, and verify
--
-- *** pg_upgrade WITH TIMESCALEDB REQUIRES THE EXTENSION INSTALLED
-- *** IN THE NEW CLUSTER AT THE SAME VERSION, AND A MISMATCH FAILS
-- *** PARTWAY *** - exactly the failure you do not want. Do it in
-- the wrong order ONCE IN THE LAB and record the error.
--
-- *** TEST THE WHOLE SEQUENCE ON A RESTORED COPY OF PRODUCTION.
-- *** ALWAYS. *** You have PITR (Module 5) - which means you can
-- make that copy in an afternoon, so there is no excuse.
Discussion
No questions on this topic yet. Sign in to ask the first one.