Skip to content

1.9 Time Series Databases ​

Tình huống: Bảng metrics trên PostgreSQL có hàng trăm triệu dòng. Query "CPU 1 giờ qua" chậm dần, còn DELETE dữ liệu cũ làm bảng phình và kéo VACUUM dài.

Quy tắc: Chọn TSDB khi dữ liệu chủ yếu là chèn nối đuôi theo thời gian, query theo khoảng thời gian, và cần xoá/gộp dữ liệu cũ theo thời gian. Ngược lại thì PostgreSQL thường đủ.

Vì sao: TSDB ghi nối đuôi (append-only), chia dữ liệu theo khoảng thời gian (chunk/partition) và nén theo cột. Query chỉ chạm chunk liên quan; xoá dữ liệu cũ là bỏ nguyên chunk.

Ví dụ đo thật (TimescaleDB 2.32 trên PostgreSQL 17, 1 triệu dòng, 100 host, đổi theo máy và dữ liệu): bảng thường 4 cột 68 byte/dòng (chỉ heap); hypertable 76 MB còn 10,5 MB sau khi chuyển sang columnstore (khoảng 7,3 lần). Xem khối lệnh ở mục Time-Based Partitioning.

Time Series Database (TSDB) là database tối ưu cho dữ liệu theo thời gian (metrics, IoT sensor, logs). TSDB dùng các kỹ thuật như append-only storage, LSM tree (hoặc cấu trúc tương đương) và delta encoding để chịu tải ghi cao.

Nền tảng về cơ sở dữ liệu chuỗi thời gian ​

Dữ liệu chuỗi thời gian là gì?

text
Characteristics:
- Timestamped data points
- Append-mostly (rarely update old data)
- Recent data accessed more frequently
- Natural ordering by time
- Often regular intervals

Examples:
- Server metrics: CPU, memory, disk every 10s
- IoT sensors: temperature, pressure every 1s
- Stock prices: every tick
- Application logs: every event
- User analytics: page views, clicks

Motivating Example:

text
Cloud monitoring system:
- 100,000 servers
- 5 metrics per server (CPU, memory, disk, network, etc.)
- Every 10 seconds

= 50,000 metrics per second
= 4.32 billion data points per day   (50,000 x 86,400)
= 30.2 billion rows per week

Bảng PostgreSQL ngây thơ (minh hoạ, bảng riêng metrics_plain, khác metrics của hypertable ở mục sau):

sql
-- PostgreSQL 17
CREATE TABLE metrics_plain (
    timestamp   TIMESTAMP,
    host        VARCHAR(255),
    metric_name VARCHAR(255),
    value       DOUBLE PRECISION
);

Vấn đề cần đo, không đoán:

  • Mỗi dòng 4 cột này chiếm khoảng 68 byte heap (đo 1 triệu dòng; chưa tính index và đổi theo máy) trong khi dữ liệu thô chỉ 16 byte (timestamp + float).
  • Tải ghi 50 nghìn dòng/giây là bài toán cho một node PostgreSQL: đo bằng benchmark riêng trên phần cứng của bạn.
  • Query trên hàng tỉ dòng không có partition theo thời gian phải quét index rất lớn.

Popular TSDBs:

text
Database        Type             Best For
─────────────────────────────────────────────────────────────
InfluxDB        Purpose-built    General time series
TimescaleDB     PostgreSQL ext   SQL familiarity
Prometheus      Pull-based       Kubernetes/monitoring
ClickHouse      Column-store     Analytics queries
VictoriaMetrics Performance      High cardinality

Cassandra hay TSDB chuyên dụng ​

Cassandra CÓ THỂ dùng cho time series (wide-row model), nhưng TSDB chuyên dụng thường tiện hơn (downsampling, hàm thời gian). Chọn Cassandra khi cần scale cực lớn, multi-DC và kiểm soát tuỳ biến.

So sánh chi tiết:

text
Tiêu chí             Cassandra                       TSDB (InfluxDB/TimescaleDB)
────────────────────────────────────────────────────────────────────────────────────
Thiết kế             Wide-column đa dụng             Chuyên cho chuỗi thời gian
Nén                  LZ4 mặc định (theo block)       Delta-of-delta + XOR (Gorilla) hoặc
                                                     nén cột; tỉ lệ đổi theo dữ liệu,
                                                     đo bằng dữ liệu của bạn
Ngôn ngữ query       CQL: có sum/avg/min/max/count   PromQL/SQL/InfluxQL, có hàm thời gian
                     nhưng không có time_bucket      (time_bucket, rate, histogram_quantile)
Downsampling         Tự viết job                     Có sẵn (continuous aggregate...)
Retention            TTL từng dòng/cột               Theo chunk/partition thời gian
Scale                Tuyến tính, nhiều DC            Một node tới cluster tuỳ sản phẩm
Multi-datacenter     Replication có sẵn              Cần dựng thêm (Thanos...)
Vận hành             Phức tạp (tinh chỉnh compaction)  Đơn giản hơn

Khi nào chọn Cassandra cho Time Series:

text
Dùng Cassandra khi:
- Tải ghi duy trì vượt khả năng một cluster TSDB mà bạn đã đo thử
- Cần multi-datacenter active-active
- Đã có chuyên môn Cassandra
- Cần nối chuỗi thời gian với dữ liệu Cassandra khác
- Cần logic retention/compaction tuỳ biến

Dùng TSDB khi:
- Workload metrics thông thường
- Cần ngôn ngữ query giàu (PromQL, SQL/InfluxQL)
- Muốn downsampling tự động
- Muốn vận hành đơn giản
- Cần nén hiệu quả (đo tỉ lệ nén trên dữ liệu thật)

Cassandra Time Series Model (nếu chọn Cassandra):

cql
-- Cassandra 5: wide-row model, partition theo metric + ngày, sắp xếp theo timestamp
CREATE TABLE metrics (
    metric_name text,
    date date,
    timestamp timestamp,
    value double,
    tags map<text, text>,
    PRIMARY KEY ((metric_name, date), timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC)
  AND default_time_to_live = 604800  -- 7 ngày
  AND compaction = {
    'class': 'TimeWindowCompactionStrategy',
    'compaction_window_unit': 'DAYS',
    'compaction_window_size': 1
  };

-- Dữ liệu mẫu
INSERT INTO metrics (metric_name, date, timestamp, value, tags)
VALUES ('cpu_usage', '2026-02-12', '2026-02-12 10:30:00', 45.2, {'host': 'host-1'});

-- Giờ vừa qua của cpu_usage (partition hôm nay)
SELECT timestamp, value FROM metrics
WHERE metric_name = 'cpu_usage'
  AND date = '2026-02-12'
  AND timestamp > '2026-02-12 10:00:00';

Ghi nối đuôi (append-only) ​

Vì sao ghi nối đuôi (append-only)?

text
Traditional DB write (random I/O):
[Seek to block 4752] → [Read] → [Modify] → [Write] → [Seek to block 9201] → ...

Problem: Disk seeks are SLOW
- HDD: 100-200 IOPS (physical arm movement)
- SSD: Much faster but still slower than sequential

Append-only write (sequential I/O):
[Write to end] → [Write to end] → [Write to end] → ...

Benefits:
- No seeking
- No read-before-write
- Sequential write nhanh hơn random rõ rệt, nhất là trên HDD; con số cụ thể đổi theo thiết bị, đo bằng fio

Trade-off:

text
Fast writes ✓
But how do we organize data for efficient reads?
→ LSM Trees solve this

LSM Tree (Log-Structured Merge Tree) ​

Điểm cốt lõi:

text
Used by: Cassandra, LevelDB, RocksDB; InfluxDB 1.x/2.x (TSM) là engine riêng, cấu trúc tương tự LSM

Core idea: Transform random writes → sequential writes
          Then reorganize in background for reads

LSM Tree hoạt động thế nào:

text
Step 1: Write to Memory (Memtable)
┌─────────────────────────────┐
│  Memtable (sorted in RAM)   │  ← Writes go here (blazing fast)
│  Red-black tree / Skip list │
└─────────────────────────────┘

Step 2: Flush to Disk (SSTable)
When memtable full:
┌─────────────────────────────┐
│  SSTable (Sorted String     │  ← Sequential write to disk
│  Table) - immutable file    │
└─────────────────────────────┘

Step 3: Background Compaction
Over time, accumulate many SSTables:
┌───┐ ┌───┐ ┌───┐ ┌───┐
│SS1│ │SS2│ │SS3│ │SS4│  → Read might check all files
└───┘ └───┘ └───┘ └───┘
         ↓ Compaction
┌─────────────────┐
│   Merged SST    │  → Fewer files, faster reads
└─────────────────┘

LSM Diagram:

text
Writes → [Memtable] → flush → [Level 0 SSTables]
                               ↓ compaction
                        [Level 1 SSTables]
                               ↓ compaction
                        [Level 2 SSTables]
                               ...

Each level: 10x larger than previous
Compaction: Merge sort, remove duplicates/tombstones

Trade-offs:

text
Pros:
- Writes never block on reads
- Sustained high write throughput
- Background organization

Cons:
- Read might check multiple SSTables
- Write amplification (data rewritten during compaction)
- Compaction uses CPU/IO

Use when: High-write workload AND willing to trade some read performance

Mã hoá delta và nén ​

The Insight:

text
Time series data has unique properties:
- Adjacent values often similar
- Timestamps often regular intervals

CPU usage: 45.2%, 45.3%, 45.1%, 45.4%
           Storing full values wastes space!

Delta Encoding:

text
Raw values:     [45.2] [45.3] [45.1] [45.4]
Delta encoded:  [45.2] [+0.1] [-0.2] [+0.3]

Small deltas = fewer bits needed

Variable-length encoding (varint):
- Number 1 = 1 byte
- Number 1,000,000 = 3 bytes
- Deltas like +1, -2 = 1-2 bytes vs 8 bytes

Result: tỉ lệ nén đổi theo dữ liệu, đo trên dữ liệu thật (ví dụ minh hoạ: Timescale 1M dòng, 76 MB -> 10,5 MB)

Delta-of-delta cho timestamp:

text
Regular 10-second intervals:

Raw timestamps:     1000, 1010, 1020, 1030, 1040
Deltas:             10  , 10  , 10  , 10  , 10  , ...
Delta-of-deltas:    10  , 0   , 0   , 0   , 0   , ...

With regular timestamps: essentially zero overhead for millions of points!

Nén XOR cho giá trị float:

Hai float giống hệt nhau → XOR = 0, chỉ cần 1 bit.
Hai float khác nhau ít bit → chỉ lưu các bit khác nhau.

Đo thật (double 64 bit, Python):
45.23 XOR 45.24 → 22 bit 0 đứng đầu, 1 bit 0 đứng cuối, còn 41 bit có nghĩa
45.25 XOR 45.50 → chỉ 2 bit có nghĩa

Lưu: số bit 0 đứng đầu + các bit có nghĩa
Giá trị đổi chậm hoặc "tròn" (lặp lại, số nguyên, bội của 0,25) → rất gọn
Số lẻ thập phân đổi liên tục → thường tốn nhiều bit

Combined Compression:

text
Typical results:
- Timestamps đều đặn: delta-of-delta = 0 nên mỗi điểm chỉ tốn rất ít bit (bài báo Gorilla: khoảng 96% timestamp nén xuống 1 bit; khoảng 51% giá trị nén xuống 1 bit)
- Tổng (bài báo Gorilla): ~1,37 byte mỗi điểm (timestamp + value)

So với lưu thô: 16 byte (timestamp 8 byte + float 8 byte)
= khoảng 12 lần (16 / 1,37 = 11,7), trên dữ liệu của Facebook; dữ liệu của bạn sẽ khác

Partition theo thời gian (chunk/shard) ​

Vì sao partition theo thời gian?

text
Time series queries almost always include time range:
- "Show CPU usage for last hour"
- "Average response time today"
- "Max temperature this week"

Partitioning by time:
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
│ Jan 1   │ │ Jan 2   │ │ Jan 3   │ │ Today   │
│ (cold)  │ │ (cold)  │ │ (warm)  │ │ (hot)   │
└─────────┘ └─────────┘ └─────────┘ └─────────┘

Benefits:
- Query "last hour" → only read today's partition
- Old data deletion → drop entire partition (instant!)
- Hot data in RAM, cold data on disk/S3

Implementation (TimescaleDB gọi các phần này là "chunks"):

sql
-- PostgreSQL 17 + TimescaleDB 2.32 (chạy một lần; các khối sau dùng lại bảng metrics)
CREATE EXTENSION IF NOT EXISTS timescaledb;

CREATE TABLE metrics (
    time timestamptz NOT NULL,
    host text,
    cpu  double precision
);

-- Tự chia theo thời gian (cú pháp mới by_range)
SELECT create_hypertable('metrics', by_range('time', INTERVAL '1 day'));

-- Dữ liệu mẫu: 1 triệu dòng, 100 host, 2 giây một điểm
INSERT INTO metrics
SELECT now() - (g * 2 || ' seconds')::interval, 'host-' || (g % 100), 45 + random() * 5
FROM generate_series(1, 1000000) g;

-- Query chỉ chạm chunk liên quan
SELECT avg(cpu) FROM metrics
WHERE time > now() - interval '1 hour';
-- EXPLAIN: ChunkAppend chỉ quét chunk có time khớp

Retention Policies:

text
Keep hot data (7 days) → fast storage
Move to warm (30 days) → cheaper storage
Delete cold (>30 days) → or archive to S3

Deletion is trivial: DROP old partitions
vs. DELETE WHERE timestamp < X (vacuum nightmare)
sql
-- TimescaleDB 2.32, chạy sau khối tạo metrics ở mục Time-Based Partitioning
-- Nén chunk cũ (columnstore/Hypercore; tên cũ: compression)
ALTER TABLE metrics SET (
    timescaledb.enable_columnstore,
    timescaledb.segmentby = 'host',
    timescaledb.orderby = 'time DESC'
);
CALL add_columnstore_policy('metrics', after => INTERVAL '7 days');
-- Nén ngay mọi chunk hiện có (policy chỉ nén chunk đủ tuổi, theo lịch)
SELECT count(compress_chunk(c, if_not_compressed => true)) FROM show_chunks('metrics') c;

-- Xoá chunk cũ theo lịch. RISK: drop_chunks xoá vĩnh viễn, thử trên bản sao trước
SELECT add_retention_policy('metrics', INTERVAL '30 days');

Đo thật (1 triệu dòng, sau khi nén mọi chunk bằng compress_chunk): 76 MB trước nén, 10,5 MB sau nén (khoảng 7,3 lần; đổi theo dữ liệu). Lui: remove_retention_policy('metrics') và remove_columnstore_policy('metrics').

Downsampling và rollup ​

The Problem:

text
Raw data: 10-second resolution
- Great for debugging last hour
- Overkill for viewing last year

Query "average CPU for 2023":
- Quét 3,15 triệu điểm cho MỘT series (365 × 8 640), hoặc 3,15 tỉ điểm với 1 000 series: quá nhiều cho một truy vấn thông thường, nên đọc dữ liệu đã downsample.

Downsampling:

text
Automatically reduce resolution of older data:

Raw (10s resolution):     ●●●●●●●●●●●●●●●●●●●●
After 1 week (1min):      ●  ●  ●  ●  ●  ●  ●
After 1 month (1hour):    ●        ●        ●

Store aggregates: min, max, avg, count, sum

Rollup Tables:

text
┌────────────────────────────┐
│  Raw metrics (10s)         │  ← Last 24 hours
│  8,640 points/day/series   │
└────────────────────────────┘
         ↓ aggregate
┌────────────────────────────┐
│  1-minute rollups          │  ← Last 7 days
│  1,440 points/day          │
└────────────────────────────┘
         ↓ aggregate
┌────────────────────────────┐
│  1-hour rollups            │  ← Last 90 days
│  24 points/day             │
└────────────────────────────┘

Query "last year" → use hourly rollups = fast!

Continuous Aggregates (TimescaleDB):

sql
-- TimescaleDB 2.32, chạy sau khối tạo metrics ở mục Time-Based Partitioning
CREATE MATERIALIZED VIEW metrics_hourly
WITH (timescaledb.continuous) AS
SELECT
    time_bucket('1 hour', time) AS hour,
    host,
    avg(cpu) AS avg_cpu,
    max(cpu) AS max_cpu,
    min(cpu) AS min_cpu
FROM metrics
GROUP BY hour, host;

-- Cần chính sách làm mới
SELECT add_continuous_aggregate_policy('metrics_hourly',
    start_offset => INTERVAL '3 hours',
    end_offset => INTERVAL '1 hour',
    schedule_interval => INTERVAL '1 hour');

Mô hình dữ liệu chuỗi thời gian ​

Series and Labels:

text
Traditional model (wide table):
timestamp | host    | cpu  | memory | disk
----------|---------|------|--------|-----
10:00:00  | host-1  | 45.2 | 80.1   | 60.0

Time series model:
Series = metric name + labels (tags)

cpu_usage{host="host-1", region="us-east", env="prod"} 45.2 @10:00:00
memory{host="host-1", region="us-east", env="prod"}    80.1 @10:00:00

Benefits:
- Flexible schema (add labels anytime)
- Query by any label: "all hosts in us-east"
- High cardinality support

Line Protocol của InfluxDB:

text
measurement,tag1=value1,tag2=value2 field1=value1,field2=value2 timestamp

Example:
cpu,host=server1,region=us-east usage=45.2,system=12.1 1609459200000000000

Mô hình lưu trữ (theo cột):

text
Traditional row storage:
[ts1, host1, 45.2] [ts2, host1, 45.3] [ts3, host1, 45.1]

Columnar storage:
timestamps: [ts1, ts2, ts3, ...]  ← compress together
values:     [45.2, 45.3, 45.1, ...]  ← compress together

Benefits:
- Same-type data compresses better
- Read only needed columns
- Vectorized operations

Đường ghi của InfluxDB 3 và Prometheus ​

Hai hệ này KHÔNG dùng memtable/SSTable; mỗi hệ có đường ghi riêng.

text
InfluxDB 3 Core:
  dữ liệu tới -> write buffer (RAM)
  -> flush ra WAL mỗi 1 giây (mặc định; đây là bước bền vững)
  -> mỗi 10 phút (mặc định) đẩy dữ liệu cũ nhất thành file Parquet trên object storage

Prometheus:
  mẫu tới -> head block (RAM) + WAL (chịu crash, replay khi restart)
  -> gom thành block 2 giờ trên đĩa
  -> compaction nền gộp thành block lớn hơn

Mẫu truy vấn chuỗi thời gian ​

Common Operations:

sql
-- PostgreSQL 17 + TimescaleDB 2.32, chạy sau khối tạo metrics ở mục Time-Based Partitioning
-- Aggregation over time
SELECT time_bucket('5 minutes', time) AS bucket,
       avg(cpu)
FROM metrics
WHERE time > now() - interval '1 hour'
GROUP BY bucket
ORDER BY bucket;

-- Rate of change (đơn vị cpu/giây)
SELECT time,
       (cpu - lag(cpu) OVER w) / NULLIF(EXTRACT(EPOCH FROM time - lag(time) OVER w), 0) AS rate
FROM metrics
WHERE time > now() - INTERVAL '1 hour' AND host = 'host-1'
WINDOW w AS (ORDER BY time);

-- Percentiles
SELECT percentile_cont(0.95) WITHIN GROUP (ORDER BY cpu)
FROM metrics
WHERE time > now() - interval '1 day';

-- Moving average (10 điểm gần nhất của host-1)
SELECT time, cpu,
       avg(cpu) OVER (ORDER BY time ROWS BETWEEN 9 PRECEDING AND CURRENT ROW) AS ma_10
FROM metrics
WHERE host = 'host-1'
ORDER BY time;

PromQL (ngôn ngữ truy vấn của Prometheus):

promql
# Rate of HTTP requests per second
rate(http_requests_total{job="api"}[5m])

# 95th percentile latency
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))

# Average CPU across all instances
avg(cpu_usage) by (region)

So sánh các TSDB phổ biến ​

Quick Comparison:

text
Database        Write Perf    Query Lang    Scaling          Best For
────────────────────────────────────────────────────────────────────────
InfluxDB        Very High     SQL/InfluxQL  Cluster (paid)   General metrics
TimescaleDB     High          SQL           PG-based         SQL familiarity
Prometheus      High          PromQL        Federation       K8s monitoring
VictoriaMetrics Very High     PromQL        Cluster          High cardinality
ClickHouse      Very High     SQL           Cluster          Analytics
Cassandra       Very High     CQL           Linear scale     Massive scale

Cột Write Perf là định tính, không phải số đo; đo bằng tải của bạn.

InfluxDB:

text
Architecture (InfluxDB 3): Apache Arrow + DataFusion + Parquet on object storage (TSI/TSM was 1.x/2.x)
- Optimized for time series
- Downsampling via processing engine/scheduled queries (Continuous Queries were 1.x)
- SQL or InfluxQL query language

Best for: General metrics, IoT
Consideration: Core là bản miễn phí; Enterprise (trả phí) thêm high availability và read replicas

TimescaleDB:

text
Architecture: PostgreSQL extension, tự chia hypertable thành chunk
- Full SQL
- Join với bảng PostgreSQL thường
- Continuous aggregates cho rollup
- Columnstore (Hypercore) để nén

Best for: Team đã quen PostgreSQL
sql
-- TimescaleDB 2.32, chạy sau khối tạo metrics ở mục Time-Based Partitioning
SELECT time_bucket('1 hour', time) AS hour,
       host,
       avg(cpu)
FROM metrics
GROUP BY hour, host
ORDER BY hour DESC;

Prometheus:

text
Architecture: Pull-based scraping, local storage
- Designed for Kubernetes monitoring
- PromQL query language
- Short-term storage (15d default)

Best for: Kubernetes, microservices monitoring
Limitation: Single-node, use Thanos/Cortex for long-term/scaling

Khi nào dùng Time Series Database ​

✅ Nên dùng TSDB khi:

- Write throughput cao hơn mức một node PostgreSQL chịu được (đo bằng benchmark riêng)
- Time-range queries dominate
- Regular retention/deletion needed
- Aggregation over time (avg, sum, percentiles)
- Downsampling for historical data

❌ Không nên dùng TSDB khi:

text
- Need complex joins (use PostgreSQL)
- Random access patterns dominate
- Transaction support required
- Ad-hoc analytics across dimensions (use ClickHouse/data warehouse)
- Use case nhỏ (một node PostgreSQL còn dư tải) → PostgreSQL đủ dùng

Lưu ý: có dữ liệu chuỗi thời gian chưa chắc cần TSDB.

text
Ví dụ: bài toán Top-K
- Thoạt nhìn TSDB có vẻ phù hợp
- Nhưng cần sắp xếp/tổng hợp trên số series rất lớn
- Đây không phải việc TSDB tối ưu sẵn; đo trước khi chọn

Lời khuyên: dùng hết khả năng của giải pháp đa dụng trước
            chỉ chuyển sang TSDB khi đo được nút thắt thật

Điểm chính về Time Series DB ​

Tóm tắt:

text
1. Append-only storage: Turn random I/O → sequential I/O
2. LSM trees: High write throughput via background compaction
3. Delta encoding: nén tốt khi giá trị kề nhau gần nhau (Gorilla báo ~12x; Timescale đo 7,3x trên fixture, đổi theo dữ liệu)
4. Time partitioning: Fast queries + trivial retention
5. Downsampling: Trade precision for speed on historical data

Combined: ghi nối đuôi nhanh, query theo khoảng thời gian chỉ quét chunk liên quan (kiểm bằng EXPLAIN)

Mẹo phỏng vấn thiết kế hệ thống:

text
When to mention TSDB:
- Monitoring/metrics system
- IoT sensor data
- Analytics with time dimension

Key points to cover:
- "We'd use append-only writes for throughput"
- "LSM trees handle the write load"
- "Delta encoding compresses similar values"
- "Partition by time for fast queries and retention"
- "Downsample old data for long-term storage"

Phải nhớ:

  • Chia theo thời gian (chunk) làm query hẹp và xoá dữ liệu cũ gần như tức thì.
  • Tỉ lệ nén và tốc độ ghi đổi theo dữ liệu và máy: đo trên dữ liệu của bạn.
  • Chưa vượt PostgreSQL thì chưa cần TSDB.

Tự kiểm: Một series 10 giây/điểm lưu 1 năm có bao nhiêu điểm thô, và bạn sẽ query "trung bình 2023" từ đâu?

Đáp án

365 x 8 640 = 3 153 600 điểm cho một series. Query từ rollup theo giờ (continuous aggregate): 365 x 24 = 8 760 dòng, thay vì quét điểm thô.