SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Relational Databases
  • Document Databases
  • Key-Value Databases
  • Full-Text Search Engines
  • Wide Column Databases
  • Time Series Databases
  • Graph Databases
  • Vector Databases
  • NewSQL Databases
  • Columnar Databases
  • In-Memory Databases
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Types (Deep Dive)

Time Series Databases

Built for data stamped with time: metrics, sensors and logs (InfluxDB, TimescaleDB).

⏱ 12 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A time series database (TSDB) is built for data where every row has a timestamp: CPU use every 10 seconds, the temperature from a sensor, the price of a stock, a log line.

  • Data arrives in time order, is almost always appended, and is rarely changed.
  • Queries ask about time ranges: "the last 15 minutes", "the average per hour this week".
  • The database gives you fast writes, strong compression, time buckets, downsampling and retention (auto-delete of old data).
  • Well known examples: InfluxDB, TimescaleDB, Prometheus, Apache Druid, Amazon Timestream.

02Concept: What is it?

Think of a series as one line on a graph over time, such as "CPU of server A". A TSDB stores millions of these lines. Each point has a timestamp, a value (a number you measure) and tags (labels such as host=a, region=eu that say which line it belongs to).

You can store this in a normal SQL table, and for small data that is fine. At large scale the pattern is special: huge write volume, data that is never updated, and queries that always cut by time. A TSDB uses this pattern. It groups data by time, compresses neighbouring values (they are usually close to each other), and drops old data cheaply by removing a whole time chunk at once.

What one data point looks like
🏷️Tagshost=web-1, region=eu
→↓+
🕒Timestamp2026-03-01 14:12:10
→↓+
📈Value(s)cpu=87.5
→↓=
📍One pointin one series
Tags say which series. The timestamp and value say what happened and when.
🧠Three habits of time series data
Append-only (new points, no edits), time-ordered (the newest is the most useful), and queried by range (not by one row id).

03Real-Life Example

🍵The Hospital Bedside Monitor
A monitor beside a hospital bed records a heartbeat every second. Nurses look at the last hour in detail. The doctor looks at the day as one smooth line. Last year's record is kept only as one number per day. Nobody asks for "the heartbeat row with id 91,284".
Bedside monitor
Time series database
A heartbeat reading every second
A point with a timestamp (high write rate)
Patient and bed number on the chart
Tags that name the series
Looking at the last hour in detail
Query a recent time range on raw data
One smooth line for the whole day
Downsampling: average per minute or hour
Old charts reduced to one number per day
Rollups kept long after raw data is deleted
Shredding paper records after 30 days
Retention policy that drops old chunks
An alarm if the heart rate goes too high
Alert rule on a query (max over a window)
Detail fades with age
🔬Todayevery second
→↓after 7 days
📊Last month1 minute buckets
→↓after 90 days
📅Last year1 hour buckets
→↓after 2 years
🗑️Deleted

04Why Do We Need It?

✍️Huge write speed
Millions of points per second arrive from servers and sensors. A TSDB batches and appends them cheaply.
🗜️Small on disk
Neighbouring timestamps and values are alike, so they compress very well, often many times smaller than raw rows.
⏱️Fast time queries
Data is stored in time order and in chunks, so a query for the last hour skips the rest.
🧹Easy clean-up
Dropping a whole old chunk is quick. Deleting millions of single rows from a normal table is slow.
🧮Built-in time maths
Buckets, moving averages, rates and gap filling are one function call.
🔔Monitoring and alerts
Dashboards and alerting tools speak to TSDBs directly.
When most of your data is "something measured at a time", use a store that is shaped like time.

05Where Do We Use It?

🖥️Infrastructure monitoring
CPU, memory, disk and request rate for every server and container.
🏭IoT and sensors
Temperature, vibration and GPS from machines, cars and smart meters.
💹Finance
Stock ticks, trades and order books.
📱App analytics
Clicks, sessions and page timings over time.
⚡Energy and utilities
Smart meter readings and grid load.
🧾Logs and traces
Event streams that you search by time.

06Types / Parts / How It Works

How a TSDB is organised

Write path and chunks
📡Agents / sensorssend points
→↓
📝Write-ahead log + memoryfast append
→↓flush
Disk, one chunk per time range
Moncompressed
Tuecompressed
Wedcompressed
Olddrop whole
Writes land in memory and a log, then are flushed into time-ordered, compressed chunks. Old chunks are dropped whole.
IdeaWhat it doesExample
Time partitioning (chunks)Splits data into pieces by time range, so queries and deletes touch only some chunks.TimescaleDB hypertables, InfluxDB shards
Time bucketGroups points into fixed windows and gives one value per window.time_bucket('5 minutes', ts), GROUP BY time(5m)
Downsampling / rollupStores a smaller summary (avg, min, max, count) of old data.Continuous aggregates, Flux tasks
Retention policyDeletes data older than a set age.Keep raw 7 days, keep hourly 1 year
CompressionStores the difference between neighbours instead of full values.Delta-of-delta timestamps, Gorilla-style floats
CardinalityHow many different series exist (the number of tag combinations).1000 hosts x 50 metrics = 50,000 series
Purpose-built TSDB
InfluxDB, Prometheus, Druid
  • Made for high write rates
  • Time functions built in
  • Own query language
  • Usually limited for general data and joins
Time series on SQL
TimescaleDB (PostgreSQL extension)
  • Full SQL and joins
  • Works with existing Postgres tools
  • Chunks and compression added on top
  • Heavier than a pure TSDB at extreme scale
Example in SQL (TimescaleDB style, general idea)
SELECT time_bucket('5 minutes', ts) AS bucket,
       host,
       avg(cpu) AS avg_cpu,
       max(cpu) AS max_cpu
FROM metrics
WHERE ts > now() - interval '6 hours'
GROUP BY bucket, host
ORDER BY bucket;
VisualizerFrom raw points to buckets, rollups and retentionPick a bucket size, then switch Average to Max and watch the 14:12 spike. Move the window, then change how long raw data is kept.
Bucket size (time_bucket / GROUP BY time)
Aggregate inside each bucket
CPU % of one server. Faint grey = every 10 second reading, cyan steps = avg per 5 minutes. The 40 second spike at 14:12 is easy to lose.
12:0015:0018:00
Raw points in window
2.2k
After bucketing
72
30 to 1
Peak seen
60%
raw peak 94%
Stored points (one series)
84.4k
raw only would be 777.6k
Storage saved
89%
retention + downsampling
The average hides the spike. Raw peak is 94% but the buckets only reach 60%. Try Max to keep the peak visible.

A simplified model: one series, one reading every 10 seconds, fixed data made by maths (no random numbers). Real systems also compress points (for example delta-of-delta on timestamps), so real storage is much smaller than this point count suggests.

07How to Use It / Steps / Implementation

Designing a time series store

  1. 1
    Pick what you measure
    Name the metrics (cpu, temp, price) and decide the sampling rate. Every 10 seconds is very different from every millisecond.
  2. 2
    Choose tags carefully
    Tags such as host and region are indexed and define a series. Never put unbounded values (user id, request id, full URL) in tags.
  3. 3
    Write in batches
    Send many points per request. One HTTP call per point is slow for both sides.
  4. 4
    Set retention
    Decide how long raw data is useful. For example keep raw for 7 days, 1 minute rollups for 90 days, hourly for 2 years.
  5. 5
    Create rollups early
    Aggregate old data into buckets before the raw data is deleted. Store sum and count, so averages can still be rebuilt.
  6. 6
    Query with a time range always
    A query without a time filter reads every chunk. Always say from when to when.
  7. 7
    Watch cardinality
    Track the number of series. It, more than the number of points, is what usually breaks a TSDB.
⚠️High cardinality is the classic killer
If you tag points with something that has millions of values (like a user id), you create millions of series. The index grows huge and memory runs out. Put such values in a normal field, or in another store.
Typical order of importance when sizingseries count, then write rate, then total points

08Key Terms to Know

TermMeaning in easy words
Time seriesA list of values measured over time, one after another
Point / sampleOne measurement with a timestamp
SeriesAll points that share the same metric name and tags
Tag / labelAn indexed key=value that says which series a point belongs to
Field / valueThe measured number (or numbers) in a point
CardinalityThe number of different series
DownsamplingReplacing many points with fewer summary points
Retention policyA rule that deletes data after a set age
Time bucketA fixed time window, such as 5 minutes, used for grouping
Hypertable / chunkA table that is silently split into time-range pieces

09Pros, Cons and Trade-offs

✅ Pros
  • Very high write throughput
  • Strong compression, low storage cost
  • Fast range queries and time maths
  • Cheap retention and clean-up
  • Great fit for dashboards and alerts
⚠️ Cons
  • Weak at updates and deletes of single points
  • High cardinality can cause memory trouble
  • Limited joins and general queries in purpose-built engines
  • Downsampling loses detail for good
  • Another system to run and learn

Trade-offs

ChoiceWe gainWe lose
Keep raw data longerFull detail for investigationsMore storage and slower old queries
Bigger rollup bucketsMuch less storageShort spikes are hidden (use max as well as avg)
More tagsMore ways to filter and groupMore series, more memory
Purpose-built TSDBBest speed and size for metricsPoor general-purpose querying
TSDB on SQLOne system, full SQLLess extreme write scale

10Common Problems and Mistakes

Common mistakes

  1. Using unbounded tags. A request id or user id as a tag creates a series for each one.
  2. Keeping everything forever. Storage and query cost grow with no end.
  3. Only averaging when rolling up. Spikes disappear. Also keep max, min and count.
  4. Querying without a time range. The query scans all chunks.
  5. One write per point. Network and commit costs dominate. Batch the writes.
  6. Averaging averages. An average of averages is wrong when buckets have different counts. Store sum and count.

Things to watch

⏰Late and out-of-order data
A device that was offline sends old points later. Decide if the database accepts them.
🕳️Gaps
Missing readings can look like zero. Know how your tool fills gaps.
🌍Time zones and clocks
Store UTC. Clock drift between machines can reorder points.
💥Cardinality explosions
A new label in a deploy can multiply the series count overnight.

11Real-World Examples

📊Prometheus
Pulls metrics from services and stores them locally. Very common for Kubernetes monitoring.
🌊InfluxDB
A purpose-built TSDB with its own query languages, used for metrics, IoT and analytics.
🐘TimescaleDB
A PostgreSQL extension that adds time chunks, compression and continuous aggregates.
☁️Cloud services
Amazon Timestream, Azure Data Explorer and Google Cloud Monitoring offer managed time series storage.
🚗Connected devices
Fleets of cars and meters send telemetry that is stored per device and time.
💹Trading systems
Tick data is stored in specialised time-ordered stores for fast replay and analysis.
📝Note
These are general ideas. Features and limits differ between products and versions.
Mini case: a monitoring pipeline
🖥️1000 serversmetrics every 10 s
→↓batched writes
🗄️TSDBraw 7 d, hourly 1 y
→↓queries
📈Dashboards
🔔Alerts
Sources Storage Users
Agents send points, the TSDB stores and rolls them up, and dashboards and alerts read from it.

12Related Topics to Read Next

Common Database Types→

Where time series fits among the other kinds of database.

LSM Trees→

The write-optimised structure many TSDBs build on.

Partitioning→

Time chunks are partitioning by time range.

Wide Column Databases→

Another store used for very large append-heavy data.

Indexing→

Tags are indexed, and the cost of that index drives cardinality limits.

Message Queues→

Often sit in front of a TSDB to absorb bursts of writes.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: a database for points with timestamps (metrics, sensors, logs).
  • ✔Shape: append-only, time-ordered, queried by time range.
  • ✔Parts: tags name the series, a timestamp, and the measured values.
  • ✔Tools: time buckets, downsampling and retention keep it small and fast.
  • ✔Layout: time chunks, compressed, dropped whole when old.
  • ✔Danger: high cardinality (too many series) and averaging away spikes.
  • ✔Examples: InfluxDB, TimescaleDB, Prometheus, Druid.
  • ✔One line: “Store measurements by time, keep detail for a short while, and keep summaries for long.”
← Previous
Wide Column Databases
Next →
Graph Databases