AlgoViz

TimescaleDB

medium 25 min

TimescaleDB 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

chunkrowsstorage
week 1700rows
week 2500rows
week 3700rows
week 4300rows

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

dayrawsummary
day 1droppedkept
day 2keptkept
day 91keptkept

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

    critical

    Every chunk must be opened.

    Wrong
    SELECT last(celsius, time) FROM readingsWHERE device_id = 42
    Right
    SELECT last(celsius, time) FROM readingsWHERE device_id = 42  AND time > now() - INTERVAL '1 day'
  • Unique key without time

    major

    Uniqueness is enforced per chunk, so the index is refused.

    Wrong
    CREATE UNIQUE INDEX ON readings (event_id)
    Right
    CREATE UNIQUE INDEX ON readings (event_id, time)
  • Segment by a nearly unique column

    major

    Segments with one row each cannot be compressed together.

    Wrong
    tsdb.segmentby = 'request_id'
    Right
    tsdb.segmentby = 'device_id'
  • Average of averages

    critical

    Hours with few readings count as much as full ones.

    Wrong
    SELECT avg(avg_c) FROM readings_hourly
    Right
    SELECT 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.