Zero Labs
Industry News / AI

Part XII — Choosing the Right Query Engine: One Engine to Rule Them All?

Source · Towards AI By chakshu_salgotra

From the publisher’s feed, collected in the ZeroLabs newsroom.

Spark vs Trino vs Presto vs ClickHouse vs Flink vs Druid — six engines, four execution models, and the workload-routing decisions that separate a $20K platform from an $85K onePart I | Part II | Part III | Part IV | Part V | Part VI | Part VII | Part VIII | Part IX | Part X | Part XI |Part XIIThe Platform That Standardized on the Wrong EverythingA 40-person data platform team standardizes on Spark. “One engine, one skill set, one cluster to babysit.” Eighteen months later the bill arrives:BI dashboards hit Spark Thrift Server. p95 latency: 47 seconds. Analysts open a dashboard, get coffee, come back. The fix so far has been adding executors — the cluster is now 3x oversized and still slow, because the problem is architectural, not capacity.The fraud-scoring pipeline runs Spark Structured Streaming with a 5-second micro-batch trigger. End-to-end latency: 6–9 seconds. The fraud team’s SLA is 500ms. Transactions are approved before the score arrives.The clickstream analytics product — customer-facing, high-concurrency slice-and-dice over 90 days of events — runs ad-hoc Spark SQL. Concurrency above 15 users triggers scheduler queueing; p99 goes to 2+ minutes.Total spend: $85K/month, and every workload class is missing its SLA simultaneously.Nothing here is a tuning problem. Each failure is a workload running on an engine whose execution model was designed for a different job. So: what do Spark, Trino, Presto, ClickHouse, Flink, and Druid actually do differently at the engine level — and how do you route workloads so each one runs on the physics that favors it?The Axis That Actually Matters: Execution Model, Not BenchmarksVendor benchmarks compare engines on the same query. That’s the wrong lens. These six engines make different fundamental trade-offs, and each trade-off is a deliberate design decision, not an implementation gap. Four execution models cover all six:Druid is a special case — a pre-aggregating, segment-based scatter-gather engine that trades query flexibility for guaranteed sub-second response at high concurrency. We’ll get there.Spark: Materialized Shuffle Is a Feature, Not a BugSpark executes queries as a DAG of stages separated by shuffle boundaries (Part IV of this series covered the job/stage/task hierarchy in depth). At every boundary, intermediate data is materialized — written to local disk by map tasks, then fetched by reduce tasks. This is Bulk Synchronous Parallel execution: stage N must fully complete before stage N+1 starts.That materialization is exactly why Spark dominates long-running batch:Stage-level retry. A lost executor re-runs only the lost tasks, reading the surviving shuffle files. A 6-hour job survives hardware failure without restarting.Speculative execution and dynamic allocation work because stage outputs are durable checkpoints.AQE (adaptive query execution) can re-plan mid-query — coalesce partitions, switch join strategies — because the shuffle boundary gives it a synchronization point with real statistics.The same materialization is why Spark loses interactive workloads. A dashboard query pays for: JVM task scheduling overhead, shuffle write + fetch on every exchange, and stage barriers that serialize the pipeline. Sub-second is not on the menu; Spark’s floor for a non-trivial SQL query is seconds. The 47-second dashboard wasn’t misconfigured Spark — it was correctly configured Spark doing what BSP does.Trino and Presto: Pipelined MPP, and Why the Fork MattersTrino and Presto share DNA — Trino forked from PrestoDB in 2019 (the original Presto creators left Facebook) — and both execute the opposite bet from Spark: fully pipelined, in-memory MPP.Operators stream pages (columnar batches) between stages over the network while the query runs. No stage barriers, no shuffle materialization.The first rows can reach the client before upstream stages finish. Latency floor: hundreds of milliseconds, even federating over S3/HDFS/Iceberg plus a Postgres catalog in one query.The classic cost: a single worker failure killed the whole query. No materialized intermediates means nothing to retry from. Acceptable for a 4-second dashboard query; fatal for a 4-hour ETL job.That trade-off is why “Trino for ETL” was long an anti-pattern. It’s also where the fork’s paths diverged:Trino added fault-tolerant execution (spooling intermediate exchange data to object storage, enabling task-level retry) — deliberately re-introducing a Spark-like durability layer, but opt-in per workload, so interactive queries keep the pipelined fast path.Presto (Meta’s line) invested in native vectorized execution — the Velox-based C++ evaluation engine — attacking the JVM interpretation overhead itself.Decision rule: same SQL frontend category, but Trino is the stronger default for lakehouse interactive + federation (Iceberg/Delta connector velocity, fault-tolerant ETL mode), while Presto matters mostly if you’re operating at Meta-adjacent scale or invested in its ecosystem.ClickHouse: Speed by Refusing to DecoupleTrino reads open formats over object storage. ClickHouse’s answer to “why are you 10x faster on scans?” is: because I own the storage engine.MergeTree tables store data in sorted, immutable parts, ordered by the table’s ORDER BY key, with sparse primary indexes (one mark per ~8,192 rows). A query filtering on the sort key prunes granules before touching data — the same job partition pruning does in a lakehouse, but at 8K-row resolution instead of file-level.Execution is vectorized SIMD over compressed columns, with specialized codecs (Delta, DoubleDelta, T64) chosen per column. There is no connector, no page exchange to a foreign format — scan-to-aggregate is one tight loop.Aggregation offers engine-specific operators that eliminate whole execution phases (see the code below).The costs are symmetric to the benefits:Storage is coupled to compute. Scaling reads means replicas that hold data (cloud-native ClickHouse variants relax this, at an operational and dollar cost).Distributed joins are the weak spot. ClickHouse wants a big fact table joined to dimensions that fit in memory (JOIN via hash table on every node, or dictionary encoding). Reshuffling two 10TB tables against each other is Spark/Trino territory.Point lookups and frequent updates fight the immutable-parts model — mutations are asynchronous rewrites, not in-place edits.Route to ClickHouse: high-QPS aggregations over a known schema — the customer-facing analytics product from the hook. That workload moved from ad-hoc Spark SQL (p99 2min at 15 users) to a ClickHouse MergeTree sorted by (tenant_id, event_date): p99 of 380ms at 200 concurrent users, on 3 nodes.Flink: The Only One That’s Actually StreamingSpark Structured Streaming processes micro-batches — small BSP jobs on a trigger (Part VIII of this series covered batch vs streaming execution contracts in depth). Flink executes a continuous dataflow: operators are long-lived, events flow through one at a time (with network buffering), and state lives inside the operators.The engine mechanics that matter:Event-at-a-time processing gives a latency floor of milliseconds, not trigger intervals. The 500ms fraud SLA is trivially achievable; it was structurally impossible on a 5s micro-batch.State backends: operator state (e.g. per-card rolling aggregates) lives in embedded RocksDB, local to the task, scaling to TBs of keyed state without an external store round-trip per event.Checkpointing uses asynchronous barrier snapshots (a Chandy–Lamport variant): barriers flow through the dataflow with the data, each operator snapshots its state on barrier arrival, producing a globally consistent snapshot without pausing processing. Combined with two-phase-commit sinks, this yields exactly-once end-to-end.Event-time semantics with watermarks are native, not bolted on: out-of-order events are handled by the time model, not by “wait longer and hope.”The trade-off: Flink is an operationally heavier system to run for pure batch (though its batch mode runs the same dataflow with staged scheduling), and its SQL ecosystem for ad-hoc analytics is thinner than Trino’s. Flink is a processing engine — it computes over streams; it is not where analysts point dashboards.Druid: Pre-Aggregation as an ArchitectureDruid answers a narrower question than everything above: “sub-second aggregations over event streams, at high concurrency, including data ingested seconds ago.” It gets there by doing work at ingestion time that other engines do at query time:Rollup: events are optionally pre-aggregated at ingestion to a chosen granularity — raw events may never be stored. A query over “events per campaign per minute” reads pre-summed rows.Segments: immutable, time-partitioned, columnar files with bitmap inverted indexes on dimensions. A filter on country = 'DE' is a bitmap intersection, not a scan.Scatter-gather tiering: real-time ingestion tasks serve the last few minutes from memory; historical nodes serve immutable segments; a broker fans out and merges. Recent + historical data unify in one query with no lambda-architecture glue.The cost is flexibility: joins are limited (broadcast-style lookups), SELECT * on raw events may be impossible post-rollup, and schema changes ripple through segment rebuilds. Druid vs ClickHouse is the most common confusion — the honest split:Druid when: streaming-first ingestion, extreme concurrency (hundreds of QPS), tolerance for pre-modeled queries, operational appetite for a multi-role cluster.ClickHouse when: richer SQL, better joins, simpler operations, and you can live with near-real-time (seconds) instead of real-time ingestion visibility.The Routed ArchitectureThe fix for the platform in the hook was not a better engine. It was routing each workload class to the engine whose execution model matches it:Presto slots where Trino sits (same role, different lineage); Druid slots where ClickHouse sits when ingestion-time rollup and higher concurrency outweigh SQL flexibility.Result for the team in the hook: dashboards moved from Spark Thrift Server to Trino over the same Iceberg tables — 47s p95 → 3.2s, zero data migration. Fraud scoring moved to Flink — 6–9s → 320ms end-to-end. The analytics product moved to ClickHouse. Spark kept what Spark is best at: the nightly 4TB ETL and feature engineering. Total spend: $31K/month — because each engine ran a workload it doesn’t have to fight.The Same Query, Three Engines“Latest status per user” — a query every platform runs — shows how engine-aware SQL diverges from portable SQL:-- Naive (portable, runs everywhere): window sort over every row-- Spark: full shuffle + sort per partition. Trino: same, pipelined but still O(n log n) per key group.WITH ranked AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY user_id ORDER BY event_ts DESC ) AS rn FROM events)SELECT user_id, status FROM ranked WHERE rn = 1;-- ClickHouse-optimized: one aggregation pass, no window state, no sortSELECT user_id, argMax(status, event_ts) AS latest_statusFROM eventsGROUP BY user_id;The Spark equivalent avoids the window-induced shuffle-and-sort the same way:from pyspark.sql import functions as F# Naive: Window.partitionBy("user_id").orderBy(F.desc("event_ts")) + row_number# Optimized: single hash aggregation — partial aggregates before the shufflelatest = ( events.groupBy("user_id") .agg(F.max_by("status", "event_ts").alias("latest_status")))And in Flink, the question dissolves entirely — “latest per key” is not a query over stored history, it’s retained operator state updated per event:-- Flink SQL: continuous query; state holds exactly one row per user_id,-- updated in milliseconds as events arrive. No nightly recompute at all.SELECT user_id, LAST_VALUE(status) AS latest_statusFROM eventsGROUP BY user_id;Same business question. In batch engines it’s an aggregation strategy choice; in a streaming engine it’s a materialized view that never goes stale. That reframing — not syntax — is what choosing an engine actually means.The Decision MatrixWorkloadEngineWhy (engine mechanics)Multi-TB ETL, ML feature prepSparkMaterialized shuffle → stage retry, AQE, survives node loss on 6h jobsInteractive BI over the lakehouseTrinoPipelined MPP, no materialization, sub-second floor, Iceberg-nativeCross-source federation (lake + OLTP)Trino/PrestoConnector-based MPP; one SQL plan spanning catalogsCustomer-facing analytics, high QPSClickHouseStorage-coupled MergeTree, sparse index granule pruning, SIMD scansSub-second streaming with stateFlinkEvent-at-a-time dataflow, RocksDB state, barrier snapshots, exactly-onceReal-time slice-and-dice at 100s of QPSDruidIngestion-time rollup, bitmap indexes, scatter-gather over segmentsThree rules that survive contact with production:Decouple storage first, engines second. Iceberg/Delta on object storage let Spark and Trino share tables — the dashboard fix required zero data movement. Engines become swappable; data gravity stops dictating architecture.Route by latency class, not by team familiarity. Batch (minutes–hours) → Spark. Interactive (sub-second–seconds) → Trino or ClickHouse. Streaming (milliseconds) → Flink. Concurrency-heavy pre-modeled analytics → ClickHouse or Druid. Every mismatch in the hook was a latency-class violation.Two engines is a platform; five is a pathology. Most teams need exactly: one batch engine, one interactive engine, and — only if there’s a genuine millisecond SLA — one streaming engine. Add ClickHouse/Druid only when a customer-facing product demands it. Each additional engine is an on-call rotation, an upgrade treadmill, and a semantic-drift risk.TakeawaysMaterialize or pipeline — pick your poison: Spark’s “slowness” on dashboards and Trino’s classic mid-query fragility are the same design decision viewed from opposite sides: materialize the shuffle (durable, slow) or pipeline it (fast, fragile). Trino’s fault-tolerant execution and Spark’s AQE are each engine borrowing the other’s trade-off — opt-in.Speed comes from owning storage: ClickHouse and Druid are fast because they own their storage layout (MergeTree parts, rolled-up segments) — the price is coupling and join weakness. Trino is flexible because it owns nothing — the price is the scan speed ceiling of open formats over object storage.Milliseconds need a standing computation: Flink is the only engine here where “latest state per key” is a standing computation rather than a repeated query — if your SLA is milliseconds, no batch engine tuning gets you there.Forks diverge on priorities: Presto vs Trino share the same execution model with diverged priorities — Trino for lakehouse velocity and fault-tolerant ETL mode, Presto/Velox for native-code execution at extreme scale.Routing beats tuning: the $54K/month saving came from routing, not tuning: shared Iceberg tables underneath, and each workload on the engine whose physics it matches.If this saved you a 3 AM pager incident, follow me on Medium for Twice a week for the next 3 Months of Advanced Data Engineering & AI. Let’s connect on LinkedIn and X.Part XII — Choosing the Right Query Engine: One Engine to Rule Them All? was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.