FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

MPP Query Engines (Trino / Presto)

Massively Parallel Processing query execution, stage scheduling, and memory spill management.

Freshness: current•16 min read•Data Engineering and Databases

Key Learning Outcomes

  • ✓Execute federated interactive queries across heterogeneous data stores using Trino
  • ✓Tune memory spill thresholds and query stage parallelization
Full Technical Reference Document

Mental model

Trino (formerly PrestoSQL) is a stateless, storage-decoupled Massively Parallel Processing (MPP) SQL query engine designed to join and scan petabyte-scale data directly across object-storage Iceberg/Delta/Parquet lakes, PostgreSQL, Kafka, and Elasticsearch inside interactive sub-second to multi-minute latency—without copying data into a proprietary monolithic warehouse first. Its speed hinges on pipelined, in-memory stage streaming: instead of checkpointing every intermediate stage blindly to disk (like legacy MapReduce), a single Coordinator compiles SQL into a distributed tree of Stages, Tasks, and SIMD vectorized Splits executed concurrently across dozens of stateless Workers—while deploying Dynamic Filtering and Broadcast vs. Partitioned Join strategies to avoid crippling cluster-wide network shuffles.

SQL Query Arrives at Trino Coordinator
Parse, Optimize & Plan Distributed Stages
Assign Parquet/Iceberg Splits to Workers
Broadcast Small Side & Dynamic-Filter Scans
Stream Pipelined Operators to Result Client
Conceptual teaching model synthesized from:trino-architecture-docs,ddia-kleppmann

Theory

Understanding Trino's execution hierarchy (Query -> Stage -> Task -> Pipeline -> Driver -> Operator -> Split) demystifies why identical SQL statements vary 50x in runtime latency depending on join ordering, partition layouts, and memory pressure:

Trino Execution ConceptRole in Distributed ClusterKey Performance / Tuning Lever
CoordinatorParses SQL, collects Connector column statistics, builds Cost-Based Optimizer (CBO) DAG, schedules splitsNever let the Coordinator process heavy worker joins (node-scheduler.include-coordinator=false in prod!)
Worker Nodes & SplitsStateless JVM engines streaming Parquet/ORC column chunks asynchronously via HTTP/2 internal exchangesCo-locate Workers & Iceberg object storage in the exact same cloud region/AZ; push filters + column projections down to Parquet!
Broadcast vs. Partitioned JoinBroadcast copies entire tiny build table (< 50 MB) to every probe worker (0 fact shuffle!); Partitioned hashes both large tables across workersjoin-distribution-type = AUTOMATIC requires up-to-date table/column statistics (ANALYZE) or CBO mis-picks wrong build tables!
Dynamic Filtering (enable-dynamic-filtering)Build-side join reads small key set first, then pushes min/max/set predicates directly down into giant fact table readers (skipping 90% of Iceberg partitions!)Dramatically cuts object-store S3 GET bandwidth & Parquet page decoding automatically

In-Memory Pipelined Execution vs. Fault-Tolerant Spooling (FTE) & Memory Spill

By default, Trino runs in pipelined mode: Worker Stage 2 starts consuming rows the microsecond Stage 1 emits them, maximizing interactive dashboard speed (0.5–5 s). However, classic pipelined execution carries two big trade-offs:

  1. Exceeding Worker Memory (Query exceeded per-node user memory limit): Massive GROUP BY cardinality explosions or un-skewed outer joins exhaust query.max-memory-per-node rapidly. Enabling Disk Spill (spill-enabled=true) lets Hash Aggregations and Hash Joins flush partial hash partitions cleanly to fast local NVMe SSDs—at steep throughput penalty (5x–15x slower than RAM!). Fixing missing join stats or skew beats hiding bad plans behind NVMe spill!
  2. Whole-Query Restart on Spot Instance Preemption: Because pipelined tasks lack intermediate durable buffers, losing one AWS EC2 Spot Worker 25 minutes into a heavy 10 TB ETL CTAS fails the entire query! Trino's Fault-Tolerant Execution (retry-policy = TASK) explicitly trades ultra-low interactive latency on batch ETL clusters for resilience by spooling intermediate shuffle exchanges to S3/HDFS so only the lost Worker's Task retries automatically rather than wasting 25 minutes across the cluster!
sql
-- Inspecting CBO join distribution & dynamic partition pruning via Trino EXPLAIN ANALYZE
EXPLAIN ANALYZE
SELECT
d.region_code,
COUNT(DISTINCT f.user_id) AS active_users,
SUM(f.token_cost_micros) AS total_cost_micros
FROM iceberg_lake.telemetry.llm_requests AS f
JOIN postgresql_prod.public.tenants AS d
ON f.tenant_id = d.id
WHERE d.plan_tier = 'enterprise'
AND f.event_date >= DATE '2026-11-01'
GROUP BY d.region_code;
​
-- Production Iceberg stats & Trino session hints for skewed joins / large batch ETL:
-- ANALYZE iceberg_lake.telemetry.llm_requests;
-- SET SESSION retry_policy = 'TASK'; -- Spool exchanges for long batch CTAS safety
-- SET SESSION join_distribution_type = 'AUTOMATIC';

Alternatives and trade-offs

  • Trino (PrestoSQL): Blazing interactive federated SQL speed across decoupled Iceberg/Delta lakes, Postgres, Kafka, and S3 with zero ingestion ETL copies needed, rich Resource Groups SLA isolation, and optional TASK-level fault tolerance; demands healthy table stats (ANALYZE) and right-sized object-store Parquet file sizes (128 MB–512 MB, never millions of tiny 10 KB files!).
  • Spark SQL / DuckDB: DuckDB shreds single-node analytical jobs up to a few hundred gigabytes on 1 fast NVMe/high-RAM machine cleanly with zero cluster overhead (10–50x simpler!). Spark dominates complex non-SQL Python/Scala UDF pipelines, MLlib, and multi-terabyte unstructured ETL, whereas Trino wins interactive BI & multi-user ad-hoc federation cleanly.
  • Monolithic Cloud Warehouses (Snowflake / BigQuery): Hands-off automated micro-partition compaction, zero JVM/spill cluster tuning, elastic virtual warehouse auto-suspend—at the cost of vendor storage egress/compute markup and less open external catalog portability compared to open Iceberg + Trino.

Failure modes and misconceptions

  1. Stale or Missing Table Statistics Flipping Join Build vs. Probe Sides: Without regular ANALYZE metadata updates on Hive/Iceberg tables, Trino's optimizer sees unknown row counts and accidentally broadcasts a 400 GB fact table to all workers instead of the 2 MB dimension table—triggering instant Exceeded local memory cluster crashes!
  2. Data Skew (NULL or Bot IDs Concentrating 80% of Rows on One Worker): Partitioned Hash Join / COUNT(DISTINCT) hashes NULL or a single "default_tenant" key identically onto Worker 7—leaving 31 sibling workers sitting completely idle at 99% done while Worker 7 OOMs! Filter out sentinel/null keys cleanly before joins or enable Trino skewed join scaling.
  3. Scanning Millions of Tiny 10 KB Streaming Files on S3 ("Metadata & S3 GET Bottleneck"): Streaming writers dumping tiny Parquet commits every 5 seconds destroy Trino scan speed (80% of query time spent opening S3 HTTP connections and Iceberg footers rather than scanning rows!). Schedule regular Iceberg optimize compaction jobs compacting partitions cleanly into 128 MB–512 MB files.
  4. Conflating Pipelined Interactive Clusters With Batch ETL Clusters Inside One Resource Pool: Letting one rogue BI analyst launch a massive cross-join ETL CTAS inside the interactive cluster starves sub-second dashboard queries cleanly unless separated via Trino Resource Groups (concurrency + cpu_quota isolation) or separate interactive vs retry_policy=TASK ETL clusters.
Reflect before revealing the guide

Decision scenario

Your data platform runs an Iceberg lakehouse on S3 alongside PostgreSQL operational metadata, serving both sub-second interactive product analytics dashboards (50 concurrent analysts) and heavy hourly 4 TB feature aggregation CTAS pipelines. Deploy two isolated Trino cluster pools sharing the same Iceberg catalog: (1) an Interactive Pipelined Cluster (node-scheduler.include-coordinator=false, join-distribution-type=AUTOMATIC, enable-dynamic-filtering=true, Resource Groups capping per-user memory and queued concurrency) fed by automated Iceberg compaction (256 MB Parquet files + scheduled ANALYZE statistics runs); and (2) an Elastic Batch ETL Cluster running retry_policy=TASK on cheap Spot Workers with exchange spooling enabled cleanly so long multi-hour jobs survive Spot interruptions cleanly without failing at 95%.

Learning outcomes

  • Trace Trino's execution model (Coordinator SQL/CBO plan -> Stage -> Task -> Pipeline -> Split) across stateless Workers.
  • Compare Broadcast Joins, Partitioned Hash Joins, and Dynamic Filtering and explain why missing ANALYZE stats break join ordering.
  • Know when to trade pipelined interactive speed for Fault-Tolerant Execution (retry_policy = TASK) and how disk spill interacts with latency.
  • Diagnose data-skew single-worker stalls and small-file S3 metadata overhead cleanly via Iceberg compaction.

Trade-offs

Trino unlocks blazing interactive SQL across open multi-cloud lakehouses and operational databases with zero vendor lock-in, yet pushes Parquet compaction hygiene, ANALYZE statistics refreshes, Resource Group governance, and join-skew debugging directly onto platform engineers.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next