Engineering

ClickHouse vs TimescaleDB vs Native Postgres Partitioning: Querying 100M Payment Ledger Logs on a $40 VPS

A
Adebayo FalojuPrincipal Systems Architect
November 11, 202615 min read
ClickHouse vs TimescaleDB vs Native Postgres Partitioning: Querying 100M Payment Ledger Logs on a $40 VPS

We benchmarked ClickHouse, TimescaleDB, and PostgreSQL native partitioning on an 8GB RAM VPS to solve high query latency and ballooning storage costs for 100 million settlement records. Here are the hard latency numbers, RAM profiles, and schema designs.

Hosting infrastructure costs paid in US Dollars create immense pressure on African engineering teams. When server bills are tied to foreign exchange rates, throwing a bigger $400/month AWS RDS instance at high-latency analytical queries is rarely an option. We faced this precise constraint while scaling an analytical reporting engine for a payment aggregator in Lagos. The core table—a historical log of virtual account transfers and card settlements—was pushing past 100 million rows, consuming over 65GB of disk space on PostgreSQL, and grinding merchant dashboard queries to a halt.

Every time a merchant queried their monthly transaction volume aggregated by payment channel, the CPU hit 100% utilization, and PostgreSQL swapped furiously. To keep infrastructure lean without sacrificing query latency, we evaluated three architectures on a modest $40 VPS (4 vCPUs, 8GB RAM, Hetzner NVMe drive):

  1. Native PostgreSQL Declarative Range Partitioning + Materialized Views
  2. TimescaleDB (PostgreSQL extension with hypertables and native compression)
  3. ClickHouse (Standalone columnar OLAP database)

Here is what we learned from benchmarking 100 million payment settlement records under production-like read and write patterns.


The Dataset and Workload Profile

Our test dataset mirrored real-world payment webhook events and settlement ledgers. The schema required tracking raw payload attributes, financial metadata, and temporal markers across millions of transactions:

  • id (UUID or Uint64)
  • merchant_id (UUID)
  • transaction_reference (String)
  • amount (Decimal / Int64 in Kobo)
  • channel (Enum/String: nibss_qr, virtual_account, card)
  • status (Enum/String: success, failed, reversed)
  • fee (Int64 in Kobo)
  • created_at (Timestamp with timezone)

The Workload Requirements

  • High-throughput append ingestion: Spikes of 1,500 to 3,000 incoming webhook events per second during peak hours (e.g., Friday evening retail spikes).
  • Heavy Analytical Aggregations: Queries performing SUM(amount), AVG(fee), and COUNT(*) grouped by merchant_id and day over 90-day to 365-day rolling windows.
  • Strict RAM Constraints: System memory capped at 8GB, with web application workers running alongside or on adjacent low-cost nodes.

Managing USD server costs requires brutal resource efficiency. As we detailed in our guide on index-linked Naira billing strategies for B2B platforms, keeping operational overhead flat during currency fluctuations is an architectural necessity.


Option 1: Native PostgreSQL Range Partitioning

PostgreSQL is the default backend choice for 90% of software products. Declarative table partitioning (introduced in Postgres 10 and improved in Postgres 12+) lets you split a massive logical table into smaller physical tables based on range criteria (e.g., monthly bounds on created_at).

-- Base partition parent table
CREATE TABLE payment_ledger (
    id UUID NOT NULL,
    merchant_id UUID NOT NULL,
    transaction_reference VARCHAR(64) NOT NULL,
    amount BIGINT NOT NULL,
    channel VARCHAR(32) NOT NULL,
    status VARCHAR(16) NOT NULL,
    fee BIGINT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL
) PARTITION BY RANGE (created_at);

-- Monthly partition example
CREATE TABLE payment_ledger_y2024m01 PARTITION OF payment_ledger
    FOR VALUES FROM ('2024-01-01 00:00:00+00') TO ('2024-02-01 00:00:00+00');

CREATE INDEX idx_ledger_m1_merch_date ON payment_ledger_y2024m01 (merchant_id, created_at DESC);

The Production Reality of Postgres Partitioning

Declarative partitioning helps Postgres bypass full-table scans by employing partition pruning (enable_partition_pruning = on). If a query asks for transactions in January 2024, Postgres only scans payment_ledger_y2024m01.

However, row-oriented engine constraints remain. At 100 million rows, B-tree indexes across multiple partitions quickly outgrow available memory. On our 8GB RAM server, the combined B-tree indexes for merchant_id, created_at, and transaction_reference consumed 22GB of disk space.

When executing aggregate queries spanning 6 to 12 months, Postgres had to read row after row into shared_buffers. Once shared buffers overflowed, the database dropped into disk I/O thrashing. Aggregating 12 months of ledger data for a top-tier merchant took 14.2 seconds on a cold cache.

Verdict: Native partitioning keeps transactional guarantees (ACID) straightforward, but fails as a low-cost analytics engine once index size surpasses system RAM.


Option 2: TimescaleDB (Hypertables & Columnar Compression)

TimescaleDB transforms standard PostgreSQL tables into auto-partitioned "Hypertables". It maintains standard SQL compatibility while adding native column-oriented chunk compression.

-- Create standard table
CREATE TABLE payment_ledger (
    id UUID NOT NULL,
    merchant_id UUID NOT NULL,
    transaction_reference VARCHAR(64) NOT NULL,
    amount BIGINT NOT NULL,
    channel VARCHAR(32) NOT NULL,
    status VARCHAR(16) NOT NULL,
    fee BIGINT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL
);

-- Convert to hypertable partitioned by 7-day time intervals
SELECT create_hypertable('payment_ledger', 'created_at', chunk_time_interval => INTERVAL '7 days');

-- Enable hypertable compression ordered by merchant_id
ALTER TABLE payment_ledger SET (
    timescaledb.compress,
    timescaledb.compress_segmentby = 'merchant_id',
    timescaledb.compress_orderby = 'created_at DESC'
);

-- Add automated compression policy for chunks older than 14 days
SELECT add_compression_policy('payment_ledger', INTERVAL '14 days');

Where TimescaleDB Excels

TimescaleDB solves the disk footprint problem eleganty. By re-ordering data into columnar chunks when compressed, run-length encoding and Gorilla compression kick in. Our 65GB uncompressed table shrunk down to 7.8GB.

Because compressed chunks are stored in column format, queries like SELECT SUM(amount) FROM payment_ledger WHERE merchant_id = x only pull the amount and merchant_id columns from disk into memory. Query latency dropped from 14.2 seconds to 480 milliseconds.

The Catch: Compression Overhead and Ingestion Edge Cases

Writing directly into compressed chunks is not supported; incoming data goes into uncompressed "hot" chunks before background jobs compress them. If your ingestion queue experiences massive backfills (e.g., re-ingesting 30 days of historical settlement data from an upstream processor API), TimescaleDB must decompress and re-compress entire chunks, leading to severe CPU and lock contention.

For systems using queue drivers like BullMQ or Temporal (which we analyzed in our breakdown of job queues for flaky APIs), sudden retries push batch inserts into older chunks, hitting this exact penalty.


Option 3: ClickHouse (MergeTree Engine)

ClickHouse is an open-source, true column-oriented OLAP engine built specifically for fast data aggregation at scale. It dispenses with standard PostgreSQL ACID transactions in favor of raw analytical processing power.

CREATE TABLE payment_ledger
(
    id UUID,
    merchant_id UUID,
    transaction_reference String,
    amount Int64,
    channel LowCardinality(String),
    status LowCardinality(String),
    fee Int64,
    created_at DateTime('Africa/Lagos')
)
ENGINE = MergeTree()
PRIMARY KEY (merchant_id)
ORDER BY (merchant_id, created_at, id)
SETTINGS index_granularity = 8192;

The ClickHouse Performance Shift

ClickHouse's execution model leverages SIMD (Single Instruction, Multiple Data) CPU hardware instructions and columnar data storage. Data with low unique counts (like channel or status) can be optimized using the LowCardinality dictionary type.

  1. Storage Footprint: The 100 million row dataset shrank from 65GB (Postgres uncompressed) to 4.1GB on disk.
  2. Batch Ingestion: Ingesting 50,000 rows in a single batch insert query took 115 milliseconds.
  3. Query Latency: Aggregating 12 months of ledger history across 4.5 million rows for a specific merchant executed in 18 milliseconds on a cold cache.
-- Analytical Query Execution in ClickHouse
SELECT 
    toStartOfDay(created_at) AS day,
    channel,
    count(*) AS total_transactions,
    sum(amount) AS total_volume,
    avg(fee) AS avg_fee
FROM payment_ledger
WHERE merchant_id = 'a3b8e910-4f5c-4d8e-9a1b-2c3d4e5f6a7b'
  AND created_at >= now() - INTERVAL 90 DAY
GROUP BY day, channel
ORDER BY day DESC;

Executing this exact query across 100M rows on our $40 VPS consumed less than 180MB of RAM and executed in under 25ms.

The Trade-off: Non-Transactional Paradigm

ClickHouse is not a primary operational database. It does not support traditional UPDATE statements or multi-row ACID transactions. Deletions and updates exist as background mutations (ALTER TABLE ... UPDATE), which are heavy operations designed for compliance (like GDPR requests), not high-frequency status changes.


Head-to-Head Comparison Table

| Evaluation Criteria | Native Postgres Partitioning | TimescaleDB Extension | ClickHouse (MergeTree Engine) | | :--- | :--- | :--- | :--- | | Disk Storage (100M Rows) | ~65 GB | ~7.8 GB (Compressed) | ~4.1 GB (Native Columnar) | | Cold Query Latency (12-mo AGG) | 14,200 ms | 480 ms | 18 ms | | RAM Footprint (Heavy Query) | 4.8 GB - 7.1 GB (Swapping) | 650 MB - 1.2 GB | 120 MB - 350 MB | | Ingestion Throughput | ~4,500 rows/sec | ~12,000 rows/sec | ~150,000 rows/sec (Batch) | | ACID / Transaction Support | Full Support (Strict ACID) | Full Support (Postgres Core) | Non-Transactional (Eventual) | | Single-Row UPDATE Speed | Fast (Indexed B-Tree) | Fast on Uncompressed Chunks | Very Slow (Background Mutation) | | Operational Overhead | Minimal (Standard Postgres) | Low (Single Postgres Extension) | Medium (Separate Service to Manage) |


Recommendation Framework: Which Engine Should You Ship?

                      Is your dataset over 50M rows 
                      AND mostly append-only logs?
                                   │
                      ┌────────────┴────────────┐
                     YES                        NO
                      │                         │
        Do you need relational JOINs           Use Native Postgres
        & immediate row updates?               Partitioning
              │            │
             YES           NO
              │            │
      Use TimescaleDB    Use ClickHouse

1. Choose Native Postgres Partitioning If:

  • Your total dataset remains under 20-30 million rows.
  • You rely heavily on foreign keys, multi-table synchronous transactions, and frequent row updates (e.g., updating transaction status from pending to successful).
  • Your engineering team does not have the operational capacity to manage secondary databases or specialized extensions.

2. Choose TimescaleDB If:

  • You already run on PostgreSQL and want zero application code rewrite (same SQL dialect, standard PostgreSQL ORM compatibility).
  • You need strong relational features and foreign key JOINs with operational tables (e.g., joining ledger logs directly to a merchants or users table).
  • You need to reduce storage costs by 80% without introducing a separate database binary to your deployment stack.

3. Choose ClickHouse If:

  • You are ingesting append-only event logs, webhooks, or financial settlement files exceeding 50 million rows.
  • You want lightning-fast merchant analytics dashboards (under 50ms responses) while running on cheap, low-memory VPS hardware.
  • You are comfortable with an asynchronous ingestion architecture: writing operational data to Postgres first, then streaming CDC (Change Data Capture) or batch event pipelines into ClickHouse.

Frequently Asked Questions

How do you sync data from Postgres to ClickHouse without dropping transactions?

Use a dual-write pattern or CDC pipeline. The cleanest pattern for mid-sized teams is publishing domain events to a lightweight queue (like Redis Stream or NATS) when a transaction settles, then running a worker process that inserts events into ClickHouse in batches of 5,000 to 10,000 rows. Avoid doing single-row INSERT queries into ClickHouse, as each write creates a physical data part on disk.

Can ClickHouse replace PostgreSQL as our main application database?

No. ClickHouse is an OLAP (Online Analytical Processing) engine, not an OLTP (Online Transaction Processing) database. It lacks row-level locking, interactive transactions, and instant point-lookups. Keep PostgreSQL for user authentication, wallet balances, and active state management, and stream completed audit events to ClickHouse for analytics.

Does TimescaleDB compression impact write speeds?

Writes to current time periods are unaffected because incoming data enters active, uncompressed chunks. However, if backfilled data arrives with timestamps that fall into older, already-compressed chunks, TimescaleDB automatically decompresses the target chunk, performs the write, and re-compresses it. If backfilling historical data is a daily requirement, tune your compression policy interval accordingly.

How do we handle GDPR or NDPR data deletion requests in ClickHouse?

ClickHouse supports lightweight mutations via the ALTER TABLE ... DELETE WHERE user_id = x syntax. Because mutations rewrite affected disk data parts in the background, they should be scheduled during low-traffic maintenance windows or batched in bulk rather than run synchronously per API request.


Final Implementation Strategy

If running a high-scale service on a tight server budget, stop asking PostgreSQL to act as a data warehouse. Using native PostgreSQL partitioning will extend your database's headroom for a few months, but once your payment or event tables surpass 50 million rows, disk I/O thrashing becomes inevitable.

If operational simplicity is your top priority, install the TimescaleDB extension on your existing Postgres cluster to gain columnar compression with zero schema rewrites. If raw speed, ultra-low resource utilization, and scale are your primary constraints, deploy ClickHouse alongside PostgreSQL. Use Postgres for single-row ACID transactions and stream completed event logs into ClickHouse for analytics.

Neobot Engineering Standard

Every system deployed by Neobot Tech incorporates enterprise baseline practices. We continuously audit our database topologies, REST API query paths, and frontend modular bundles to prevent latency spikes and ensure top-tier security posture.

Tags:#Database Architecture#Postgres#ClickHouse#TimescaleDB#System Design#Performance Optimization#DevOps

Discussion

Comments Coming Soon

We are currently migrating our discussion engine to a new real-time database schema. Check back shortly to join the conversation.