Kafka to ClickHouse streaming ingestion is a composition of layers. The Kafka Engine, Materialized Views, and MergeTree tables provide the foundation, but production reliability depends on how storage design, batching, deduplication, error handling, and monitoring fit together. Correct wiring gets messages into a table. Deliberate design makes that pipeline dependable under load and replay.
Why direct Kafka reads break in production and what the correct mental model is
The tempting assumption is that a SELECT against a Kafka Engine table will show the data like a read from any other table. That assumption makes early pipelines fragile. A direct read consumes messages and moves the consumer group offset forward, so it cannot serve as a replayable query surface. Treating the consumer as durable storage can therefore lose data from the intended ingestion path.
The Kafka Engine table consumes messages, a Materialized View transforms each consumed block, and a MergeTree-family destination stores the results for queries. Each object has a distinct job. In this ingestion path, broker offsets are committed only after a successful insert reaches the destination, giving at-least-once delivery. The view runs once per block, so visibility depends on polling and flushing.
The three-object DDL and what each object is responsible for
The three definitions belong together in a versioned migration file so that consumer configuration and transformation logic remain auditable. The Kafka Engine definition declares the broker list, kafka_topic_list, consumer group name, and wire format. More than one topic can be listed under one consumer group, with commas between them. With kafka_format = 'JSONAsString', the schema holds the raw message in a single String column, leaving extraction to the view. The virtual columns _topic, _partition, and _offset are available automatically and must not be declared in the consumer schema.
The destination definition establishes the durable query surface. The supplied log-shaped pattern uses MergeTree, partitions by toDate(ts), orders by (ts, level, service), and uses LowCardinality(String) for level and service. These choices are workload-specific. The Materialized View then selects from the consumer, extracts values with functions such as JSONExtractString, casts them into the destination types, and sends the result to that table. Keeping parsing in the view isolates schema evolution from the raw-message consumer definition.
ORDER BY key and storage design decisions that determine query performance
The destination’s ORDER BY key determines how well compression and the primary index work, and which filters run well. It deserves a schema review before ingestion begins. For common event-filtering patterns, the recommended order places a low-cardinality discriminator such as event_type first, a high-cardinality identifier such as user_id second, and the timestamp last. Similar values then sit close together, which improves locality and compression. The timestamp-first log example is a different layout, so its suitability depends on the dominant query shape.
Partition granularity must also fit how long data is kept and how much is inserted. Monthly partitions using toYYYYMM(event_time) work well for streams that keep 30–90 days of data. Daily partitions need a deliberate retention rationale. Under sustained inserts, excessive partitioning inflates active part counts and burdens merges, unless frequent partition-level deletion is an intentional part of the retention policy. TTL expressions handle expiry during background merges without cron jobs, while merge_with_ttl_timeout controls the minimum delay in seconds before repeating a merge with delete TTL.
Compression and batching complete the storage decision. DoubleDelta with ZSTD(1) suits DateTime values whose consecutive differences are small and predictable. Integer metrics can use Delta with LZ4 to get fast decompression with a somewhat lower compression ratio. Categorical fields suit the low-cardinality representation already shown. None of these choices compensates for row-by-row inserts, because each insert creates a part and adds background merge work.
Throughput tuning knobs and what each one controls
Conservative defaults can limit a high-volume consumer even when its topology is correct. The first control is kafka_max_block_size, which sets how many rows the engine accumulates before passing a block to the view. max_insert_block_size controls the maximum block size at the insert layer. These settings should be tuned together. Setting both to the same value aligns batching across the two layers, while increasing that value reduces parts-per-second at the cost of longer delays before messages become queryable.
Partial blocks need a separate latency control. stream_flush_interval_ms governs how often the engine flushes when the row threshold has not been reached, and reducing it favors visibility over batching efficiency. That tradeoff should be evaluated against consumer progress. system.kafka_consumers exposes assignments and current offsets, but it does not directly expose the broker-side high watermark needed to calculate lag. Broker tooling such as kafka-consumer-groups.sh --describe, or the per-partition statistics in rdkafka_stat, supplies the missing context.
Idempotency strategies and why at-least-once delivery requires a deduplication layer
At-least-once delivery requires an explicit policy for repeated events after restarts, failover, or replay. Successful insertion and offset commitment do not constitute an exactly-once contract. ReplacingMergeTree(version) provides a storage-level strategy by retaining the highest-version row for each ORDER BY key during background merges. The version can come from toUnixTimestamp(event_time) or an explicit version_id. Until those merges occur, duplicate rows can remain visible.
Eventual deduplication is a deliberate write-performance tradeoff. When a read must resolve duplicates right away, FINAL forces query-time deduplication across parts, which takes a lot of computation on large tables. It suits correctness validation or low-frequency analytical queries, with limited suitability for high-concurrency dashboards. The key must also reflect the intended identity, using entity identifier and event time, with a stable event_id when exact event idempotency is required. A version column cannot fix an identity that was defined incorrectly.
The same distinction applies to feature tables keyed by (entity_id, feature_name), where versions protect the latest feature value from re-emitted vectors. Update-heavy workloads offer another choice through CollapsingMergeTree. Its producer must emit paired rows, including explicit delete signals with sign = -1. That is a stronger producer obligation. The choice therefore depends on both read-time correctness requirements and the update protocol the producer can support.
Dead-letter handling so malformed payloads do not halt the primary stream
Deduplication does not address messages that cannot be parsed. Without an error path, one malformed payload can stall consumption and block subsequent messages in its partition. Setting kafka_handle_error_mode = 'stream' exposes engine parse failures through the virtual _error column while allowing consumption to continue. The primary view filters on length(_error) = 0. A second view filters on length(_error) > 0 and routes failures to a separate MergeTree destination.
This branch adds two objects, a second view and its destination, while preserving the primary consumer and durable raw-data path. The dead-letter table stores the failed raw message, error text, and _topic, _partition, and _offset metadata. Those coordinates show exactly which broker message failed. After a schema fix, reprocessing can use the dead-letter table without replaying the original topic, although the engine’s parse-error path should not be mistaken for validation of every transformation performed later in the view.
When the native Kafka Engine is the right choice and when an external connector is better
The native engine is a capable starting point because it requires no separate consumer service to deploy or monitor. Broker consumer groups retain offset state, while the three database objects define the ingestion path. Its constraint is resource coupling. Consumption and querying share the database process, so workloads that genuinely compete for resources can require a separate ingestion layer. Independent scaling is the architectural reason to move, rather than a general assumption that external connectors are more advanced.
Heavy enrichment and strict exactly-once requirements also call for an external connector architecture rather than reliance on the native at-least-once path. Kafka Connect with the database sink and ClickPipes are external options, with their delivery guarantees evaluated against the required contract. The managed option separates ingestion from compute at the infrastructure level. It has per-connector pricing and is available on Basic, Scale, and Enterprise plans. That separation changes which parts run where, but destination storage still needs to be designed correctly.
Using Materialized Views for pre-aggregation so dashboards do not scan the raw stream
The Materialized View mechanism also serves the query layer. A further view on the raw destination can populate an AggregatingMergeTree table with incrementally maintained aggregates, avoiding a separate processing job or scheduled refresh. Dashboard queries then read the rollup, avoiding repeated aggregation of the raw stream. A practical example groups by (class_id, toStartOfHour(event_time)) and stores AggregateFunction(count) states. Status-code breakdowns, time-windowed error rates, and per-domain throughput follow the same pattern.
SummingMergeTree handles additive aggregates such as counts and sums, while cardinality estimates need AggregatingMergeTree with uniqState and uniqMerge. Aggregate states keep the calculation working as intended when parts merge. This distinction becomes important when dashboards combine results across stored partial aggregates.
Projections provide another route for query patterns added after the original table design. They define a secondary sort order and pre-aggregation within the destination table, without requiring a separate table, but offer less flexibility than a standalone aggregate destination. Views can also form transformation chains through their backing tables. Parsing, normalization, and aggregation can therefore remain separate stages. The same primitive that connects consumption to storage can extend that storage into a query-acceleration layer.
Observability of the pipeline itself — knowing when the stream is healthy
Consumer progress begins with system.kafka_consumers, including consumer_id, num_messages_read, last_poll_time, and last_commit_time. A widening gap between polling and committing signals a stalled consumer. Partition-level diagnosis uses assignments.topic, assignments.partition_id, and assignments.current_offset. Lag still needs the broker-side reference point. The runbook should therefore pair those fields with broker lag output or the high-watermark offsets available through rdkafka_stat.
In system.parts, filtering to active = 1 and grouping by table derives active part counts. Rapid growth under sustained insertion points to under-batching or merges falling behind. system.merges shows background merges currently in progress. Together, these queries help show whether the consumer has a problem or storage work is slowing queries down.
Counting its rows by hour reveals the volume of parse failures, while stored broker coordinates make individual failures traceable. A spike calls for a check of upstream schema changes. These signals cover failures that successful dashboard queries alone would not reveal. Prometheus-compatible exporters can scrape the system tables, and Grafana can display them within the same observability stack used for application logs.
Putting the full pattern together — from a proof-of-concept to a production pipeline
Getting ready for production means making careful choices in eight connected areas. The first three are versioned three-object wiring, an ORDER BY key matched to dominant queries, and column encodings matched to data distributions. The fourth is coordinated block sizing with a flush interval suited to visibility requirements. The fifth is an explicit deduplication policy. The remaining three are a dead-letter branch, an aggregate destination for dashboard queries, and monitoring that covers consumer progress, active parts, and rejected messages.
These decisions remain relevant across deployment models. ClickHouse, an open-source analytical database built for real-time analytics at scale, ships the Kafka Engine natively and exposes virtual columns such as _offset and _partition for offset-aware routing inside the database. The self-managed native pattern has no licensing constraint. For teams choosing managed ingestion, Cloud with ClickPipes offloads consumer group management, offset tracking, and connector scaling while retaining the same destination-design and query concerns.