Every second, your servers report CPU usage. Every minute, a sensor sends a temperature. Every trade on an exchange carries a price and a timestamp. This kind of data has one thing in common: each record is a measurement at a point in time, and you almost never change it after it arrives.
You can store it in a normal table. Many teams start that way and it works for a while. Then the table grows to billions of rows, dashboards get slow, the disk fills up, and deleting old data locks everything. Time-series databases exist for exactly this shape of data.
What counts as time-series data
A time-series is a sequence of values indexed by time. A single data point usually has:
- a timestamp,
- a metric name, such as
cpu_usageortemperature, -
tags (also called labels or dimensions) that say where it came from, such as
host=web-1orregion=eu, - one or more values, usually numbers.
The access pattern is what makes it special:
- Writes are mostly appends. New points arrive with a recent timestamp. Updates and deletes of single rows are rare.
- Reads are by time range. "The last 15 minutes", "yesterday between 9 and 10", "this week per hour".
- Reads aggregate. You rarely want every raw point. You want averages, maximums, percentiles or counts per time bucket.
- Old data loses value. Raw per-second data matters for a few days. After that, per-hour summaries are enough, and after a year you may drop it entirely.
A general-purpose database is built for a mix of reads, updates and deletes on any row. A time-series database is built around the four points above.
How a time-series database works
The details differ between products, but most of them use the same set of ideas.
Partitioning by time
Data is split into chunks by time range, for example one chunk per day. TimescaleDB calls these chunks, InfluxDB calls them shards, Prometheus calls them blocks. A query for "the last hour" only touches the newest chunk. Dropping data older than 30 days means deleting whole chunks, which is a cheap file or table drop instead of a slow DELETE that scans millions of rows.
Write-friendly storage
Incoming points are first collected in memory and in a write-ahead log, then flushed to disk in large sorted batches. Large sequential writes are much cheaper than many small random ones. This is why a time-series database can ingest a high rate of points on modest hardware.
Compression
Time-series data compresses very well because neighbouring points look alike:
- Timestamps arrive at regular intervals, so the database stores the difference between differences (delta-of-delta). For a metric scraped every 10 seconds, that is mostly zero, which takes almost no bits.
- Values change slowly, so storing the XOR with the previous value (the approach described in Facebook's Gorilla paper) leaves mostly zeros as well.
- Data is stored by column, so all values of one series sit together and compress as a block.
The result is that a data point often takes only a few bytes on disk instead of the dozens a row in a regular table needs.
Series and an index on tags
Each unique combination of metric name and tags is one series. cpu_usage{host=web-1} and cpu_usage{host=web-2} are two series. The database keeps an index from tags to series, so a query like "all hosts in region eu" finds the right series quickly and then reads only their time range.
Retention and downsampling
You define a retention policy ("keep raw data for 14 days") and the database drops older chunks for you. Many products can also downsample: compute per-minute or per-hour averages in the background (continuous aggregates in TimescaleDB, recording rules in Prometheus), keep those for much longer, and drop the raw points.
A concrete example
Say you collect CPU usage from 200 servers every 10 seconds. That is 20 points per second, about 1.7 million per day. A dashboard wants the average CPU per server, per 5 minutes, over the last 6 hours.
In TimescaleDB, which is PostgreSQL with a time-series extension, it looks like this:
CREATE TABLE cpu (
time TIMESTAMPTZ NOT NULL,
host TEXT NOT NULL,
usage DOUBLE PRECISION
);
SELECT create_hypertable('cpu', 'time');
SELECT time_bucket('5 minutes', time) AS bucket, host, avg(usage)
FROM cpu
WHERE time > now() - INTERVAL '6 hours'
GROUP BY bucket, host
ORDER BY bucket;
The table looks normal, but create_hypertable splits it into time chunks behind the scenes. The query touches only the chunks for the last 6 hours, and time_bucket groups points into 5-minute buckets.
The same question in Prometheus, which has its own query language, PromQL:
avg_over_time(cpu_usage[5m])
Graphed over a 6-hour range, Prometheus evaluates this for each step and returns one line per host label.
The main options
- Prometheus: pulls (scrapes) metrics from your services, stores them locally, and is the usual choice for infrastructure and application monitoring. It is designed for recent operational data, not for long-term storage or exact records like billing.
- InfluxDB: a dedicated time-series database that accepts pushed points over HTTP, with its own query languages.
- TimescaleDB: an extension for PostgreSQL. You keep SQL, joins and your existing tools.
- ClickHouse and other column stores: not time-series databases by name, but often used for large volumes of events and logs with time-range queries.
Trade-offs and common mistakes
High cardinality. Every unique tag combination creates a new series. Putting a user ID, request ID or full URL in a tag can create millions of series and exhaust memory, especially in Prometheus. Keep tags for things with a bounded number of values (host, region, status code). Put unbounded values in logs or a column store.
Using it for everything. A time-series database is weak at updates, joins across many entities, and transactions. Your users, orders and invoices still belong in a relational database.
No retention policy. If you never set retention, storage grows forever and queries over "all time" get slower. Decide on day one how long raw data lives and what gets downsampled.
Storing averages only. If you store only per-minute averages, you cannot compute a correct percentile later. Keep raw data long enough, or store histograms instead of averages when you care about latency tails.
Late or out-of-order data. Points that arrive with old timestamps can be awkward for some engines. Check how your choice handles them if your devices buffer data while offline.
Do you need one?
Not always. A PostgreSQL table with an index on (host, time) and table partitioning by month handles a moderate volume well. Reach for a time-series database when the data is mostly append-only metrics or events, the volume keeps growing, and most queries are aggregations over time ranges. If you are already on PostgreSQL, TimescaleDB is a gentle step. For monitoring, Prometheus is the common default.
Watch the animated version: https://youtu.be/M-J7Uvhmiyg
In short
- Time-series data is timestamped measurements that are appended, read by time range and aggregated.
- Time-series databases partition by time, write in sorted batches, compress heavily, and drop or downsample old data.
- Watch tag cardinality, set retention early, and keep business records in a relational database.
- Start with what you have: PostgreSQL plus TimescaleDB, or Prometheus for monitoring, covers most needs.
Originally published at abdeldjalilchougui.biz.
Top comments (0)