Home / Data Platform / Databricks & Spark

Data PlatformHow-toAdvanced

Spark storage-partitioned joins on Iceberg: remove the shuffle and prove it in the plan

Design matching Iceberg partitioning, set the right Spark options and read the plan so large joins and MERGEs run without Exchange, plus what to do about skew and mixed specs.

Deepak Bhardwaj7 min read

Applies toApache Spark 3.4 to 4.x, Apache Iceberg tables through the DataSource V2 API

Goal

Two large Iceberg tables are joined on the same key several times a day, and most of the runtime is shuffle. If both tables are already laid out by that key, Spark can join matching partitions directly. This is a storage-partitioned join (SPJ). The plan loses its Exchange nodes before the join, and shuffle spill and fetch failures for that join go with them.

SPJ is worth it when the join is frequent, both sides are too big to broadcast, and you control both layouts. It is not worth it for a one-off join, or when filters reduce one side to broadcast size.

Requirements

Requirement Why
Both sides are V2 sources that report partitioning Plain Parquet and Hive tables don't qualify
Join is an equi-join on the partition source columns Spark must map join keys to reported partitions
Partition transforms match, e.g. bucket(64, id) on both Different bucket counts need an extra option, or a shuffle
Key types match, with no cast on the key bucket over a cast expression is a different expression
All live files share compatible partition fields Old specs reduce what Iceberg can report

Step 1: Design the layout

Pick the bucket count by the data per join task, not by file count. Each partition value becomes a task that reads both sides' files for that value, so it needs a similar size to a healthy shuffle partition, typically a few hundred MB combined.

CREATE TABLE lake.sales.orders (
  order_id BIGINT, customer_id BIGINT, amount DECIMAL(12,2), order_date DATE
) USING iceberg
PARTITIONED BY (bucket(64, customer_id));

CREATE TABLE lake.sales.customers (
  customer_id BIGINT, segment STRING, region STRING
) USING iceberg
PARTITIONED BY (bucket(64, customer_id));

Trade-offs to settle first:

  • More buckets mean more parallelism but more small files on each write.
  • Adding days(order_date) on one side helps pruning, but the join keys are then only a subset of that table's partition keys. That needs Spark 4.0 options (below).
  • Changing the bucket count later means rewriting the table.

Check the existing data

-- More than one spec means old layouts are still live
SELECT spec_id, count(*) AS files, sum(file_size_in_bytes) AS bytes
FROM lake.sales.orders.files GROUP BY spec_id;

-- Size and skew by partition
SELECT partition, count(*) AS files, sum(file_size_in_bytes)/1048576 AS mb
FROM lake.sales.orders.files GROUP BY partition ORDER BY mb DESC LIMIT 20;

If a table was altered to add bucketing, rewrite the old files into the current spec:

CALL lake.system.rewrite_data_files(
  table => 'sales.orders',
  options => map('rewrite-all','true','partial-progress.enabled','true')
);

Warning

rewrite-all rewrites the whole table. Budget for compute, for double storage until snapshots expire, and for commit conflicts with concurrent writers. Run it by partition filter (where) on big tables.

Step 2: Set the session options

SET spark.sql.sources.v2.bucketing.enabled=true;
SET spark.sql.sources.v2.bucketing.pushPartValues.enabled=true;
SET spark.sql.iceberg.planning.preserve-data-grouping=true;
SET spark.sql.requireAllClusterKeysForCoPartition=false;
Setting What it does
...v2.bucketing.enabled Turns on SPJ. Default depends on Spark version, so set it explicitly
...pushPartValues.enabled Handles partition values that exist on one side only
spark.sql.iceberg.planning.preserve-data-grouping Makes Iceberg keep splits grouped by partition; off by default
spark.sql.requireAllClusterKeysForCoPartition false allows join keys that don't exactly equal the partition keys in order

Missing preserve-data-grouping is the most common reason a correct layout still shuffles.

Spark 4.0 adds these, all off by default:

Setting (prefix spark.sql.sources.v2.bucketing.) Use when
allowJoinKeysSubsetOfPartitionKeys.enabled Table is partitioned by more columns than the join uses
allowCompatibleTransforms.enabled Transforms are compatible but not identical, such as different bucket counts
shuffle.enabled Only one side reports partitioning; shuffle just the other

Names and interactions have moved between releases, so confirm with SET -v and your version's SQL tuning guide.

Step 3: Prove it in the plan

Force a sort-merge join during testing so that a broadcast doesn't hide the result:

SET spark.sql.autoBroadcastJoinThreshold=-1;

EXPLAIN FORMATTED
SELECT o.customer_id, c.segment, o.amount
FROM lake.sales.orders o
JOIN lake.sales.customers c ON o.customer_id = c.customer_id;

Expected shape:

SortMergeJoin Inner
:- Sort
:  +- Filter
:     +- ColumnarToRow
:        +- BatchScan lake.sales.orders
+- Sort
   +- Filter
      +- ColumnarToRow
         +- BatchScan lake.sales.customers

There must be no Exchange hashpartitioning between the scans and the join. The sort stays: SPJ removes the shuffle, not the sort. In the Iceberg scan details, a groupedBy value shows the grouping Iceberg reported; if it is empty, the problem is on the Iceberg side (layout or preserve-data-grouping) and not in the join rules.

Check it in code and fail a test if the shuffle returns. This query has no aggregation or final sort, so any Exchange belongs to the join:

df = spark.sql("""
  SELECT o.customer_id, c.segment, o.amount
  FROM lake.sales.orders o
  JOIN lake.sales.customers c ON o.customer_id = c.customer_id""")
plan = df._jdf.queryExecution().executedPlan().toString()
assert "Exchange hashpartitioning" not in plan, plan

This uses PySpark internals on a classic session; it isn't available through Spark Connect.

Step 4: Use it in MERGE

MERGE INTO joins target and source, so a staging table bucketed like the target can avoid that shuffle:

MERGE INTO lake.sales.orders t
USING lake.staging.orders_delta s
ON t.customer_id = s.customer_id AND t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;

Expect another exchange after the join: Iceberg's write distribution clusters rows for the writers. write.merge.distribution-mode controls it. Setting none removes that exchange but can create many small files, so measure before changing it.

When it doesn't work

Symptom Cause Fix
Both sides still exchange preserve-data-grouping is off, or mixed specs Set it; rewrite old files
One side exchanges Transform or bucket count mismatch, cast on key Align types and buckets
Only exchanges with extra join keys Strict co-partition rule requireAllClusterKeysForCoPartition=false
Few tasks, cluster idle Bucket count below core count More buckets, or accept a shuffle
One task runs for hours Skewed bucket See below
Executors OOM in scan or sort Too much data per partition value More buckets; compact delete files

Skew

AQE's skew-join handling works on shuffle partitions. With no shuffle it has nothing to split, so SPJ can turn a manageable skew into one very long task. Two options:

SET spark.sql.sources.v2.bucketing.partiallyClusteredDistribution.enabled=true;

This lets Spark split one side's large partitions and replicate the matching side. It doesn't apply to full outer joins, and may not combine with the compatible-transform option. If one key dominates, switch SPJ off for that query and let AQE split the shuffle:

SET spark.sql.sources.v2.bucketing.enabled=false;

Prevent it next time

  • Put bucket counts and key types in a shared table standard, so that joined tables match.
  • Run the plan assertion in CI against small tables with the production spec.
  • Re-check spec_id counts after any ALTER TABLE ... PARTITION FIELD.
  • Chart max-versus-median task time; SPJ skew appears there first.
  • Retest after Spark or Iceberg upgrades, because defaults change.