Video in progress
IoT devices send 100 thousand measurements per second. How do you store them, and how do you make a "last 30 days chart" query fast?
This is time-series data: append-only, read by time range, and the old data matters less. Kafka as a buffer at ingestion, a time-partitioned columnar or time-series database for storage, and for charts precomputed minute and hour aggregates plus a retention policy.
📖 Answer
First the numbers: 100,000 measurements/s × ~40 bytes ≈ 4 MB/s, about 350 GB of raw data per day, over 100 TB per year. Writing every measurement into a plain Postgres table with a B-tree index will soon choke on index updates and vacuum.
- Ingestion. Devices send to a gateway over MQTT or HTTP, and from there to Kafka. The key is
deviceId, so one device's measurements stay in order. If the store slows down, Kafka acts as the buffer. - Batch writes. The consumer collects 5,000 at a time and sends them in one write.
- Storage. TimescaleDB (inside Postgres, so you keep SQL and JOINs) or ClickHouse (very fast aggregation, compression often better than 10x). If the team knows Postgres well, I start with TimescaleDB; if the analytical queries are heavy, ClickHouse.
CREATE TABLE readings (
device_id UInt64,
ts DateTime64(3),
metric LowCardinality(String),
value Float64
) ENGINE = MergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (device_id, metric, ts)
TTL toDateTime(ts) + INTERVAL 90 DAY;
- Downsampling. A 30-day chart doesn't need 2.6 million points, since the screen has about a thousand pixels. Minute and hour aggregates (min/max/avg) are written by a materialized view, and the chart query picks the right table based on the range.
- Retention. Raw data for 90 days, minute aggregates for 1 year, hourly for the long term. Old partitions are dropped whole or moved to cheap storage.
Subtle points:
- a device clock can be wrong, so store the measurement time and the receive time separately;
- an offline device sends an hour of data all at once, and late-arriving records force you to recompute aggregates;
- "the latest value of each device" should live in a separate small table or in Redis; you shouldn't find it by scanning millions of rows.
Sign up to mark studied questions and save your progress.