Contents
ClickHouse: Stop Burdening PostgreSQL with Logs and Events
Do you know the feeling when your application slows down and monitoring shows 95% CPU utilization on PostgreSQL? The reason is not complex business logic, but thousands of rows per second being written to an events table.
I have seen this repeatedly. The solution is surprisingly simple: stop forcing a relational database to do something it was not designed for.
The problem: a relational database as an event dumping ground
Most applications start simply:
-- "Put it in PostgreSQL; it can handle it"
CREATE TABLE events (
id BIGSERIAL PRIMARY KEY,
user_id UUID NOT NULL,
event_type VARCHAR(50) NOT NULL,
payload JSONB,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE audit_logs (
id BIGSERIAL PRIMARY KEY,
entity_type VARCHAR(100),
entity_id UUID,
action VARCHAR(20),
old_value JSONB,
new_value JSONB,
performed_by UUID,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE request_logs (
id BIGSERIAL PRIMARY KEY,
method VARCHAR(10),
path TEXT,
status_code INT,
response_time_ms INT,
ip_address INET,
created_at TIMESTAMP DEFAULT NOW()
);At first it works. A hundred events per minute? No problem. Then growth arrives:
Month 1: 1 000 events/day → PostgreSQL: "Easy"
Month 3: 50 000 events/day → PostgreSQL: "Managing"
Month 6: 500 000 events/day → PostgreSQL: "Hmm..."
Month 12: 5 000 000 events/day → PostgreSQL: "HELP"Why does PostgreSQL struggle?
PostgreSQL is a row-oriented database optimized for:
- ✅ ACID transactions
- ✅ Complex JOINs
- ✅ UPDATE / DELETE operations
- ✅ Referential integrity
But not for:
- ❌ Massive append-only writes (millions of INSERTs)
- ❌ Analytical queries over billions of rows
- ❌ Compressing hundreds of gigabytes of logs
- ❌ Aggregations such as hourly average response time over the past 30 days
Every PostgreSQL INSERT involves:
- A WAL (write-ahead log) write
- An index update, if you have indexes—and you do
- MVCC overhead to store row visibility
- VACUUM later cleaning up dead tuples
All of this loads the same database that runs your business logic. Customers wait for checkout while the database writes audit logs.
The solution: ClickHouse—a database designed for events
ClickHouse is an open-source column-oriented analytical database originally developed at Yandex. It is designed for the workload PostgreSQL struggles with.
Column-oriented vs row-oriented
Row-oriented (PostgreSQL):
┌────┬──────────┬───────────┬─────────────┐
│ id │ user_id │ event_type│ created_at │ ← the whole row is stored together
├────┼──────────┼───────────┼─────────────┤
│ 1 │ abc-123 │ click │ 2026-02-01 │
│ 2 │ def-456 │ purchase │ 2026-02-01 │
│ 3 │ abc-123 │ pageview │ 2026-02-02 │
└────┴──────────┴───────────┴─────────────┘
Column-oriented (ClickHouse):
id: [1, 2, 3, ...] ← each column is stored separately
user_id: [abc-123, def-456, ...]
event_type: [click, purchase, ...]
created_at: [2026-02-01, 2026-02-01, ...]Why is it faster for analytics?
For SELECT count(*) FROM events WHERE event_type = 'purchase', ClickHouse reads only the event_type column, rather than whole rows. Across billions of rows, that can mean the difference between seconds and minutes.
Numbers that speak for themselves
| Metric | PostgreSQL | ClickHouse |
|---|---|---|
| INSERT rate | ~10,000/s | ~1,000,000+/s |
| Compression of 1 TB of logs | ~800 GB | ~50–100 GB |
| Aggregation over 1B rows | Minutes | Under a second |
| Storage cost (one year of logs) | $$$ | $ |
Practical implementation: hybrid architecture
The goal is not to replace PostgreSQL but to reduce its load. Business data stays in PostgreSQL; events and logs go to ClickHouse.
Architecture
┌──────────────┐
│ Application │
└──────┬───────┘
│
┌────────────┴────────────┐
│ │
▼ ▼
┌─────────────────┐ ┌──────────────────┐
│ PostgreSQL │ │ ClickHouse │
│ │ │ │
│ • Users │ │ • Events │
│ • Orders │ │ • Audit logs │
│ • Products │ │ • Request logs │
│ • Transactions │ │ • Metrics │
│ │ │ • Analytics │
│ (Business data) │ │ (Append-only data)│
└─────────────────┘ └──────────────────┘1. ClickHouse setup (Docker)
# docker-compose.yml
services:
clickhouse:
image: clickhouse/clickhouse-server:latest
ports:
- "8123:8123" # HTTP interface
- "9000:9000" # Native protocol
volumes:
- clickhouse-data:/var/lib/clickhouse
environment:
CLICKHOUSE_USER: admin
CLICKHOUSE_PASSWORD: your-secure-password
ulimits:
nofile:
soft: 262144
hard: 2621442. ClickHouse tables
-- Events table using the MergeTree engine
CREATE TABLE events (
event_id UUID DEFAULT generateUUIDv4(),
user_id UUID,
event_type LowCardinality(String), -- optimization for repeated values
payload String, -- JSON as a string (or use the JSON type)
created_at DateTime DEFAULT now()
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(created_at) -- monthly partitions
ORDER BY (event_type, created_at) -- sort key for fast queries
TTL created_at + INTERVAL 12 MONTH; -- automatic deletion after one year
-- Audit log
CREATE TABLE audit_logs (
entity_type LowCardinality(String),
entity_id UUID,
action LowCardinality(String),
old_value String,
new_value String,
performed_by UUID,
created_at DateTime DEFAULT now()
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(created_at)
ORDER BY (entity_type, created_at)
TTL created_at + INTERVAL 24 MONTH;
-- Request logs with automatic TTL
CREATE TABLE request_logs (
method LowCardinality(String),
path String,
status_code UInt16,
response_time_ms UInt32,
ip_address IPv4,
created_at DateTime DEFAULT now()
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(created_at)
ORDER BY (status_code, created_at)
TTL created_at + INTERVAL 3 MONTH; -- logy len 3 mesiaceKey differences from PostgreSQL:
LowCardinality(String): enum-like optimization for columns with few unique valuesMergeTree(): an engine optimized for append-only workloadsPARTITION BY: automatic division of data by monthTTL: automatic deletion of old data, without a cron job runningDELETE FROM ... WHERE created_at < ...
3. Writing from the application (Spring Boot / Node.js)
// Spring Boot — async event writer
@Service
public class ClickHouseEventWriter {
private final ClickHouseClient client;
private final BlockingQueue<Event> buffer = new LinkedBlockingQueue<>(10_000);
@Scheduled(fixedRate = 1000) // Flush every second
public void flushEvents() {
List<Event> batch = new ArrayList<>();
buffer.drainTo(batch, 5000); // Max 5000 eventov naraz
if (batch.isEmpty()) return;
// Batch INSERT — ClickHouse favors batches
try (var insert = client.write("events")
.format(ClickHouseFormat.JSONEachRow)) {
for (Event event : batch) {
insert.write(event.toJson());
}
}
}
public void track(Event event) {
buffer.offer(event); // Non-blocking; does not hold up the main request
}
}// Node.js — batch writer
import { createClient } from '@clickhouse/client';
const clickhouse = createClient({
url: 'http://localhost:8123',
username: 'admin',
password: 'your-secure-password',
});
class EventBuffer {
private buffer: Event[] = [];
private readonly FLUSH_INTERVAL = 1000;
private readonly BATCH_SIZE = 5000;
constructor() {
setInterval(() => this.flush(), this.FLUSH_INTERVAL);
}
track(event: Event) {
this.buffer.push(event);
if (this.buffer.length >= this.BATCH_SIZE) this.flush();
}
private async flush() {
if (this.buffer.length === 0) return;
const batch = this.buffer.splice(0, this.BATCH_SIZE);
await clickhouse.insert({
table: 'events',
values: batch,
format: 'JSONEachRow',
});
}
}Important: Always write in batches, not one row at a time. ClickHouse is optimized for large batches: one INSERT of 5,000 rows is orders of magnitude faster than 5,000 separate INSERTs.
4. Query examples: analytics that took minutes in PostgreSQL
-- Top 10 slowest endpoints in the past 7 days
SELECT
path,
count() AS requests,
avg(response_time_ms) AS avg_ms,
quantile(0.95)(response_time_ms) AS p95_ms,
quantile(0.99)(response_time_ms) AS p99_ms
FROM request_logs
WHERE created_at > now() - INTERVAL 7 DAY
GROUP BY path
ORDER BY p95_ms DESC
LIMIT 10;
-- Hourly event counts for the past month (for a dashboard)
SELECT
toStartOfHour(created_at) AS hour,
event_type,
count() AS cnt
FROM events
WHERE created_at > now() - INTERVAL 30 DAY
GROUP BY hour, event_type
ORDER BY hour;
-- Error rate by day
SELECT
toDate(created_at) AS day,
countIf(status_code >= 500) AS errors,
count() AS total,
round(errors / total * 100, 2) AS error_rate_pct
FROM request_logs
WHERE created_at > now() - INTERVAL 30 DAY
GROUP BY day
ORDER BY day;These queries run over billions of rows in less than a second. Try the same in PostgreSQL.
When to use—and not use—ClickHouse
Use ClickHouse when:
- ✅ You write lots of data that does not change (append-only)
- ✅ You need analytics over large data volumes
- ✅ You want to save storage through 10–20× compression
- ✅ PostgreSQL is overloaded with logs or events
- ✅ You need automatic TTL for old data
Do not use ClickHouse when:
- ❌ You need UPDATE/DELETE on individual rows
- ❌ You need ACID transactions
- ❌ You need JOINs between business entities
- ❌ You have fewer than 100,000 events per day, which PostgreSQL can handle
- ❌ You need point lookups (
SELECT * FROM ... WHERE id = ?)
Conclusion: the right tool for the job
A relational database is excellent at what it was designed for: business data, transactions and referential integrity. But forcing it to be log storage, event store and analytics engine at the same time is like asking a surgeon to mop the hospital floor as well.
Give PostgreSQL room to do what it does best. Send events, logs and metrics where they are at home: ClickHouse.