Skip to content

TimescaleDB hypertables for time-series on PostgreSQL

Run time-series workloads on PostgreSQL with TimescaleDB — hypertables, chunk sizing, continuous aggregates, retention policies, and compression.

TimescaleDB is a PostgreSQL extension that turns a regular table into a hypertable — a logical view over many time-bucketed chunks. It handles the partition layout, chunk creation, retention, and columnar-style compression for you, while keeping full SQL and indexes. It suits metrics, IoT telemetry, financial tick data, and audit logs that need to live in Postgres rather than a separate TSDB. This article covers the operational shape: chunk sizing, compression, continuous aggregates, and the failure modes that matter.

How to verify

Confirm the extension is loaded and the hypertable is healthy:

psql -d metrics -c "SELECT extversion FROM pg_extension WHERE extname='timescaledb';"
psql -d metrics -c "SELECT hypertable_name, num_chunks, compression_enabled
                    FROM timescaledb_information.hypertables;"
psql -d metrics -c "SELECT pg_size_pretty(total_bytes) AS total
                    FROM hypertable_detailed_size('metrics');"
psql -d metrics -c "SELECT * FROM timescaledb_information.hypertable_compression_settings;"

If num_chunks grows as expected, chunk creation is working. hypertable_detailed_size() is a function that takes the hypertable name, and hypertable_compression_settings lists the segmentby and orderby of each compressed chunk.

Check the partitioning column, the chunk interval and the newest chunks:

SELECT column_name, time_interval
FROM timescaledb_information.dimensions
WHERE hypertable_name = 'metrics';

SELECT chunk_name, range_start, range_end, is_compressed
FROM timescaledb_information.chunks
WHERE hypertable_name = 'metrics'
ORDER BY range_start DESC LIMIT 10;

On an empty test hypertable, load a small batch and run the chunks query again. The rows below cover about one week, so with a 1-day interval you should see seven or eight chunks:

INSERT INTO metrics (time, device_id, metric, value)
SELECT now() - (s * interval '1 minute'),
       gen_random_uuid(),
       'requests_per_second',
       random() * 1000
FROM generate_series(1, 10000) AS s;

Check how much of the hypertable is compressed and what it saved:

SELECT total_chunks, number_compressed_chunks,
       pg_size_pretty(before_compression_total_bytes) AS uncompressed,
       pg_size_pretty(after_compression_total_bytes)  AS compressed
FROM hypertable_compression_stats('metrics');

If the compressed total is far smaller than the uncompressed total, compression is doing its job.

What’s happening

A hypertable is a parent table with TimescaleDB’s chunk catalog underneath. When you insert a row, TimescaleDB routes it to the chunk whose time range matches; new chunks are created lazily as data crosses the boundary. Each chunk is a regular Postgres table — you can VACUUM, ANALYZE, and index it normally — but you mostly interact with the hypertable.

Compression converts a chunk’s row-store into a column-store. The chunk’s rows are sorted by segment_by columns (your tenant key, device id, metric name), then each column is compressed individually with type-aware codecs (delta-of-delta for timestamps, gorilla for floats, dictionary for low-cardinality strings). The vendor documentation cites chunk size reductions of up to 98%, and the ratio you get depends on how well the segmenting and ordering fit your data. Compressed chunks stay writable (see the pitfalls below). Query performance on the compressed window depends on whether your predicates align with segment_by.

Continuous aggregates are materialised views that TimescaleDB refreshes incrementally — only the time bucket containing new rows is recomputed. They’re how you keep dashboards fast over years of raw data without re-running the aggregation every time.

Install the extension on Ubuntu

TimescaleDB publishes its own apt repository. The vendor’s self-hosted procedure lists Ubuntu 22.04 and 24.04 as supported, and the commands below follow it:

# PostgreSQL packages from the PGDG repository
sudo apt install gnupg postgresql-common apt-transport-https lsb-release wget
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh

# TimescaleDB repository and signing key
echo "deb https://packagecloud.io/timescale/timescaledb/ubuntu/ $(lsb_release -c -s) main" | sudo tee /etc/apt/sources.list.d/timescaledb.list
wget --quiet -O - https://packagecloud.io/timescale/timescaledb/gpgkey | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/timescaledb.gpg

# The package name carries the PostgreSQL major version
sudo apt update
sudo apt install timescaledb-2-postgresql-18 postgresql-client-18

# Tune postgresql.conf, then restart to load the library
sudo timescaledb-tune
sudo systemctl restart postgresql

Replace 18 with the PostgreSQL major version you run. The vendor warns that this procedure can raise errors on a server where PostgreSQL was installed earlier. To keep an existing installation, their documentation points to the build from source instead.

timescaledb-tune reads postgresql.conf and proposes values based on the server’s memory, CPU count and PostgreSQL version. It asks before each group of changes and writes a backup of the file. The first change it proposes is the one the extension cannot run without:

shared_preload_libraries = 'timescaledb'

If you manage postgresql.conf by hand, add that line yourself and separate any other preloaded libraries with commas. The setting takes effect at the restart. The package also sends usage telemetry to the vendor by default; timescaledb.telemetry_level = off in postgresql.conf turns it off.

The procedure

  1. Install and create the hypertable:

    CREATE EXTENSION IF NOT EXISTS timescaledb;
    
    CREATE TABLE metrics (
      time        timestamptz NOT NULL,
      device_id   uuid NOT NULL,
      metric      text NOT NULL,
      value       double precision NOT NULL,
      tags        jsonb
    );
    
    SELECT create_hypertable('metrics', by_range('time', INTERVAL '1 day'));
    
    CREATE INDEX ON metrics (device_id, time DESC);
    CREATE INDEX ON metrics (metric, time DESC);

    Chunk interval is the most important sizing decision, and the default is 7 days. The vendor’s rule is to set it so that the indexes of the chunks currently being ingested into fit within 25% of main memory. Their example is a server with 64 GB of memory: index growth of about 2 GB per day suits a 1-week interval, and about 10 GB per day calls for a 1-day interval. Too-small chunks fragment the planner; too-large chunks lose chunk-exclusion benefits. set_chunk_time_interval() changes the interval later, for new chunks only.

    by_range() belongs to the hypertable API introduced in TimescaleDB 2.13. From 2.20, the vendor recommends CREATE TABLE ... WITH (tsdb.hypertable) for a new hypertable, and that form also enables the columnstore. create_hypertable() remains the call that converts an existing table.

  2. Add compression policy:

    ALTER TABLE metrics SET (
      timescaledb.compress,
      timescaledb.compress_segmentby = 'device_id, metric',
      timescaledb.compress_orderby = 'time DESC'
    );
    
    SELECT add_compression_policy('metrics', INTERVAL '7 days');

    segmentby should match your most common WHERE columns. orderby should be your sort order within a segment — time DESC is the right default for time-series. Chunks older than 7 days are compressed in a background job.

    Since TimescaleDB 2.18 the vendor calls this feature the columnstore, or hypercore. timescaledb.enable_columnstore, add_columnstore_policy(), convert_to_columnstore() and chunk_columnstore_stats() supersede timescaledb.compress, add_compression_policy(), compress_chunk() and chunk_compression_stats(). The documentation marks the older names as “Old API” and states that they are still supported, so the commands here run on current releases and on versions before 2.18. The 2.18.0 release notes plan their removal for TimescaleDB 3.0.

  3. Retention policy:

    SELECT add_retention_policy('metrics', INTERVAL '90 days');

    Drops whole chunks past the cutoff — instant, no VACUUM cost. This is the win over partitioning by hand.

  4. Continuous aggregate for dashboards:

    CREATE MATERIALIZED VIEW metrics_1h
      WITH (timescaledb.continuous) AS
      SELECT time_bucket('1 hour', time) AS bucket,
             device_id, metric,
             avg(value) AS avg_val,
             max(value) AS max_val,
             count(*)   AS samples
      FROM metrics
      GROUP BY 1, 2, 3;
    
    SELECT add_continuous_aggregate_policy('metrics_1h',
      start_offset => INTERVAL '24 hours',
      end_offset   => INTERVAL '1 hour',
      schedule_interval => INTERVAL '15 minutes');

    end_offset = '1 hour' prevents the most recent (incomplete) bucket from being materialised. Since TimescaleDB 2.13, real-time aggregation is disabled by default, so the view returns only materialised data. To have queries add the recent rows that are not materialised yet, run ALTER MATERIALIZED VIEW metrics_1h SET (timescaledb.materialized_only = false);.

  5. Watch the policies. TimescaleDB jobs live in timescaledb_information.jobs and timescaledb_information.job_stats. Alert when total_failures increments — a stuck compression job is silent data growth.

  6. Verify compression actually compressed:

    SELECT chunk_name, compression_status,
           pg_size_pretty(before_compression_total_bytes) AS before,
           pg_size_pretty(after_compression_total_bytes)  AS after
    FROM chunk_compression_stats('metrics');

    A low ratio suggests your segment_by and order_by don’t match your data shape — re-tune.

Common pitfalls

  • Compressed chunks accept writes: INSERT works from TimescaleDB 2.3, and UPDATE and DELETE from 2.11. When the table has unique constraints, each insert decompresses a small amount of data to check them. For a large backfill into the compressed window, the vendor’s advice is to pause the compression job, run decompress_chunk on the affected chunks, load the data, then compress again.
  • Continuous aggregates aren’t free — they hold a refresh job and storage. Don’t materialise a 1-minute aggregate over 5 years of raw if you only query the last 30 days.
  • DROP TABLE on a hypertable drops every chunk; use drop_chunks for partial cleanup.
  • Multi-node TimescaleDB (distributed hypertables) was removed in 2.14. Version 2.13 was the last release with it, on PostgreSQL 13 to 15 only. Scaling past one server now means PostgreSQL read replicas for read load, or a different tool such as Citus for sharded writes.
  • Restoring a pg_dump of a TimescaleDB database has a required sequence. Create the extension in the target database, run SELECT timescaledb_pre_restore();, run pg_restore, then run SELECT timescaledb_post_restore();. Do not use pg_restore -j, which the vendor says does not restore the TimescaleDB catalogs correctly. The hypertable data are in the chunks, no data will be copied notice that pg_dump prints is safe to ignore.
  • pg_dump --table on one hypertable does not carry enough information to recreate it. The documented path is a schema dump, create_hypertable() on the target, and a COPY of the data.
  • failed to start a background worker in the PostgreSQL log means the worker settings are too low for your policies. The vendor’s rule is that timescaledb.max_background_workers equals the number of databases plus the number of concurrent background workers, and that max_worker_processes equals that value plus max_parallel_workers.

For declarative partitioning without TimescaleDB, see PostgreSQL declarative partitioning.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.