Use TimescaleDB for Time-Series Data
Enable TimescaleDB on Managed PostgreSQL, turn a table into a hypertable, query it with time_bucket(), and automate retention with pg_cron.
What Is Available
Managed PostgreSQL ships the Apache-licensed edition of TimescaleDB. Check it after creating the extension:
SHOW timescaledb.license;The value is apache. Hypertables, chunks, time_bucket(), first(), last(),
histogram(), show_chunks() and drop_chunks() work.
The features of the Timescale License (TSL) do not. They fail with an error such as
function "add_retention_policy" is not supported under the current "apache" license, or
functionality not supported under the current "apache" license:
- Policies and jobs:
add_retention_policy(),add_compression_policy(),add_columnstore_policy(),add_job(),alter_job(),delete_job(). - Compression and columnstore:
ALTER TABLE ... SET (timescaledb.compress). - Continuous aggregates:
CREATE MATERIALIZED VIEW ... WITH (timescaledb.continuous). - Gap filling:
time_bucket_gapfill(),locf(),interpolate().
The TSL edition cannot be selected: exo dbaas update with --pg-variant timescale is refused
with Invalid value `timescale` at 'variant': should be one of aiven.
Replacements on Managed PostgreSQL:
- Retention: schedule
drop_chunks()withpg_cron, see Automate Retention with pg_cron. - Rollups: a plain materialized view over a
time_bucket()query, refreshed bypg_cron. The refresh recomputes the whole view, so keep its time window bounded. - Gap filling: join the aggregate onto a
generate_series()of buckets, see Fill Empty Buckets.
Enable the Extension
Connect as avnadmin (see
Connect with psql) to the
database that holds your time-series tables:
CREATE EXTENSION timescaledb;SELECT extname, extversion FROM pg_extension WHERE extname = 'timescaledb';Run CREATE EXTENSION timescaledb as the first statement of a new session. If the session has
already loaded another version of the library, it fails with
extension "timescaledb" has already been loaded with another version and asks you to start a
new session.
Create a Hypertable
A hypertable is split into chunks, one per time range. Queries that filter on time only read the chunks they need.
CREATE TABLE sensor_data (
recorded_at timestamptz NOT NULL,
device_id text NOT NULL,
temperature double precision NOT NULL,
humidity double precision,
battery_pct smallint,
PRIMARY KEY (recorded_at, device_id)
);SELECT create_hypertable(
'sensor_data',
'recorded_at',
chunk_time_interval => INTERVAL '1 day',
if_not_exists => true
);Primary keys and unique constraints must include the time column. A table with
id bigserial PRIMARY KEY is refused with
cannot create a unique index without the column "recorded_at" (used in partitioning).
A table that already holds rows is refused with table "..." is not empty, unless you ask for the
data to be moved. The move rewrites the data and locks the table meanwhile:
SELECT create_hypertable(
'sensor_data',
'recorded_at',
chunk_time_interval => INTERVAL '1 day',
migrate_data => true
);Add ordinary indexes for your filters:
CREATE INDEX ON sensor_data (device_id, recorded_at DESC);SELECT hypertable_name, num_dimensions, num_chunks
FROM timescaledb_information.hypertables;Query with time_bucket
time_bucket() groups rows into intervals of any width:
SELECT
time_bucket(INTERVAL '1 hour', recorded_at) AS bucket,
device_id,
avg(temperature) AS avg_temperature,
max(temperature) AS max_temperature,
count(*) AS samples
FROM sensor_data
WHERE recorded_at >= now() - INTERVAL '24 hours'
GROUP BY bucket, device_id
ORDER BY bucket DESC;Always filter on the time column, so that TimescaleDB can skip chunks.
first() and last() return a value at the earliest or latest time, for example the latest
reading per device:
SELECT
device_id,
first(temperature, recorded_at) AS first_temperature,
last(temperature, recorded_at) AS last_temperature
FROM sensor_data
WHERE recorded_at >= now() - INTERVAL '1 hour'
GROUP BY device_id;Combined with time_bucket(), they downsample a series:
SELECT
time_bucket(INTERVAL '15 minutes', recorded_at) AS bucket,
device_id,
last(battery_pct, recorded_at) AS battery_pct
FROM sensor_data
WHERE recorded_at >= now() - INTERVAL '6 hours'
GROUP BY bucket, device_id
ORDER BY bucket DESC;histogram() counts values in equal-width bins between two bounds:
SELECT device_id, histogram(temperature, 0, 40, 10) AS distribution
FROM sensor_data
WHERE recorded_at >= now() - INTERVAL '7 days'
GROUP BY device_id;The array has the 10 requested bins plus one element for values below the lower bound and one for values above the upper bound.
Fill Empty Buckets
Generate the buckets with generate_series() and join the data onto them:
SELECT g AS bucket, avg(s.temperature) AS avg_temperature
FROM generate_series(time_bucket(INTERVAL '1 hour', now() - INTERVAL '6 hours'),
now(), INTERVAL '1 hour') AS g
LEFT JOIN sensor_data s
ON time_bucket(INTERVAL '1 hour', s.recorded_at) = g
GROUP BY g
ORDER BY g;Buckets without rows return NULL.
Inspect Chunks
Chunks that are too large reduce the benefit of partitioning; chunks that are too small add planning overhead. A common target is that the most recent chunk and its indexes fit in memory.
SELECT show_chunks('sensor_data');SELECT chunk_name, range_start, range_end
FROM timescaledb_information.chunks
WHERE hypertable_name = 'sensor_data'
ORDER BY range_start DESC;List the chunks older than a threshold, which is also what drop_chunks() would remove:
SELECT show_chunks('sensor_data', older_than => INTERVAL '90 days');Change the interval for new chunks; existing chunks keep their range:
SELECT set_chunk_time_interval('sensor_data', INTERVAL '2 days');Estimate the row count from statistics, which are as fresh as the last ANALYZE:
SELECT approximate_row_count('sensor_data');Automate Retention with pg_cron
Dropping a chunk removes its rows and frees its disk space at once, unlike DELETE. A chunk is
dropped only when its whole time range is older than the threshold.
Drop old chunks once:
SELECT drop_chunks('sensor_data', older_than => INTERVAL '90 days');To repeat it every night, create pg_cron
in defaultdb, the only database that accepts it:
CREATE EXTENSION pg_cron;Then, still in defaultdb, schedule the call in the database that holds the hypertable:
SELECT cron.schedule_in_database(
'sensor-data-retention',
'0 3 * * *',
$$SELECT drop_chunks('public.sensor_data', older_than => INTERVAL '90 days')$$,
'DATABASE_NAME'
);Parameters:
DATABASE_NAME: database with the hypertable and thetimescaledbextension. If the hypertable is indefaultdb, usecron.schedule()with the first three arguments.
Check the runs:
SELECT d.status, d.return_message, d.start_time, d.end_time
FROM cron.job_run_details d
JOIN cron.job j USING (jobid)
WHERE j.jobname = 'sensor-data-retention'
ORDER BY d.start_time DESC
LIMIT 5;Warning
The job deletes data without asking. Test the threshold with show_chunks() first. Getting
dropped data back means creating a new service from a point in time before the drop, see
Fork a service.
A rollup view is refreshed the same way. REFRESH ... CONCURRENTLY needs a unique index on the
view and keeps it readable during the refresh:
CREATE MATERIALIZED VIEW public.sensor_data_hourly AS
SELECT time_bucket(INTERVAL '1 hour', recorded_at) AS bucket,
device_id,
avg(temperature) AS avg_temperature
FROM sensor_data
WHERE recorded_at > now() - INTERVAL '30 days'
GROUP BY bucket, device_id;
CREATE UNIQUE INDEX ON public.sensor_data_hourly (bucket, device_id);SELECT cron.schedule_in_database(
'sensor-data-hourly-refresh',
'5 * * * *',
$$REFRESH MATERIALIZED VIEW CONCURRENTLY public.sensor_data_hourly$$,
'DATABASE_NAME'
);TimescaleDB Service Settings
The number of TimescaleDB background workers is a service setting, separate from --pg-settings.
Read its range in the settings catalog:
exo api get-dbaas-settings-pg -q 'settings.timescaledb'Change it with:
exo dbaas update SERVICE_NAME -z ZONE -f --pg-timescaledb-settings '{"max_background_workers":8}'Parameters:
SERVICE_NAME: name of the service.ZONE: zone of the service, for examplech-gva-2.
The change restarts the service. Check the value with SHOW timescaledb.max_background_workers;.