About Skills Projects Blog Contact View my CV ↗ Español
ClickHouse hands-on: logs and observability without drowning

ClickHouse hands-on: logs and observability without drowning

A hands-on ClickHouse guide for logs and observability: MergeTree, ORDER BY, codecs, OpenTelemetry ingestion, retention, and wide-event queries.

By Omar Flores
Table of Contents

It is 2:47 in the morning and the phone rings. A service is returning 500s and the dashboard only says the error rate is up 4%. You open the log tool, search for the request_id from the report, and the query takes so long that the browser gives up. When it finally answers, sampling has removed the exact request that failed.

You have logs. What you do not have is an answer.

ClickHouse shows up when the problem stops being “store lines of text” and becomes “understand millions of requests without waiting.” It is a columnar database built for aggregation at brutal speed. It is not a replacement for PostgreSQL or Elasticsearch. It is the engine you put under your observability when the questions matter more than the dashboards.


The problem is not storing logs, it is answering questions

An application writes one line per event: request, query, cache miss, error, deploy. The full story is spread across eight lines and three services; reconstructing it requires joins by request_id and turns a text store into an analytics engine.

Traditional logs have another problem: sampling. Reducing volume is reasonable for trends, but the event that breaks production is usually the rare one. If sampling drops it, no dashboard brings it back.

The alternative is to store wide events: one row per request with all the context together. User, route, status, latency, deployed version, flags, trace ID, and client attributes. Fewer rows than log lines, more information per row. ClickHouse is designed for that pattern.

Why ClickHouse is fast without magic

ClickHouse is columnar: it stores each column separately. A query that sums duration_ms never reads message or attributes. That cuts I/O dramatically.

It is also vectorized. It processes blocks of values with array operations, not row by row. And it compresses well: monotonic timestamps, repeated strings, and bounded integers shrink to a fraction of their original size.

The part people forget is the index. ClickHouse does not index every row. It uses a sparse index over the sort key: it stores marks every 8,192 rows and skips whole ranges before reading. For logs, that is usually enough to go from seconds to milliseconds.

System Model Strong at Weak at
PostgreSQL OLTP, rows Transactions, joins, consistency Massive analytical scans
Elasticsearch Search, documents Relevance, free text Numeric aggregation at scale
ClickHouse OLAP, columns Aggregations, logs, time series Point updates, OLTP

ClickHouse is not “faster” in the abstract. It is fast at the job it was designed for: reading many rows, few columns, and aggregating.

MergeTree: parts, granules, and the ORDER BY that decides everything

When you insert into a MergeTree table, ClickHouse writes an immutable part sorted by the key. A background process merges parts to reduce files and improve compression.

Each part is divided into granules of up to 8,192 rows. The primary index stores the key value at the start of each granule. A query with a filter on the key can skip entire granules without reading them.

ORDER BY is not a presentation detail: it is the sort key and the primary index. Column order matters because the index is used by prefix.

ORDER BY (service, level, toUnixTimestamp(Timestamp), trace_id)

With that key, filtering by service is fast. Filtering by service and level is also fast. Filtering only by trace_id does not use the prefix, though a bloom filter can help.

PARTITION BY is something else: it manages data, it does not speed up queries. Partition by day or month. Never by user_id or request_id; you would create millions of partitions and drown the server in metadata.

The log table you actually want

A reasonable schema for logs and traces combines compact types, suitable codecs, and few truly hot columns.

CREATE TABLE logs (
    Timestamp DateTime64(3) CODEC(Delta(8), ZSTD(1)),
    service LowCardinality(String),
    env LowCardinality(String),
    level LowCardinality(String),
    trace_id String CODEC(ZSTD(1)),
    user_id UInt64,
    route String CODEC(ZSTD(1)),
    status UInt16,
    duration_ms UInt32 CODEC(T64, ZSTD(1)),
    message String CODEC(ZSTD(1)),
    attributes Map(LowCardinality(String), String) CODEC(ZSTD(1)),
    INDEX idx_trace trace_id TYPE bloom_filter(0.001) GRANULARITY 1,
    INDEX idx_message lower(message) TYPE text(tokenizer = 'splitByNonAlpha')
)
ENGINE = MergeTree
PARTITION BY toDate(Timestamp)
ORDER BY (service, level, toUnixTimestamp(Timestamp), trace_id)
TTL toDateTime(Timestamp) + INTERVAL 30 DAY
SETTINGS ttl_only_drop_parts = 1;

Every choice has a reason. LowCardinality dictionary-encodes repeated strings. DateTime64(3) keeps milliseconds. Delta(8) compresses the difference between consecutive timestamps. T64 drops high bits that do not change within a block of integers. Map stores attributes you do not know in advance without altering the table for every new field.

The bloom filter speeds up trace_id lookups. The text index enables hasToken(lower(message), 'timeout') without scanning every message. TTL drops whole partitions when they expire, and ttl_only_drop_parts = 1 avoids rewriting parts to remove individual rows.

Ingestion: from SDK to table without creating 10,000 parts

The classic mistake is inserting one row per event. Every INSERT creates a part; ten thousand tiny inserts turn merges into an emergency.

The rule: send batches. At least a thousand rows per insert, and tens of thousands if you can. If the producer cannot wait, use async inserts: ClickHouse buffers in memory and writes when the buffer fills.

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
processors:
  batch:
    timeout: 5s
    send_batch_size: 10000
exporters:
  clickhouse:
    endpoint: tcp://clickhouse:9000?dial_timeout=10s&compress=lz4&async_insert=1
    logs_table_name: logs
    create_schema: false
service:
  pipelines:
    logs:
      receivers: [otlp]
      processors: [batch]
      exporters: [clickhouse]

The OpenTelemetry Collector receives OTLP, batches, and exports. create_schema: false forces you to define the table yourself, including the TTL, which is exactly what you want: the default schema is a starting point, not an optimization. async_insert=1 delegates batching to ClickHouse when the collector cannot guarantee large batches. Keep wait_for_async_insert=1 if you need delivery confirmation.

Log queries that answer incidents

The first query of an incident is not a dashboard: it is counting by severity over a short window.

SELECT level, count() AS events
FROM logs
WHERE Timestamp >= now() - INTERVAL 15 MINUTE
GROUP BY level
ORDER BY events DESC;

The second question is usually which route is breaking and how slow it is.

SELECT route,
       countIf(status >= 500) AS errors,
       quantiles(0.5, 0.95, 0.99)(duration_ms) AS latencies
FROM logs
WHERE Timestamp >= now() - INTERVAL 1 HOUR
GROUP BY route
HAVING errors > 0
ORDER BY errors DESC
LIMIT 10;

countIf avoids a verbose CASE WHEN; quantiles returns an array. The time window limits partitions; ORDER BY helps when the filter starts with its first columns.

To follow a single request, filter by trace_id and time. Without time, ClickHouse looks at every partition.

SELECT Timestamp, service, level, message, attributes
FROM logs
WHERE trace_id = '4bf92f3577b34da6a3ce929d0e0e4736'
  AND Timestamp >= now() - INTERVAL 1 DAY
ORDER BY Timestamp;

To find out whether a deploy broke something, group by the version you stored in the attributes:

SELECT attributes['deploy_version'] AS version,
       countIf(status >= 500) / count() AS error_rate
FROM logs
WHERE Timestamp >= now() - INTERVAL 6 HOUR
GROUP BY version
ORDER BY error_rate DESC;

That attributes['deploy_version'] is the difference between having logs and having context. The version lived in the pipeline, not in the message; now it is in the row.

Wide events: the row that tells the whole story

A wide event is not a longer log line. It is a change of model. Instead of writing “request start,” “db query,” “cache miss,” and “request end” as separate lines, you write one row at the end of the request with everything you learned.

That row answers questions that used to require correlating sources: users affected by a slow route, error rate by version, latency for feature-flag users, which services share a trace ID.

Dynamic attributes go in Map. When a field is queried constantly, promote it to a column. MATERIALIZED computes it on insert and stores it; ALIAS computes it on read.

ALTER TABLE logs
ADD COLUMN deploy_version LowCardinality(String)
MATERIALIZED attributes['deploy_version'];

Do not materialize everything: every new column takes space and is written on every insert. Promote the keys that appear in filters or dashboards; the rest stays in the Map, with bloom indexes if needed.

Retention and tiering without manual deletes

Retention should not be a cron job that runs DELETE. In ClickHouse it is a table clause.

ALTER TABLE logs
MODIFY TTL
    toDateTime(Timestamp) + INTERVAL 30 DAY DELETE,
    toDateTime(Timestamp) + INTERVAL 7 DAY TO VOLUME 'cold';

DELETE removes expired rows. TO VOLUME 'cold' moves whole parts to a cheaper storage volume, provided a storage policy exists. TTL is evaluated during merges, not at the exact instant; if you need to force it, run ALTER TABLE ... MATERIALIZE TTL.

For data you no longer query but must keep, move the partition to an archive table with the same structure and partitioning:

ALTER TABLE logs MOVE PARTITION '2026-11-01' TO TABLE logs_archive;

That is much cheaper than an INSERT INTO SELECT. To delete, DROP PARTITION is much cheaper than a massive DELETE. And if the full message only matters for a week, give it a column TTL and keep the rest of the event longer.

ClickHouse Cloud separates compute and storage, so volume-based tiering does not apply the same way. On self-hosted, the combination of TTL, volumes, and partitions is what keeps cost under control.

Performance: fewer columns, better types, fewer parts

Optimization starts with the schema, not the server. Check how many active parts each table has:

SELECT table, count() AS parts, sum(rows) AS total_rows
FROM system.parts
WHERE active
GROUP BY table
ORDER BY parts DESC;

If a table has hundreds of parts, the problem is ingestion or merges, not the query. If a query reads more bytes than expected, review ORDER BY, filters, and selected columns.

EXPLAIN indexes = 1
SELECT route, count()
FROM logs
WHERE service = 'checkout' AND Timestamp >= now() - INTERVAL 1 HOUR
GROUP BY route;

EXPLAIN indexes = 1 shows which granules are skipped. To measure real queries, system.query_log stores read_rows, read_bytes, memory_usage, and query_duration_ms. That is where you see whether the problem is reading too much, grouping badly, or running out of memory.

Other levers: avoid Nullable on hot columns because it adds a mask per value; use LowCardinality for repeated strings; add projections for frequent aggregations; and do not run OPTIMIZE TABLE ... FINAL every hour. Merges already do their job. FINAL is for specific ReplacingMergeTree cases, not for cleaning up your mood.

Common mistakes that cost money

  • Inserting row by row and creating thousands of parts.
  • Partitioning by user_id, request_id, or any high-cardinality key.
  • Putting Timestamp first in ORDER BY when almost every query filters by service.
  • Using Nullable everywhere “just in case.”
  • Storing JSON as a string and parsing it on every query.
  • Running SELECT * on a table with a hundred columns.
  • Treating OPTIMIZE FINAL as a performance strategy.
  • Using mutations to delete millions of rows instead of DROP PARTITION.
  • Expecting uniqueness, foreign keys, or row transactions.
  • Forgetting retention and discovering the cost three months later.

None of these is exotic: all of them show up in the first week of a team treating ClickHouse like PostgreSQL.

When NOT to use ClickHouse

Do not use it for OLTP. It is not a transactional database, it does not shine at single-row updates, and it will not give you relational guarantees for your shopping cart.

It is also not the best choice if:

  • The dataset is small and PostgreSQL already answers in milliseconds.
  • Your main workload is complex joins across many tables.
  • You need relevance search, synonyms, and search-engine ranking.
  • Your access pattern is random point lookups by primary key, not analytical scans.
  • You need a queue, a workflow engine, or a document store.
  • Nobody can operate merges, disks, replicas, and backups.

ClickHouse is infrastructure. Speed does not remove operations; it only changes where they hurt.

Checklist for taking logs to production

  • One row per request, not ten loose lines.
  • ORDER BY aligned with the most frequent filters.
  • Partitions by day or month, never by user.
  • Per-column codecs: Delta for time, T64 + ZSTD for integers, and ZSTD for the rest.
  • LowCardinality on services, environments, and levels.
  • TTL aligned with the partition size.
  • Batched ingestion or async inserts.
  • OpenTelemetry Collector with batching and create_schema: false.
  • Indexes only where queries justify them.
  • Monitoring for active parts, merges, disk, and ingest latency.
  • A retention test before trusting retention.
  • A PII plan: do not store what you do not need.

Observability does not start when the dashboard loads. It starts when you can answer the question nobody anticipated, at 2:47 in the morning, without asking the tool for permission.