🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Time Series Databases

⭐ Premium

Time Series Databases

Time series data is everywhere: metrics from web servers, IoT sensor readings, financial price feeds, application performance traces. Traditional relational databases struggle with these workloads because they are optimised for row-level updates rather than append-heavy, time-ordered streams. Specialised time series databases handle the unique access patterns of temporal data efficiently, providing compression, automatic partitioning, and purpose-built query languages. This lesson compares the three most common choices—InfluxDB, TimescaleDB, and Prometheus—and shows how to implement each with production-ready patterns.

The time series data model

Time series data has a simple structure: a timestamp, one or more numeric fields, and optional tag dimensions that identify the source. A single CPU metric might look like a timestamp, a usage percentage field, and tags for host and region. The simplicity of this schema belies the engineering challenges: high write throughput, time-based partitioning, automatic data retention, and efficient range queries across billions of points.

Time series databases optimise for append-only workloads with automatic partitioning by time, columnar compression that exploits the repetitive nature of metrics, retention policies that drop old data without manual intervention, and continuous aggregates that pre-compute common queries.

FeatureInfluxDBTimescaleDBPrometheus
Data modelPoints with tags and fieldsSQL tables with time columnMetrics with labels
Query languageFlux or InfluxQLSQLPromQL
CompressionBuilt-inColumnarLimited
Best forHigh-cardinality IoT metricsComplex SQL analyticsService monitoring
ScalabilityClusteringMulti-node with extensionsFederation

Choose InfluxDB when you need high write throughput with flexible schemas and are comfortable with a dedicated query language. Choose TimescaleDB when you need SQL, complex joins, or integration with existing PostgreSQL tooling. Choose Prometheus when monitoring Kubernetes or microservices where its pull-based model and PromQL are the standard.

InfluxDB for high-throughput metrics

InfluxDB stores data as points: a measurement name, tags for indexing, fields for values, and a timestamp. The client library below shows batch writes, range queries, and retention policy management—patterns that scale to millions of points per second in production.

python
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS
import pandas as pd
from datetime import datetime, timedelta

class InfluxDBManager:
    def __init__(self, url: str, token: str, org: str, bucket: str):
        self.client = InfluxDBClient(url=url, token=token, org=org)
        self.write_api = self.client.write_api(write_options=SYNCHRONOUS)
        self.query_api = self.client.query_api()
        self.org = org
        self.bucket = bucket

    def write_point(self, measurement: str, tags: dict, fields: dict, timestamp=None):
        point = Point(measurement)
        for tag_key, tag_value in tags.items():
            point = point.tag(tag_key, tag_value)
        for field_key, field_value in fields.items():
            point = point.field(field_key, field_value)
        if timestamp:
            point = point.time(timestamp)
        self.write_api.write(self.bucket, self.org, point)

    def write_batch(self, measurement: str, data_list: list):
        points = []
        for data in data_list:
            point = Point(measurement)
            for tag_key, tag_value in data.get('tags', {}).items():
                point = point.tag(tag_key, tag_value)
            for field_key, field_value in data['fields'].items():
                point = point.field(field_key, field_value)
            if 'timestamp' in data:
                point = point.time(data['timestamp'])
            points.append(point)
        self.write_api.write(self.bucket, self.org, points)

    def query(self, flux_query: str) -> pd.DataFrame:
        tables = self.query_api.query(flux_query, org=self.org)
        results = []
        for table in tables:
            for record in table.records:
                results.append({
                    'time': record.get_time(),
                    'measurement': record.get_measurement(),
                    'field': record.get_field(),
                    'value': record.get_value()
                })
        return pd.DataFrame(results)

    def get_cpu_metrics(self, host: str, hours: int = 24) -> pd.DataFrame:
        query = f'''
        from(bucket: "{self.bucket}")
            |> range(start: -{hours}h)
            |> filter(fn: (r) => r._measurement == "cpu")
            |> filter(fn: (r) => r.host == "{host}")
            |> filter(fn: (r) => r._field == "usage_percent")
            |> aggregateWindow(every: 1m, fn: mean)
        '''
        return self.query(query)

    def downsample(self, measurement: str, from_interval: str, to_interval: str):
        task_name = f"downsample_{measurement}_{from_interval}_{to_interval}"
        flux = f'''
        option task = {{name: "{task_name}", every: {to_interval}}}

        from(bucket: "{self.bucket}")
            |> range(start: -{from_interval})
            |> filter(fn: (r) => r._measurement == "{measurement}")
            |> aggregateWindow(every: {to_interval}, fn: mean, createEmpty: false)
            |> to(bucket: "{self.bucket}", org: "{self.org}")
        '''
        return flux

manager = InfluxDBManager(
    url="http://localhost:8086",
    token="my-token",
    org="my-org",
    bucket="metrics"
)
manager.write_point(
    measurement="cpu",
    tags={"host": "server-01", "region": "us-east"},
    fields={"usage_percent": 75.3, "cores": 8}
)

InfluxDB’s strength is its write performance and flexible schema. Tags are indexed for fast lookups, while fields are stored compressed. The trade-off is that complex analytical queries involving joins across measurements are awkward—use TimescaleDB when you need that flexibility.

TimescaleDB for SQL-native time series

TimescaleDB extends PostgreSQL with hypertables that automatically partition by time, continuous aggregates that pre-compute rollups, and columnar compression that reduces storage by up to 95%. If you already know SQL and need joins with relational data, TimescaleDB is often the simplest choice.

python
import psycopg2
import pandas as pd

class TimescaleDBManager:
    def __init__(self, dbname: str, user: str, password: str, host: str, port: int):
        self.conn = psycopg2.connect(
            dbname=dbname, user=user, password=password,
            host=host, port=port
        )
        self.conn.autocommit = True

    def create_hypertable(self, table_name: str, time_column: str = 'time'):
        with self.conn.cursor() as cur:
            cur.execute(f"""
                SELECT create_hypertable('{table_name}', '{time_column}',
                    if_not_exists => TRUE);
            """)

    def create_continuous_aggregate(self, view_name: str, source_table: str,
                                    time_bucket: str = '1 hour'):
        query = f"""
        CREATE MATERIALIZED VIEW {view_name}
        WITH (timescaledb.continuous) AS
        SELECT
            time_bucket('{time_bucket}', time) AS bucket,
            device_id,
            AVG(temperature) AS avg_temp,
            MAX(temperature) AS max_temp,
            COUNT(*) AS sample_count
        FROM {source_table}
        GROUP BY bucket, device_id;
        """
        with self.conn.cursor() as cur:
            cur.execute(query)

    def add_retention_policy(self, table_name: str, interval: str = '30 days'):
        query = f"""
        SELECT add_retention_policy('{table_name}', INTERVAL '{interval}');
        """
        with self.conn.cursor() as cur:
            cur.execute(query)

    def add_compression(self, table_name: str, compress_after: str = '7 days'):
        query = f"""
        ALTER TABLE {table_name} SET (
            timescaledb.compress,
            timescaledb.compress_segmentby = 'device_id',
            timescaledb.compress_orderby = 'time DESC'
        );

        SELECT add_compression_policy('{table_name}',
            INTERVAL '{compress_after}');
        """
        with self.conn.cursor() as cur:
            cur.execute(query)

    def query_timeseries(self, device_id: str, start_time, end_time,
                         bucket: str = '5 minutes') -> pd.DataFrame:
        query = f"""
        SELECT
            time_bucket('{bucket}', time) AS bucket,
            AVG(temperature) AS avg_temp,
            MAX(humidity) AS max_humidity,
            COUNT(*) AS samples
        FROM sensor_data
        WHERE device_id = %s
          AND time BETWEEN %s AND %s
        GROUP BY bucket
        ORDER BY bucket;
        """
        return pd.read_sql(query, self.conn, params=(device_id, start_time, end_time))

    def detect_anomalies(self, table_name: str, z_threshold: float = 3.0) -> pd.DataFrame:
        query = f"""
        WITH stats AS (
            SELECT
                AVG(temperature) AS mean_temp,
                STDDEV(temperature) AS std_temp
            FROM {table_name}
            WHERE time > NOW() - INTERVAL '24 hours'
        )
        SELECT time, temperature, device_id,
            (temperature - mean_temp) / std_temp AS z_score
        FROM {table_name}, stats
        WHERE ABS((temperature - mean_temp) / std_temp) > {z_threshold}
        ORDER BY time DESC;
        """
        return pd.read_sql(query, self.conn)

db = TimescaleDBManager(
    dbname="metrics", user="admin", password="secret",
    host="localhost", port=5432
)
db.create_hypertable("sensor_data", "time")
db.add_retention_policy("sensor_data", "90 days")
db.add_compression("sensor_data", "7 days")
db.create_continuous_aggregate("hourly_stats", "sensor_data", "1 hour")

Continuous aggregates are TimescaleDB’s killer feature. They automatically refresh in the background as new data arrives, so dashboards querying hourly rollups stay fast without manual ETL. Combined with compression, you can keep years of data queryable without worrying about storage costs.

Prometheus for service monitoring

Prometheus is the de facto standard for monitoring cloud-native applications. It uses a pull-based model where exporters expose metrics on an HTTP endpoint, and Prometheus scrapes them at regular intervals. PromQL provides powerful functions for rate calculations, histogram quantiles, and alerting rules.

python
import requests
from datetime import datetime, timedelta

class PrometheusClient:
    def __init__(self, base_url: str):
        self.base_url = base_url.rstrip('/')

    def query_instant(self, promql: str) -> dict:
        response = requests.get(
            f"{self.base_url}/api/v1/query",
            params={"query": promql}
        )
        return response.json()

    def query_range(self, promql: str, start, end, step: str = "15s") -> dict:
        response = requests.get(
            f"{self.base_url}/api/v1/query_range",
            params={
                "query": promql,
                "start": start,
                "end": end,
                "step": step
            }
        )
        return response.json()

    def get_cpu_usage(self, instance: str, hours: int = 1) -> list:
        promql = f'100 - (avg by(instance) (irate(node_cpu_seconds_total{{instance="{instance}",mode="idle"}}[5m])) * 100)'
        end = datetime.now()
        start = end - timedelta(hours=hours)
        result = self.query_range(promql, start.isoformat(), end.isoformat())
        if result['status'] == 'success':
            return result['data']['result']
        return []

    def get_memory_usage(self, instance: str) -> dict:
        promql = f'(1 - node_memory_MemAvailable_bytes{{instance="{instance}"}} / node_memory_MemTotal_bytes{{instance="{instance}"}}) * 100'
        return self.query_instant(promql)

ALERT_RULES = """
groups:
  - name: ml_system_alerts
    rules:
      - alert: HighPredictionLatency
        expr: histogram_quantile(0.99, rate(ml_prediction_duration_seconds_bucket[5m])) > 0.1
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "High prediction latency"

      - alert: ModelAccuracyDrop
        expr: ml_model_accuracy < 0.85
        for: 10m
        labels:
          severity: critical
        annotations:
          summary: "Model accuracy below threshold"
"""

Prometheus excels at operational monitoring but is not designed for long-term storage of high-cardinality business metrics. For those, pair it with Thanos or Cortex for long-term retention, or use InfluxDB or TimescaleDB for application-level time series.

Query patterns and feature engineering

Once data is stored, the next challenge is extracting useful features for machine learning. Rolling statistics, lag features, and exponential moving averages are the building blocks of time series feature engineering.

python
import pandas as pd

def resample_timeseries(df: pd.DataFrame, rule: str = '5T', method: str = 'mean') -> pd.DataFrame:
    df.index = pd.to_datetime(df.index)
    return df.resample(rule).agg(method)

def rolling_features(df: pd.DataFrame, windows: list = [7, 14, 30]) -> pd.DataFrame:
    features = pd.DataFrame(index=df.index)
    for window in windows:
        features[f'rolling_mean_{window}'] = df['value'].rolling(window).mean()
        features[f'rolling_std_{window}'] = df['value'].rolling(window).std()
        features[f'rolling_min_{window}'] = df['value'].rolling(window).min()
        features[f'rolling_max_{window}'] = df['value'].rolling(window).max()
    return features

def lag_features(df: pd.DataFrame, lags: list = [1, 7, 14, 30]) -> pd.DataFrame:
    features = pd.DataFrame(index=df.index)
    for lag in lags:
        features[f'lag_{lag}'] = df['value'].shift(lag)
    return features

def ewm_features(df: pd.DataFrame, spans: list = [7, 14, 30]) -> pd.DataFrame:
    features = pd.DataFrame(index=df.index)
    for span in spans:
        features[f'ewm_{span}'] = df['value'].ewm(span=span).mean()
    return features

Always compute features within each entity group to avoid leakage across devices or users. Rolling windows should respect time boundaries, not row counts, especially when data has gaps or irregular sampling.

For anomaly detection on time series, z-score methods work well when the distribution is roughly stationary, but many real-world signals exhibit seasonality and trend. In those cases, use seasonal decomposition or a model such as Prophet to isolate the residual before computing anomaly scores, or apply an isolation forest on a feature matrix built from the rolling and lag transforms above.

Feature stores for time series also need special consideration. Unlike batch features that can be precomputed offline, many time series features are needed in real time at inference—for example, the trailing seven-day average at the moment a prediction is requested. Building a feature store that supports both historical point-in-time joins for training and low-latency online reads for serving is one of the more subtle engineering challenges in production time series systems.

Production deployment patterns

In production, separate ingestion from query workloads. Use write buffers or message queues like Kafka to absorb bursty writes, then batch-write to the database. For reads, pre-compute aggregates in continuous aggregates or materialised views rather than querying raw points on dashboards.

Set retention policies aggressively for raw data. Keep full-resolution data for the period you actively investigate (often 7 to 30 days), downsample older data to hourly or daily aggregates, and archive anything older to object storage. This tiered approach keeps query performance high while controlling costs.

Monitor the database itself. InfluxDB and TimescaleDB both expose internal metrics; track write latency, query latency, storage growth, and compression ratios. Alert when write buffers fill or when query latency exceeds your service level objectives.

Schema design deserves careful attention in time series databases. InfluxDB’s schema-on-write model means you decide at write time whether a value is a tag (indexed, low cardinality) or a field (stored, high cardinality). Misclassifying a high-cardinality identifier as a tag will degrade query performance and bloat the index. TimescaleDB, being PostgreSQL, uses a more traditional schema-on-read approach, but you still need to choose appropriate column types and indexes for time and device_id.

Backfilling historical data is another operational pattern. When you add a new sensor or import a legacy dataset, you may need to write billions of points at once. Batch writes in chunks, use asynchronous write APIs where available, and monitor memory usage to avoid overwhelming the database. For TimescaleDB, copy operations or multi-row inserts are significantly faster than individual INSERT statements.

High availability and clustering are deployment concerns that grow with data volume. InfluxDB OSS supports single-node deployments, while InfluxDB Cloud or Enterprise adds clustering and replication. TimescaleDB uses PostgreSQL’s streaming replication, with multi-node extensions for distributing hypertables across shards. Choose the deployment model that matches your availability requirements and budget, and test failover procedures before you need them.

Data lifecycle management ties all of these patterns together. A well-designed time series pipeline has clear ownership of each stage: ingestion validates and buffers, storage compresses and partitions, query layers serve pre-aggregated views, and archival moves cold data to cheap storage. Document the lifecycle so that on-call engineers know where to look when a metric goes missing.

Common Mistakes

Storing unbounded high-cardinality tags that explode storage and query times

Fix: Limit tag cardinality, use controlled vocabularies, and move truly high-cardinality identifiers to fields if they are not needed for indexing.

Querying raw high-frequency points for dashboards instead of pre-aggregated rollups

Fix: Create continuous aggregates or materialised views for common dashboard queries and point dashboards at those.

No retention policy, leading to unbounded storage growth

Fix: Define retention policies at table or bucket creation time and review storage metrics regularly.

Best Practices

  • Batch writes through a message queue to absorb bursty ingestion
  • Pre-compute aggregates for dashboards rather than querying raw points
  • Set retention policies and downsampling tiers at design time, not after storage fills
  • Choose SQL-native TimescaleDB when you need joins with relational data
  • Monitor write latency, query latency, and compression ratios as first-class metrics

Key Takeaways

  • Time series databases optimise for append-only, time-ordered workloads with compression and automatic partitioning
  • InfluxDB provides high write throughput with flexible schemas; TimescaleDB brings SQL and continuous aggregates
  • Prometheus is the standard for service monitoring with PromQL and pull-based scraping
  • Feature engineering on time series must respect temporal boundaries to avoid leakage
  • Tiered retention with downsampling keeps query performance high while controlling storage costs
🔒

Premium Content

Time Series Databases

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
💼Interview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Advertisement