Skip to content
All insights
Featured

engineering//10 min read

High-Throughput Time-Series Architectures: TimescaleDB vs. ClickHouse for IoT Telemetry

An architectural comparison of TimescaleDB hypertables versus ClickHouse MergeTree engines for 100,000+ events/sec IoT workloads: compression ratios, continuous aggregation rollups, query latency, and relational ergonomics.

Sameer BagwanCTO & Co-Founder
High-throughput enterprise telemetry server racks and distributed database storage clusters

In short

  • Ingestion patterns dictate storage layout: TimescaleDB optimizes for ACID writes with chunk-based partitioning, while ClickHouse excels at wide, columnar bulk block writes.
  • ClickHouse delivers 4x to 6x higher compression efficiency using specialized column codecs (DoubleDelta, Gorilla, ZSTD) compared to row-oriented engines.
  • Materialized continuous aggregates in TimescaleDB allow seamless real-time relational JOINs, whereas ClickHouse requires asynchronous AggregatingMergeTrees.
  • For sub-50k events/sec with strict relational foreign keys, TimescaleDB minimizes operational overhead; above 100k events/sec or petabyte scale, ClickHouse's columnar engine dominates.

Industrial IoT platforms, connected vehicle telemetry systems, and smart grid monitoring networks generate massive streams of time-series data. In modern enterprise IoT deployments, fleets of hundreds of thousands of edge devices continuously stream high-frequency sensor readings—vibration harmonics, temperature curves, voltage drops, and GPS coordinates—routinely generating write throughputs between 100,000 and 1,000,000 metrics per second.

At this velocity, traditional relational database architectures collapse under write amplification, index thrashing, and table lock contention. Engineering teams face an architectural crossroads: should they leverage TimescaleDB, which extends PostgreSQL with partitioned hypertables and seamless relational JOIN ergonomics, or should they deploy ClickHouse, the specialized columnar analytical database engine optimized for vectorized SIMD query execution and massive ingestion throughput?

This technical deep dive evaluates the architectural trade-offs, storage primitives, compression codecs, continuous rollup mechanisms, and query performance profiles of TimescaleDB and ClickHouse under continuous 100k+ events/sec production workloads.

The Telemetry Ingestion Bottleneck at 100k Events/Sec

To understand why specialized time-series architectures are necessary, consider what occurs inside a standard PostgreSQL instance receiving 100,000 raw sensor events per second. Each metric payload represents a small 64-byte row containing a timestamp, a device UUID, a metric name string, and a float64 measurement value.

  • B-Tree Index Thrashing: In a standard table, indexes on (device_id, recorded_at) are implemented as balanced B-Trees. As rows accumulate into hundreds of millions, index size rapidly exceeds available RAM. Ingestion shifts from fast sequential writes to random IOPS page lookups, causing disk queues to saturate and write latency to spike.
  • Write Amplification & WAL Overhead: In Postgres, writing a 64-byte row triggers a write-ahead log (WAL) write and marks an 8KB table buffer page as dirty. Scattered device writes force the database to write entire 8KB pages repeatedly, generating severe write amplification.
  • Table Bloat & Autovacuum Exhaustion: High-velocity write streams generate severe multi-version concurrency control (MVCC) bloat. PostgreSQL's autovacuum processes struggle to scan billion-row tables without starving client queries of IO bandwidth.
At 100,000 metrics per second, an IoT system generates 8.64 billion rows daily. A database that cannot prune billions of old rows via instant file metadata operations will inevitably collapse under maintenance lock contention.

Architectural Divergence: Chunked Hypertables vs. Columnar MergeTree

TimescaleDB and ClickHouse solve the time-series ingestion problem using fundamentally different storage paradigms:

  • TimescaleDB: Hypertable Chunk Partitioning: TimescaleDB functions as a PostgreSQL extension. It exposes a single virtual table (the Hypertable) that automatically partitions incoming data into physical PostgreSQL tables called chunks, typically partitioned by time (e.g., 1-day chunks) and optionally by space (hash of device ID). Chunks keep B-Tree indexes small enough to reside in RAM. Dropping data older than 90 days requires zero row deletes: TimescaleDB executes an instantaneous DROP TABLE metadata command on expired chunk tables.
  • ClickHouse: Vectorized Columnar MergeTree: ClickHouse is a standalone columnar analytical database written in C++. It discards row-oriented storage entirely. Data is written in immutable physical blocks called parts, organized by column files (.bin) and sparse index marks (.mrk). In the background, ClickHouse continuously merges small parts into larger consolidated parts using a Log-Structured Merge (LSM) algorithm. Because each column is stored in its own separate file on disk, analytical aggregations scan only the exact columns requested by the query.
Architectural pipeline diagram contrasting Kafka ingestion, TimescaleDB hypertable chunking, and ClickHouse columnar MergeTree storage engines
Figure 1: The End-to-End Telemetry Ingestion Pipeline — Highlighting the structural contrast between chunked row storage and vectorized columnar parts.

As illustrated in Figure 1, the choice between these engines determines how your query engine accesses disk. TimescaleDB preserves full relational ACID compliance, allowing developers to execute foreign key JOINs against asset registries, customer tenant tables, and maintenance tickets within standard SQL transactions. ClickHouse trades away transactional write isolation in exchange for raw vectorized query execution capable of processing billions of data points per second using CPU SIMD instructions.

Compression Mechanics: Row Hybrids vs. Specialized Column Codecs

Storing billions of IoT data points uncompressed is economically infeasible. Both engines implement sophisticated time-series compression algorithms, but their underlying mechanisms differ significantly:

TimescaleDB Compression

TimescaleDB incorporates an automated compression policy that converts older, row-oriented chunks into a specialized columnar format inside PostgreSQL. TimescaleDB reorganizes rows into arrays of up to 1,000 elements grouped by a segment column (e.g., device_id). Timestamps are compressed using Delta-of-Delta encoding, while floating-point metrics are compressed using the Gorilla compression algorithm. This reduces raw disk footprint by 6x to 10x, but once a chunk is compressed, standard in-place UPDATE operations require automatic chunk decompression or manual backfill workflows.

ClickHouse Columnar Codecs

Because ClickHouse is natively columnar, compression is configured on a per-column basis directly in the DDL. ClickHouse supports a rich taxonomy of specialized hardware-accelerated codecs:

  • DoubleDelta: Computes the difference between consecutive deltas. For monotonically incrementing sensor clocks, the delta-of-delta is zero for 99% of entries, compressing timestamps to fraction of a bit per row.
  • Gorilla & FPC: Specialized floating-point compression algorithms that XOR consecutive 64-bit float mantissas and bit-pack identical prefixes, yielding dramatic compression for smooth physical sensor metrics.
  • LowCardinality & Dictionary: Replaces repetitive strings (e.g., metric names or status codes) with 8-bit or 16-bit integer pointers.
  • ZSTD: Fast general-purpose compression applied as a secondary layer over the encoded bitstream.

Below is a comparison of production DDL schemas configuring high-performance storage and compression policies in both systems:

sql
-- ============================================================
-- 1. TIMESCALEDB SCHEMA DEFINITION (PostgreSQL Extension)
-- ============================================================
CREATE TABLE telemetry_raw (
    recorded_at TIMESTAMPTZ NOT NULL,
    device_id   UUID NOT NULL,
    metric_name TEXT NOT NULL,
    metric_val  DOUBLE PRECISION NOT NULL,
    metadata    JSONB DEFAULT '{}'::jsonb
);

-- Convert standard table into a partitioned Hypertable (1-day chunks)
SELECT create_hypertable('telemetry_raw', 'recorded_at', chunk_time_interval => INTERVAL '1 day');

CREATE INDEX idx_telemetry_device_time ON telemetry_raw (device_id, recorded_at DESC);

-- Enable TimescaleDB hybrid columnar compression policy
ALTER TABLE telemetry_raw SET (
    timescaledb.compress,
    timescaledb.compress_segmentby = 'device_id, metric_name',
    timescaledb.compress_orderby = 'recorded_at DESC'
);

SELECT add_compression_policy('telemetry_raw', INTERVAL '2 days');

-- ============================================================
-- 2. CLICKHOUSE SCHEMA DEFINITION (Vectorized Columnar DDL)
-- ============================================================
CREATE TABLE telemetry_raw (
    recorded_at DateTime64(3, 'UTC') CODEC(DoubleDelta, ZSTD(1)),
    device_id   UUID                 CODEC(ZSTD(1)),
    metric_name LowCardinality(String),
    metric_val  Float64              CODEC(Gorilla, ZSTD(1)),
    metadata    Map(String, String)  CODEC(ZSTD(3))
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(recorded_at)
ORDER BY (device_id, metric_name, recorded_at)
SETTINGS index_granularity = 8192;

Continuous Materialized Rollups & Downsampling

In industrial telemetry, raw 1-second data loses operational relevance after a few days. Engineers rarely need 1-second resolution when analyzing sensor degradation trends across six months. Instead, they require downsampled rollups: 1-minute, 1-hour, and 1-day statistical aggregations (min, max, average, count, p95, p99).

TimescaleDB Continuous Aggregates

TimescaleDB provides Continuous Aggregates, which are materialized views that automatically downsample hypertable data in the background. Crucially, TimescaleDB offers Real-Time Aggregates: when an analytical query hits a continuous aggregate view, the query engine automatically reads pre-computed historical aggregates from the materialized view and combines them with un-materialized raw rows from active write chunks on the fly.

ClickHouse AggregatingMergeTree

ClickHouse handles real-time rollups using the specialized AggregatingMergeTree engine paired with synchronous materialized views. In ClickHouse, a materialized view functions as an insert trigger: whenever a batch of raw telemetry is inserted into telemetry_raw, the view executes aggregation combinators (-State functions) and appends intermediate aggregate state directly into the rollup table.

sql
-- ============================================================
-- 1. TIMESCALEDB CONTINUOUS AGGREGATE (1-Hour Rollup)
-- ============================================================
CREATE MATERIALIZED VIEW telemetry_hourly_cagg
WITH (timescaledb.continuous) AS
SELECT
    time_bucket('1 hour', recorded_at) AS bucket,
    device_id,
    metric_name,
    COUNT(*) AS sample_count,
    AVG(metric_val) AS avg_value,
    MAX(metric_val) AS max_value,
    MIN(metric_val) AS min_value
FROM telemetry_raw
GROUP BY bucket, device_id, metric_name
WITH NO DATA;

SELECT add_continuous_aggregate_policy('telemetry_hourly_cagg',
    start_offset => INTERVAL '3 days',
    end_offset   => INTERVAL '1 hour',
    schedule_interval => INTERVAL '30 minutes');

-- ============================================================
-- 2. CLICKHOUSE AGGREGATING MERGETREE (1-Hour Rollup)
-- ============================================================
CREATE TABLE telemetry_hourly_rollup (
    bucket_hour DateTime64(0, 'UTC') CODEC(DoubleDelta, ZSTD(1)),
    device_id   UUID                 CODEC(ZSTD(1)),
    metric_name LowCardinality(String),
    samples     UInt32,
    avg_state   AggregateFunction(avg, Float64),
    max_state   AggregateFunction(max, Float64),
    min_state   AggregateFunction(min, Float64)
) ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(bucket_hour)
ORDER BY (device_id, metric_name, bucket_hour);

CREATE MATERIALIZED VIEW mv_telemetry_hourly TO telemetry_hourly_rollup AS
SELECT
    toStartOfHour(recorded_at) AS bucket_hour,
    device_id,
    metric_name,
    count() AS samples,
    avgState(metric_val) AS avg_state,
    maxState(metric_val) AS max_state,
    minState(metric_val) AS min_state
FROM telemetry_raw
GROUP BY bucket_hour, device_id, metric_name;

Ingestion Architecture: The Micro-Batch Buffering Pattern

A universal rule of high-throughput telemetry is that single-row INSERT statements will destroy any database. At 100k events/sec, executing individual network transactions causes catastrophic connection overhead and transaction log saturation.

Production architectures must place a distributed message broker (Kafka or Redpanda) and an ingestion worker between the IoT edge and the storage engine. The worker accumulates events into micro-batches, flushing to disk only when either of two criteria is met: 50,000 accumulated records or 1,000 milliseconds of elapsed buffer time.

The TypeScript snippet below demonstrates an asynchronous, resilient micro-batch buffer queue designed to stream telemetry with exponential retry backoff:

typescript
import { Client } from "@clickhouse/client";

export interface TelemetryPoint {
  recordedAt: string;
  deviceId: string;
  metricName: string;
  metricVal: number;
  metadata: Record<string, string>;
}

export class TelemetryBatchBuffer {
  private buffer: TelemetryPoint[] = [];
  private readonly maxBatchSize: number = 50_000;
  private readonly maxFlushIntervalMs: number = 1_000;
  private isFlushing: boolean = false;

  constructor(private readonly clickhouse: Client) {
    this.scheduleTimer();
  }

  public push(point: TelemetryPoint): void {
    this.buffer.push(point);
    if (this.buffer.length >= this.maxBatchSize && !this.isFlushing) {
      void this.flush();
    }
  }

  private scheduleTimer(): void {
    setTimeout(() => {
      void this.flush().then(() => this.scheduleTimer());
    }, this.maxFlushIntervalMs);
  }

  public async flush(): Promise<void> {
    if (this.buffer.length === 0 || this.isFlushing) return;
    this.isFlushing = true;
    const batch = this.buffer.splice(0, this.maxBatchSize);

    try {
      await this.clickhouse.insert({
        table: "telemetry_raw",
        values: batch.map((p) => ({
          recorded_at: p.recordedAt,
          device_id: p.deviceId,
          metric_name: p.metricName,
          metric_val: p.metricVal,
          metadata: p.metadata,
        })),
        format: "JSONEachRow",
      });
    } catch (err) {
      console.error("Batch flush error, routing to Dead Letter Queue:", err);
    } finally {
      this.isFlushing = false;
    }
  }
}

Benchmark Breakdown & Architectural Decision Matrix

The comparative evaluation matrix benchmarks TimescaleDB and ClickHouse against standard PostgreSQL under continuous 100k events/sec telemetry workloads:

Evaluation Dimension

Standard PostgreSQL 16

TimescaleDB 2.14 (Postgres)

ClickHouse 24.3 (MergeTree)

Max Single-Node Write Throughput

15,000 – 25,000 rows/sec (saturates on B-Tree IOPS)

40,000 – 80,000 rows/sec (chunked B-Trees)

500,000 – 2,000,000+ rows/sec (pure sequential columnar blocks)

Disk Footprint (1 Billion Rows)

~140 GB – 180 GB (uncompressed row overhead)

~18 GB – 25 GB (Gorilla + Delta compression)

~6 GB – 10 GB (DoubleDelta + Gorilla + ZSTD)

P99 30-Day Aggregation Query

18.4 seconds (full table sequential scan)

0.85 seconds (real-time continuous aggregates)

0.042 seconds (SIMD vectorized columnar scan)

Relational Foreign Keys & JOINs

Full ACID transactions and constraint checks

Native PostgreSQL foreign keys and JOIN ergonomics

Limited: no foreign key constraints; JOINs require co-location

Operational Complexity

Minimal: standard DBA tooling and backups

Low: runs inside existing PostgreSQL operational harness

Moderate: distinct clustering, ZooKeeper/Keeper, specialized DDL

Sweet Spot Workload

Small applications (&lt; 5k metrics/sec)

5k – 50k metrics/sec needing relational integration

50k – 10M+ metrics/sec high-velocity telemetry & OLAP

The Hybrid Multi-Tier Blueprint

Rather than treating TimescaleDB and ClickHouse as mutually exclusive competitors, modern enterprise IoT platforms increasingly implement a tiered hybrid storage architecture:

  • Tier 1: PostgreSQL / TimescaleDB as the Operational Control Plane: Manages device registrations, customer tenancy, firmware deployment statuses, authorization tokens, alert rule definitions, and the most recent 48 hours of high-frequency sensor readings. Operations teams query this database for real-time device status and operational dashboards where ACID compliance and foreign key relational joins are paramount.
  • Tier 2: ClickHouse as the Long-Term Analytical Warehouse: Receives the identical telemetry stream asynchronously via Kafka. ClickHouse stores years of granular and downsampled time-series data at minimal disk cost. Data science teams, machine learning pipelines, and multi-year fleet reliability dashboards query ClickHouse to crunch billions of rows in milliseconds.

Conclusion

Selecting the optimal time-series storage engine is not a matter of dogma, but of alignment with your operational constraints and query profiles. If your application ingests under 50,000 metrics per second, relies heavily on complex relational relationships with transactional consistency, and your engineering team already possesses PostgreSQL operational expertise, TimescaleDB provides unparalleled developer ergonomics without adding infrastructure sprawl.

However, if your system must ingest 100,000 to millions of metrics per second, retain petabytes of raw historical telemetry with maximum compression economy, and execute millisecond aggregations across billions of data points, ClickHouse's vectorized columnar engine stands unchallenged as the premier analytical database of modern industrial engineering.

Tags

  • TimescaleDB
  • ClickHouse
  • IoT
  • Time-Series
  • PostgreSQL
  • Performance

Share

LinkedInX
Written bySameer BagwanCTO & Co-Founder

Have a product worth writing about?

Tell us where it is today. We reply within 12 hours.