Lakehouse Query Performance Tuning: 8 Techniques
Tune lakehouse query performance with eight techniques for pruning, files, statistics, caching, and concurrency. Use Spark SQL examples and fair tests.
Image Source: unsplash
Direct answer: Diagnose the measured bottleneck before you tune anything. Read the query plan, check files actually scanned, and confirm where time goes. Data layout (column projection, partition pruning, clustering, compaction), engine planning (statistics, join plans), materialization, cache behavior, and concurrency each move a different number. Tune one lever at a time, then re-measure under identical conditions.
This guide is written for data engineers and analytics engineers who already run Spark SQL against a lakehouse table and now need to know which knob to turn, how to prove it helped, and where each technique stops working. Nothing here is a guaranteed speedup — a technique that fixes your scan problem can do nothing for a shuffle-bound query.
Key Takeaways
Start from evidence:
EXPLAIN FORMATTED, scanned-bytes counters, and stage timings, not from a list of tricks.Column pruning and predicate pushdown usually cost nothing to adopt, because they change what the query asks for rather than what the storage layer holds.
Layout work such as clustering and small-file compaction pays off for selective scans but adds maintenance overhead and rarely helps full-table aggregations.
Statistics, materialization, caching, and concurrency isolation fix different failure modes; applying the wrong one hides the real bottleneck.
Compare only like with like: same snapshot, same query, same concurrency level, and cold runs separated from warm runs.
Technique 1: Column Pruning
Column pruning means selecting only the columns a question needs. In a columnar format such as Parquet, unprojected columns are skipped at read time, so SELECT * on a wide table reads far more bytes than the query uses. This is the cheapest technique in the list, and the most commonly skipped.
Check it first in the plan. The scan node's Statistics block in Spark's formatted plan output reports read size and row counts, and it lists the columns read, which is where projection shows up.
Example configuration — validate in your target environment.
These examples are illustrative and were not executed for this article. They assume a Spark 3.x SQL session with read access to a table named trading.document_line_items (columns: document_id, document_date, region, product_id, quantity, unit_price). Syntax shown is Spark SQL and is not universal across lakehouse engines or Singdata's own interface.
-- Illustrative shape of a measurement query: the select list here is narrow,
-- so the plan should list only region, document_date, quantity, and unit_price
EXPLAIN FORMATTED
SELECT region, SUM(quantity * unit_price) AS revenue
FROM trading.document_line_items
WHERE document_date >= '2026-01-01'
GROUP BY region;
This is a projection demonstration, not a before/after measurement. To test column pruning, keep the select list, filter, and aggregation identical and change only which columns the scan returns; comparing this against a SELECT * query changes two things at once, so any difference can't be attributed to column pruning.
Technique 2: Predicate and Partition Pruning
Predicate pushdown pushes filters down to the scan. Partition pruning goes further and removes whole partitions before files are even opened. When both work, a query that asks for one month of one region reads a fraction of the table.
The evidence is in the number of files listed in the plan's scan node, not in the runtime. If a filter appears in the plan below the scan and the file count doesn't drop, your predicate isn't being pushed — often because of a function wrapping the partition column or a type mismatch. Optimizers vary, though: Spark and several lakehouse engines can rewrite some function predicates, so a wrapped column is a thing to check, not proof that pruning fails everywhere.
Example configuration — validate in your target environment.
-- Filter written so the partition column stays unwrapped
EXPLAIN FORMATTED
SELECT region, SUM(quantity * unit_price) AS revenue
FROM trading.document_line_items
WHERE document_date BETWEEN DATE '2026-03-01' AND DATE '2026-03-31'
AND region = 'APAC'
GROUP BY region;
-- Same intent and the same region filter; only the date predicate form differs
EXPLAIN FORMATTED
SELECT region, SUM(quantity * unit_price) AS revenue
FROM trading.document_line_items
WHERE substr(CAST(document_date AS STRING), 1, 7) = '2026-03'
AND region = 'APAC'
GROUP BY region;
Both queries carry region = 'APAC', so the only difference is whether the partition column is left bare or wrapped in a function. Read the scan node for PartitionFilters, ReadSchema, and PushedFilters: if all three look the same in both plans, the optimizer rewrote the function predicate and pruning still works. If PartitionFilters is empty in the second, the filter didn't reach the scan. Either outcome is a fact about your engine and your table, not a general verdict.
Technique 3: Clustering and Sort Order
Partitioning narrows to a directory; clustering and sort order narrow to files and row groups within it. Sorting by the column you filter most lets file-level and row-group statistics skip whole blocks. This is where the term "data clustering" gets overloaded, so be precise about which mechanism you own:
Delta Lake:
OPTIMIZE ... ZORDER BYis the documented multi-column clustering mechanism.Apache Iceberg: compaction rewrites data files, and sorted or clustered layouts depend on the writer and engine; check your engine's documentation for supported syntax.
Generic Hive-style tables: clustering is a write-time
SORT BYorDISTRIBUTED BYdecision, not something you can fix with a metadata call afterwards.
Don't assume the commands transfer between formats. A Z-order statement copied from Delta into an Iceberg table is, at best, a no-op and, at worst, an error. Confirm the syntax in the documentation for the exact engine, catalog, and table format you run.
Technique 4: Small-File Compaction
Streaming ingestion creates small files, and each one costs an open, a footer read, and a planning entry. Compaction merges them. The trade-off is real, so treat it as a scheduled maintenance job rather than a permanent fix: it rewrites data, it consumes compute, and it should respect retention rules so you don't compact files that are about to expire.
Measure the effect by counting files in the scan before and after, and by re-running the identical query on the same snapshot that contains the compacted files. Our walkthrough on compaction and streaming latency covers the write-amplification side.
Technique 5: Statistics and Join Plans
Join strategy depends on what the optimizer knows. Without table and column statistics, Spark picks a shuffle hash join where a broadcast would do, or misjudges which side is smaller. ANALYZE TABLE refreshes those statistics; broadcast thresholds and hints then shape the decision.
Example configuration — validate in your target environment.
Not executed for this article. Prerequisite: trading.product_catalog must have product_id as a unique key. If it doesn't, the join fans out and inflates quantity * unit_price, so the result measures duplication rather than query speed.
-- Refresh statistics so the optimizer can size inputs
ANALYZE TABLE trading.document_line_items COMPUTE STATISTICS;
ANALYZE TABLE trading.product_catalog COMPUTE STATISTICS FOR COLUMNS product_id;
-- Then inspect join selection before changing anything
EXPLAIN FORMATTED
SELECT d.region, p.category, SUM(d.quantity * d.unit_price) AS revenue
FROM trading.document_line_items d
JOIN trading.product_catalog p ON d.product_id = p.product_id
WHERE d.document_date >= '2026-01-01'
GROUP BY d.region, p.category;
Join selection appears in the plan as the join operator type. If you see a shuffle exchange feeding a sort-merge join for a small right-hand side, statistics or the broadcast threshold are the suspects — not the storage layout.
Technique 6: Materialization
Materialization trades freshness and storage for repeat cost. A dashboard that recomputes the same aggregate hourly doesn't need to recompute it; a materialized view or a periodically refreshed summary table serves it from a smaller snapshot instead.
The limitation matters more than the benefit. Materialized results are only as fresh as the last refresh, they need their own maintenance, and they don't help ad-hoc queries with new filters. Fixing a slow interactive query by caching its answer only helps if someone asks the same question again.
Technique 7: Cache Validation
Caching in Spark is often assumed and rarely verified. CACHE TABLE followed by a scan doesn't guarantee the cache was actually used — different executors or a re-planned query can silently bypass it. Confirm usage from the plan and counters, then measure warm runs separately from cold.
Example configuration — validate in your target environment.
Not executed for this article. CACHE TABLE materializes the table eagerly, which costs memory across your executors, so run this in an isolated trial session and release it afterwards.
-- Materializes the table into executor memory up front
CACHE TABLE trading.document_line_items;
EXPLAIN FORMATTED
SELECT region, SUM(quantity * unit_price) AS revenue
FROM trading.document_line_items
WHERE document_date BETWEEN DATE '2026-03-01' AND DATE '2026-03-31'
GROUP BY region;
-- Inspect the plan for an InMemoryTableScan or InMemoryRelation
-- before concluding the cache helped
-- Release the cached copy when the test is done
UNCACHE TABLE trading.document_line_items;
Seeing InMemoryTableScan in the plan is evidence; a faster wall-clock number might be coincidence. If the node is absent, your query is reading from storage and the cache is irrelevant to the timing.
Technique 8: Concurrency Isolation
A query's runtime on a shared cluster reflects its neighbours. If a heavy batch job saturates I/O or shuffle capacity, your interactive query slows down without changing a single byte of its own plan. That's a resource-shape problem, and layout tuning won't touch it.
Separate workloads into pools or warehouses with their own limits, and cap the resources an exploratory query can consume. The evidence you need is per-query resource use, not a blended cluster average. Compare the same query at the same concurrency level before and after isolating it — otherwise you're measuring your neighbour's job.
Troubleshooting Table
Use this to move from a symptom to a first test. Each row is a hypothesis with a way to check it and a reason it can fail.
Symptom | Action | Evidence to check | Limitation |
|---|---|---|---|
Query reads far more bytes than rows returned | Add column pruning; select explicit columns | Scan Statistics read size in EXPLAIN FORMATTED | No effect when the query genuinely needs most columns |
Filter present but file count unchanged | Rewrite predicate on the raw partition column | Files listed in the scan node | Engines may already rewrite some expressions |
Selective scan still slow with pruning working | Cluster or sort on the filtered column | Row-group/file skipping counters | Adds write cost; unhelpful for full-table scans |
Planning time grows, many tiny files | Schedule compaction within retention | File count before and after | Rewrites data; needs compute and retention rules |
Large shuffle, small build side | ANALYZE TABLE, review broadcast threshold | Join operator in the plan | Stale stats return quickly after heavy ingestion |
Repeated dashboard aggregation slow | Materialize the aggregate | Refresh age vs query cost | Stale between refreshes; no help for new filters |
Cached table still slow | Verify cache in the plan | InMemoryTableScan present or absent | Cache can be lost on re-planning or new executors |
Performance shifts by hour of day | Isolate workloads into pools | Per-query resource use, not cluster averages | Needs governance and capacity planning |
Measurement Protocol
Every technique above is a hypothesis about a bottleneck. To know whether it worked, hold the conditions fixed:
Same snapshot. File sets, statistics, and clustering all live in the table metadata, so a background job landing new data mid-test changes the input. Pin the snapshot or freeze ingestion.
Same query text. A slightly different
SELECTlist or filter is a different query. Save the exact SQL and theEXPLAIN FORMATTEDoutput for each run.Same concurrency. Run trial queries in the same pool with the same number of parallel sessions. Benchmarks taken alone and compared against a busy-production number are not a comparison.
Cold and warm reported separately. A cold run includes storage reads and cluster start-up; a warm run hits cache and page cache. Averages that blend the two hide both.
Record scan bytes, shuffle bytes, spilled bytes, and total stage time alongside wall-clock duration. If scan bytes didn't fall, a layout change didn't do what you intended, whatever the clock says.
Why It Slows Down: A Short Diagnosis
The least productive habit in tuning is applying a fix before naming the problem. Our deep dive on columnar storage and sub-second queries follows the same logic: read a lot, compute a little. If your plan shows a full scan and a small result, the problem is layout; if it shows a big exchange and a long sort, it's planning and shuffle; if nothing changed in the plan but the clock moved, it's the cluster around you.
None of these techniques is universal. Pick the one that matches the symptom you can measure, validate it in your own environment, and keep the evidence — plan output, scan bytes, and a cold/warm split — so the next engineer on the platform can reproduce your result.
FAQ
How do I know which technique to try first?
Read the plan before you touch anything. Look at the leaf scan node's Statistics for bytes read, then at the exchanges and joins above it. If bytes read dwarf the result size, start with pruning, partitioning, or clustering. If the scan looks lean but a large exchange dominates, start with statistics and join plans. If the plan is unchanged but timing varies by hour, look at concurrency.
Can I copy Delta Lake Z-Order commands onto an Iceberg table?
No. OPTIMIZE ... ZORDER BY is a Delta Lake feature. Iceberg compaction is a separate maintenance operation, and sorted layouts depend on the writer and engine you run. Verify the supported syntax in the documentation for your engine and table format; if the docs don't cover it, don't run it.
Does caching always make queries faster?
Only when the cache is actually used and the query would otherwise read from slower storage. Check the plan for an in-memory scan node before crediting the cache. A second run can also be faster simply because the OS page cache is warm, which has nothing to do with Spark's cache.
How should I report a tuning result?
Report scan bytes, shuffle bytes, and wall-clock time together, on the same snapshot, with the same query and concurrency. State whether the run was cold or warm. A single faster number without those conditions isn't evidence of a real improvement.
See Also
A Practical Checklist Before You Blame the Engine
How Iceberg And Parquet Enhance Data Lake Efficiency
Partitioning Strategies That Hold Up Under Real Workloads
Spark SQL Join Efficiency on Terabyte Datasets
Comparing Apache Iceberg And Delta Lake Solutions