TimescaleDB
medium 25 minTimescaleDB is a PostgreSQL extension for time-series and event data.
See it run
Cut by time, read few chunks, turn old rows into columns and keep summaries fresh.
Operations
Route inserts to chunks
Four weekly chunks. Today is in week 4.
Step 1 of 5
Four chunks
| chunk | rows | storage |
|---|---|---|
| week 1 | 700 | rows |
| week 2 | 500 | rows |
| week 3 | 700 | rows |
| week 4 | 300 | rows |
1 hypertable, 4 chunks
Each holds 7 days, the default interval.
Step 1: Four chunks
def insert(row): start = row.time - row.time % interval chunk = chunks.get(start) or create_chunk(start) chunk.heap.append(row) for index in chunk.indexes: index.add(row)- Work
- 1 chunk
- Watch out for
- Too many chunks
- One giant table
- Huge indexes
Only the newest chunk's indexes need to be in memory for writing.
In the real world
The same timescaledb doing real jobs. Pick one and step through it.
Raw rows are kept 90 days. Summaries should live for years.
Step 1 of 3
Day 91
| day | raw | summary |
|---|---|---|
| day 1 | dropped | kept |
| day 2 | kept | kept |
| day 91 | kept | kept |
As intended
Retention drops the raw chunk of day 1. The summary of day 1 stays.
Step 1: Day 91
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No time filter
criticalEvery chunk must be opened.
WrongSELECT last(celsius, time) FROM readingsWHERE device_id = 42RightSELECT last(celsius, time) FROM readingsWHERE device_id = 42 AND time > now() - INTERVAL '1 day'Unique key without time
majorUniqueness is enforced per chunk, so the index is refused.
WrongCREATE UNIQUE INDEX ON readings (event_id)RightCREATE UNIQUE INDEX ON readings (event_id, time)Segment by a nearly unique column
majorSegments with one row each cannot be compressed together.
Wrongtsdb.segmentby = 'request_id'Righttsdb.segmentby = 'device_id'Average of averages
criticalHours with few readings count as much as full ones.
WrongSELECT avg(avg_c) FROM readings_hourlyRightSELECT sum(total) / sum(n) FROM readings_hourly_sums
Interview tips
How to explain it
- One table, cut by time.
- Recent rows, older columns.
- Drop whole chunks.
Design order
- Rows per second and retention.
- Chunk interval from memory.
- Rollups from the dashboard.
Reach for it when
- Queries filter on time.
- You want SQL and joins.
- One primary is enough.
Choose something else when
- Time is not in the query.
- Rows change for months.
- Writes exceed one machine.