Query icon
Log icon
If icon
SlackIncomingWebhook icon
Loop icon
Fail icon
Schedule icon

TimescaleDB Continuous Aggregate Refresh Lag Guard

Detect TimescaleDB continuous aggregates lagging the raw hypertable, catch them up with refresh_continuous_aggregate and verify the watermark.

Categories
DataInfrastructure

A TimescaleDB continuous aggregate is a materialized rollup of a hypertable, kept current by a refresh policy that runs on a schedule. When the policy is missing, paused or failing, the aggregate keeps answering queries with old numbers and nothing errors. A dashboard reading the aggregate looks healthy while it sits hours or days behind the raw data.

This blueprint reads the materialization watermark of every continuous aggregate, the latest row in its raw hypertable and the refresh policy job statistics. It compares the watermark with the latest raw time and reports each aggregate that is behind, with the reason drawn from last_run_status and last_successful_finish. It can then resume a paused policy, catch the aggregate up with refresh_continuous_aggregate, add a policy where one is missing, then read the watermark again to confirm the rollup is current.

This blueprint was created by zkasuran.

Findings

Status What the catalog shows Why it matters
NO_POLICY No policy_refresh_continuous_aggregate job for the view The watermark never advances on its own, so the rollup drifts further behind over time
PAUSED A refresh job exists but scheduled is false Somebody paused it, so the aggregate stops updating while it still looks configured
LAGGING The watermark is further behind the latest raw row than the end offset plus the schedule interval plus the grace The job runs but cannot keep up, often because it is failing or the data outruns the policy
OK The watermark is within that allowed window Recent buckets inside the end offset are not materialized yet by design, so they are not reported

The watermark is the exclusive upper bound of the materialized region, read with cagg_watermark and turned into a timestamp with to_timestamp. A healthy real time aggregate sits about one end offset behind the newest row, so the allowed lag is the policy end offset plus its schedule interval plus a grace period.

last_run_status and last_successful_finish are reported for every flagged aggregate, so a failing job shows up as the cause of the lag rather than as a separate signal to chase.

Safety

  • Read-only unless auto_remediate is true and dry_run is false. The audit and the plan are two SELECT queries.
  • The plan is printed before anything runs, one line per statement, so the change is reviewable from a dry run log.
  • refresh_continuous_aggregate commits inside its own transaction, so each statement runs on its own and never inside a transaction block.
  • Nothing is dropped or deleted. A refresh materializes buckets that the aggregate already defines.

How it works

  1. audit (io.kestra.plugin.jdbc.postgresql.Query, read-only) joins timescaledb_information.continuous_aggregates, the raw hypertable time dimension, the policy_refresh_continuous_aggregate jobs and their job_stats. For each aggregate it reads the watermark, the latest raw row and classifies it as NO_POLICY, PAUSED, LAGGING or OK.
  2. plan returns one row per remediation statement, ordered resume, refresh, add policy. Nothing in it runs unless both gates are open.
  3. summary logs every aggregate, its lag and the plan.
  4. route (io.kestra.plugin.core.flow.If):
    • clean: logs it.
    • behind: alert posts to Slack.
      • remediate_gate opens only when auto_remediate is true and dry_run is false.
      • remediate (io.kestra.plugin.core.flow.Loop, concurrencyLimit: 1) runs each statement in turn, one single statement per query.
      • recheck counts, from the catalog, how many targeted aggregates are still behind.
      • reaudit reads the full picture again for the log.
      • verify_result fails the run when a targeted aggregate is still behind. Otherwise it logs what was caught up and what is left.
  5. errors alerts Slack when the database cannot be reached.

What you get

  • A per aggregate verdict that separates no policy from a paused policy from a policy that cannot keep up.
  • The real time lag between each rollup and its raw data, read from the watermark and the hypertable, not inferred from a job timestamp.
  • A catch up checked against the watermark afterwards, so the run fails if the rollup is still behind.
  • Aggregates that are current left untouched.

Who it's for

  • Teams serving dashboards and APIs from TimescaleDB continuous aggregates.
  • Platform teams who inherited aggregates built by several services, some with a policy and some without.
  • Anyone who found a rollup was days stale only when a customer asked why a number looked wrong.

Why orchestrate this with Kestra

A refresh policy can be paused during an incident and never resumed. It can also quietly fail while the aggregate keeps serving old rows. Kestra runs the audit on a schedule, sends the aggregates that are behind and their lag to Slack and keeps the catch up behind auto_remediate and dry_run. A refresh can be slow and holds its own locks, so a scheduled, sequential, re-verified run suits it.

Tested end to end

On Kestra 2.0.5 OSS against TimescaleDB 2.30.2 on PostgreSQL 16, with a local HTTP sink standing in for Slack. One raw hypertable conditions holds 30 days of hourly rows. Four continuous aggregates were built into one state each:

Continuous aggregate State built Watermark before
cagg_ok Policy present, refreshed to the latest bucket 2026-10-10 09:00, within the window
cagg_lag Policy scheduled, refreshed only up to 7 days ago 2026-10-03 08:00, 7 days behind
cagg_paused Policy exists, then scheduled set to false 2026-10-05 08:00, 5 days behind
cagg_nopolicy Continuous aggregate with no refresh policy never materialized
Run Execution Inputs Result
1 2S7v2o2nhIgyU9BDqcR0eW defaults 4 scanned, 3 behind: LAGGING cagg_lag, NO_POLICY cagg_nopolicy, PAUSED cagg_paused, with cagg_ok OK. Plan 5 statements (1 RESUME_JOB, 3 REFRESH, 1 ADD_POLICY). Alert sent. psql confirmed every watermark unchanged afterwards
2 2EBTgS37wMShvjvxvBQHvY auto_remediate: true, dry_run: false The 5 statements ran. The three lagging watermarks advanced to 2026-10-10 09:00, cagg_paused was resumed, cagg_nopolicy gained job 1008. recheck reported 0 still behind. Run succeeded
3 6622zszHqRUBTqgSDnPGmq defaults 4 scanned, 0 behind. Clean branch, no alert
4 1G0woKZ1fBOcrvP6Rfv53A defaults, after inserting hourly rows 3 days past the watermark 4 behind. Every watermark 2026-10-10 09:00, now 2 days 23:54:26 behind the latest raw row 2026-10-13 08:54. The detector caught the new lag. Plan 4 REFRESH
5 4mUKCY8Z7Jo6sKaotFYQ1j auto_remediate: true, dry_run: false 4 refreshed. psql: every watermark advanced to 2026-10-13 09:00. recheck 0 still behind. Run succeeded
6 3HXdQO6ZQsCESrBb8uZ10v unreachable database audit failed with a connection error. errors posted to Slack. Run FAILED

Every watermark figure was read back from psql with cagg_watermark and to_timestamp, not from the Kestra log alone. Runs 3 then 4 are the before and after of one healthy system: clean, then lagging once rows arrived past the watermark. That is the proof the check can fail.

Prerequisites

  • TimescaleDB 2.12 or later. The flow calls _timescaledb_functions.cagg_watermark and to_timestamp, the timescaledb_information views, refresh_continuous_aggregate and add_continuous_aggregate_policy.
  • Continuous aggregates built on a hypertable whose time dimension is timestamp with time zone, the common case. Aggregates on a plain timestamp, date or integer dimension are skipped.
  • The audit needs a role that can read the information views and call cagg_watermark. Remediation needs the owner of the aggregates.
  • Local testing:
    • docker run -d --name ts -p 5432:5432 -e POSTGRES_PASSWORD=ts -e POSTGRES_DB=metrics timescale/timescaledb:latest-pg16;
    • create a hypertable, a continuous aggregate and a refresh policy, then pause the policy or insert rows past the last refresh.

Secrets

  • TIMESCALE_PASSWORD: the database password, read by the db_password input default.
  • SLACK_WEBHOOK_URL: used by alert and the errors block.
  • In Kestra OSS, provide each one as a base64-encoded environment variable prefixed SECRET_.

Inputs

Input Default Purpose
jdbc_url jdbc:postgresql://localhost:5432/metrics TimescaleDB database
db_user postgres Database user
db_password secret('TIMESCALE_PASSWORD') Database password
schemas public Comma separated schemas to scan
grace_period 1 hour Added to the allowed lag
fallback_start_offset 3 days Window refreshed and start offset of a policy added for an aggregate with none
fallback_end_offset 1 hour End offset of a policy added for an aggregate with none
fallback_schedule_interval 1 hour Schedule interval of a policy added for an aggregate with none
auto_remediate false Allow the plan to run
dry_run true Must be false for anything to run

Quick start

  1. Add the TIMESCALE_PASSWORD and SLACK_WEBHOOK_URL secrets.
  2. Import the flow, set jdbc_url and schemas.
  3. Run it with the defaults and read the plan in the summary log.
  4. Agree the fallback offsets with the owners, then run with auto_remediate: true and dry_run: false.
  5. Enable the hourly trigger, which always runs in safe mode.

How to extend

  • Add a Pause before remediate when the lag crosses a threshold, so a large catch up gets an approval.
  • Refresh a bounded window per run for a very large backlog and let later runs finish it.
  • Loop over several JDBC URLs to cover every database of a fleet from one run.
  • Record the per aggregate lag into a table and chart how freshness moves over time.
  • Extend the scan to aggregates built on top of another aggregate.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.