All posts

What's new in Apache Spark 4.3

Spark 4.3 new features: stateful real-time streaming, Auto CDC with history, JSON_TABLE, ASOF JOIN, VARIANT editing and more. Each feature has its area, a source ticket, the code before and with 4.3, and a plain note on what needs a flag or a connector.

51 min read Spark

Spark 4.3.0 shipped on 30 October 2026, 108 days after 4.2.0. It’s the first feature release on the quarterly cadence in the versioning policy, the fourth of the 4.x line, and the release notes count over 1,100 Jira tickets from more than 210 contributors.

Two themes stand out. Streaming grows up: stateful queries, the ones that keep a running count or drop duplicates, now run under the real-time trigger. And SQL finally gets standard answers to three old workarounds: reading JSON as rows, matching each row to the closest earlier row, and keeping the history of a changing record. Around those sit smaller changes to Spark Connect, data types, caching and Python UDFs.

The ten features below each show the code you’d have written before 4.3, the code you write now, and what it needs first, whether that’s nothing, a flag or a connector. New to Spark 4? The glossary is a good start, and the install steps come right after the overview image. Spark 4.2 is the previous release, and the features-by-release post puts them all side by side.

Spark 4.3.0 closed over 1,100 Jira tickets with more than 210 contributors, 108 days after 4.2.0; the four 4.x releases are 207, 210 and 108 days apart

Image 1: Spark 4.3.0 in numbers, and the gaps between the four 4.x releases.

Spark 4.3 features, each with what it replaces and what you write now, and the two ways to install it

Image 2: Spark 4.3 by area, with what each feature replaces and what you write now.

Key takeaways

  • Real-time mode now runs stateful queries (aggregation, dropDuplicates, Scala and Java transformWithState) with only a trigger change. Budget a free task slot for every task.
  • Auto CDC can keep the full history of a row with SCD Type 2. TRACK HISTORY ON picks which columns open a new version, and the target must support row-level operations.
  • JSON_TABLE, UNNEST, the VARIANT editing functions and @ time travel work out of the box. ASOF JOIN and BIN BY sit behind flags.
  • Single-task execution removes both shuffles from an eligible small query, and an Arrow-native cache is opt-in.
  • Python 3.10 is gone and a few defaults changed, so read the upgrade checklist before you move.

Features at a glance

Feature Area On by default? How to turn it on
Stateful real-time mode Structured Streaming Yes, with the real-time trigger Trigger.RealTime("5 seconds") or trigger(realTime="5 seconds"), with update output mode
Auto CDC with SCD Type 2 Declarative Pipelines Yes STORED AS SCD TYPE 2; the target needs row-level operations
JSON_TABLE, UNNEST, VARIANT editing, new functions SQL Yes Nothing
ASOF JOIN SQL No, preview spark.sql.join.asofJoin.enabled=true
BIN BY SQL No spark.sql.binByRelationOperator.enabled=true
TIME(p) Types No spark.sql.timeType.enabled=true
Nanosecond timestamps Types No, preview spark.sql.timestampNanosTypes.enabled=true
DataFrame.zip DataFrame API Yes Nothing
Single-task execution Performance No spark.sql.optimizer.singleTaskExecution.enabled=true
Arrow-native Dataset cache Performance No spark.sql.cache.serializer=org.apache.spark.sql.execution.columnar.ArrowCachedBatchSerializer, set at start
Archive reader File sources No spark.sql.files.archive.reader.enabled=true
Connect operation IDs and REST endpoints Spark Connect Yes Nothing
Local Connect server reuse Spark Connect No, experimental SPARK_LOCAL_CONNECT_REUSE=1
Python UDF transpiling PySpark No, experimental spark.sql.experimental.optimizer.transpilePyUDFs=true with ANSI mode on

Before you start

What you need

Need Detail
Java 17, 21 or 25, per the Spark 4.3.0 overview
Python, for PySpark 3.11 or newer
Spark The apache/spark:4.3.0-python3 image, or the 4.3.0 release tarball (535 MiB)
Kafka A broker, for feature 1 only
A table with row-level operations For feature 2 only: the target connector must support MERGE

Install Spark 4.3

Pick one.

Option 1: pip. The wheel bundles Spark, so you only need Java (17, 21 or 25) and Python 3.11 or newer.

python3 -m venv .venv && source .venv/bin/activate
pip install pyspark==4.3.0
python -c "import pyspark; print(pyspark.__version__)"

The last command prints 4.3.0.

Option 2: the release tarball in a common path. Download it, check the checksum, unpack it under /opt and point SPARK_HOME at a stable link.

curl -LO https://archive.apache.org/dist/spark/spark-4.3.0/spark-4.3.0-bin-hadoop3.tgz
curl -s https://archive.apache.org/dist/spark/spark-4.3.0/spark-4.3.0-bin-hadoop3.tgz.sha512
shasum -a 512 spark-4.3.0-bin-hadoop3.tgz   # compare with the line above
sudo tar -xzf spark-4.3.0-bin-hadoop3.tgz -C /opt
sudo ln -sfn /opt/spark-4.3.0-bin-hadoop3 /opt/spark
export SPARK_HOME=/opt/spark PATH=/opt/spark/bin:$PATH
spark-submit --version

The file is 561,204,042 bytes (about 535 MiB). spark-submit --version reports version 4.3.0 and Scala 2.13.18. Add the two export lines to ~/.zshrc or ~/.bashrc to keep them. If the version printed isn’t 4.3.0, an older SPARK_HOME in your shell is winning; start with env -u SPARK_HOME.

Glossary

Term Meaning
Micro-batch Structured Streaming’s default: the stream is run as a series of small batch jobs
Real-time mode A streaming mode where long-lived tasks process records as they arrive, with no batch boundary
Shuffle Moving data between stages so that rows with the same key meet on the same task
Task slot One unit of parallelism on an executor. Real-time mode needs a free slot for every task
CDC Change data capture: a feed of inserts, updates and deletes from a table
SCD Slowly changing dimension. Type 1 overwrites old values; Type 2 keeps every version as a row
VARIANT The Spark type for semi-structured data such as JSON, encoded once in binary
As-of join A join that matches each row to the closest row on the other side in time, by default the closest earlier one

1. Stateful real-time mode

Since: 4.3.0 · Area: Streaming · Source: SPARK-58635, SPARK-58508, SPARK-57228, SPARK-57141, SPARK-58263

Lineage: stateless queries in 4.1.0, stateful queries in 4.3.0.

Structured Streaming normally cuts a stream into small batches, micro-batches, and runs one job per batch. Real-time mode throws that out and uses long-lived tasks that process records as they arrive. 4.1 shipped it for stateless queries only, which ruled out the things people most want from streaming: a running count, or de-duplicating a Kafka topic. 4.3 fixes that. It adds streaming aggregation (SPARK-58635), dropDuplicates (SPARK-58508) and Scala or Java transformWithState (SPARK-57228), the operators that keep state between records, and it drops the @Experimental marker (SPARK-57281).

So you can keep a running count and see each update as the record lands, instead of at the end of a batch. To make that work, the stages of a query now run at the same time, joined by a pipelined shuffle (StreamingShuffleManager, SPARK-57141), where a downstream task reads while the upstream task is still writing. The scheduler admits the whole stage group only when slots are free for all of its tasks, fails fast otherwise, and fails the group as one unit (SPARK-58263). That’s why the cluster needs a free task slot for every task in every stage, and it’s the thing that trips people up first.

Before Spark 4.3

In 4.1 and 4.2, real-time mode covered stateless queries only, so a running count by key had to use micro-batches, and results arrive once per batch. This is the same query with the micro-batch trigger.

import org.apache.spark.sql.functions.col
import org.apache.spark.sql.streaming.Trigger

// the source and the aggregation, shared with the 4.3 version below
val counts = spark.readStream.format("kafka")
  .option("kafka.bootstrap.servers", "kafka:29092")
  .option("subscribe", "rtm43_demo3").option("startingOffsets", "latest").load()
  .select(col("value").cast("string").alias("word"))
  .groupBy("word").count()

// micro-batch trigger: results appear once per micro-batch
counts.writeStream.format("console").outputMode("update")
  .option("checkpointLocation", "/tmp/rtm43_ckpt3")
  .trigger(Trigger.ProcessingTime("5 seconds")).start()

Producing a, b, a, a printed one row per word in the batch, with only its final count:

b  1
a  3

The same word count with a micro-batch trigger on the left and the real-time trigger on the right

Image 3: Only the trigger changes: micro-batches before 4.3, the real-time trigger with 4.3.

With Spark 4.3: sample code

Runnable file: 07_stateful_real_time_mode.scala.

// needs a Kafka broker; `counts` is the same source and aggregation as above
// slots needed = the Kafka reader tasks + spark.sql.shuffle.partitions, all free at once;
// 1 reader task + 2 shuffle partitions run on a 4-slot session, 1 + 4 does not
spark.conf.set("spark.sql.shuffle.partitions", "2")

// the real-time trigger replaces the micro-batch trigger
counts.writeStream.format("console").outputMode("update")
  .option("checkpointLocation", "/tmp/rtm43_ckpt3")
  .trigger(Trigger.RealTime("5 seconds")).start()

With the real-time trigger the same input printed every running count in one batch (the row order can vary):

a  1
a  2
a  3
b  1

With the default 200 shuffle partitions on a two-core session the query failed:

[CONCURRENT_SCHEDULER_INSUFFICIENT_SLOT] Cannot run the pipelined stage group: it needs 201 concurrent task slots to run all its stages together, but only 2 are currently free.

The same shape in PySpark, which has had the real-time trigger since 4.2. Here a watermark and dropDuplicates count resent clicks once, then a windowed count per aisle. Runnable file: 07b_real_time_dedup_window.py.

from pyspark.sql import functions as F

# slots needed = Kafka reader tasks + the shuffle partitions of each stateful step
# (the de-duplication and the window count): 1 + 2 + 2 = 5 free slots for this query
spark.conf.set("spark.sql.shuffle.partitions", "2")

clicks = (spark.readStream.format("kafka")
    .option("kafka.bootstrap.servers", "kafka:29092")
    .option("subscribe", "clicks").load()
    .select(F.from_json(F.col("value").cast("string"),
                        "event_id STRING, aisle STRING, ts TIMESTAMP").alias("e"))
    .select("e.*"))

trending = (clicks
    .withWatermark("ts", "10 seconds")
    .dropDuplicates(["event_id"])                      # resent clicks count once
    .groupBy(F.window("ts", "10 seconds"), "aisle")
    .count())

(trending.writeStream.format("console")
    .outputMode("update")                              # required by real-time mode
    .option("checkpointLocation", "/tmp/rtm_clicks")
    .trigger(realTime="30 seconds")                    # the whole change
    .start())

Sending e1, e1, e2 for the fiction aisle and e3 for poetry printed one batch in which the resent click e1 counted once:

fiction  1
fiction  2
poetry   1

When it fits, and when it doesn’t

Reach for it when a stateful Kafka query should show a result as each record lands and you can reserve a task slot per task. If micro-batch latency is fine, if the query needs PySpark transformWithState, an ASOF JOIN or a stream-stream join, or if the cluster is small, stay with micro-batches. The classic first failure is leaving spark.sql.shuffle.partitions at 200 on a small cluster, which dies with CONCURRENT_SCHEDULER_INSUFFICIENT_SLOT.

Constraints from the documentation

These are stated in the 4.3 real-time mode guide.

  • Output and checkpoint. The output mode must be update, or the query fails with STREAMING_REAL_TIME_MODE.OUTPUT_MODE_NOT_SUPPORTED. A checkpointLocation is required.
  • Sources and sinks. Kafka is the only source; the built-in rate source isn’t supported. Sinks are Kafka, foreach, console and memory, and foreachBatch isn’t supported.
  • Not supported. Stream-stream joins, flatMapGroupsWithState, session windows, PySpark transformWithState, range partitioning and Adaptive Query Execution.
  • Sizing. Count the source’s reader tasks plus the stateful operator’s shuffle tasks. A 10-partition Kafka topic feeding an aggregation with 5 shuffle partitions needs at least 15 cores, and the guide advises one real-time query per cluster.
  • The trigger duration is a checkpoint interval, not a latency target, and it must be at least spark.sql.streaming.realTimeMode.minBatchDuration, 5,000 ms by default.
  • Delivery. Processing is exactly-once, but the built-in Kafka sink is at-least-once.
  • Latency. The trigger duration isn’t the latency. Records move through the pipelined shuffle when a buffer fills or when spark.shuffle.streaming.networkBufferMaxWaitTimeMs (default 50 ms) expires, so lowering it trades more small network writes for lower latency.

Kafka records a, b, a, a flow through a groupBy count under the real-time trigger and print running counts a 1, a 2, a 3, b 1

Image 4: Records on the left, running counts on the right, with no batch boundary in between.

2. Auto CDC with SCD Type 2

Since: 4.3.0 · Area: Declarative Pipelines · Source: SPARK-58321, SPARK-58261

Lineage: Auto CDC with SCD Type 1 in 4.2 (SPARK-56249), SCD Type 2 and its SQL syntax in 4.3.

Change data capture (CDC) is a feed of inserts, updates and deletes coming out of a source table. Auto CDC applies that feed to a target table inside a Declarative Pipeline, the 4.1 framework where you declare datasets and Spark works out the run order. What happens to old values is decided by the slowly changing dimension (SCD) type. Type 1 overwrites them, so only the latest row per key survives. Type 2, new in 4.3 (SPARK-58321), keeps every version as its own row, bounded by __START_AT and __END_AT. You get the full history of a customer or product record from one declaration instead of hand-written MERGE logic.

Spark applies each micro-batch to the target as a MERGE, so the target has to be a table whose connector implements Data Source V2 row-level operations. On a default Parquet table the syntax parses, and then the flow fails with AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE. The documentation requires a connector with row-level operations.

Before Spark 4.3

Keeping history by hand means a MERGE that closes the old row, plus a second statement that inserts the new current row, repeated for every dimension table. It needs a table with row-level operations. This works against Spark’s own in-memory test catalog, InMemoryRowLevelOperationTableCatalog, from the spark-catalyst tests jar.

To try it, add the tests jar and register the catalog:

curl -LO https://repo1.maven.org/maven2/org/apache/spark/spark-catalyst_2.13/4.3.0/spark-catalyst_2.13-4.3.0-tests.jar
spark-sql --jars spark-catalyst_2.13-4.3.0-tests.jar \
  --conf spark.sql.catalog.lh=org.apache.spark.sql.connector.catalog.InMemoryRowLevelOperationTableCatalog
-- setup: a history table with an is_current flag
CREATE TABLE lh.default.customers_history
  (id INT, name STRING, version BIGINT, is_current BOOLEAN);
-- the batch to apply; for the second run, replace the row with (1, 'alicia', 20L)
CREATE OR REPLACE TEMP VIEW changes AS SELECT * FROM VALUES
  (1, 'alice', 10L) AS t(id, name, version);
-- apply one batch of changes: close the current row, or insert a new key
MERGE INTO lh.default.customers_history h
USING changes c ON h.id = c.id AND h.is_current
WHEN MATCHED AND c.version > h.version THEN UPDATE SET h.is_current = false
WHEN NOT MATCHED THEN
  INSERT (id, name, version, is_current) VALUES (c.id, c.name, c.version, true);

-- a second statement opens the new current row for each key that was just closed
INSERT INTO lh.default.customers_history
SELECT c.id, c.name, c.version, true FROM changes c
LEFT ANTI JOIN lh.default.customers_history h ON h.id = c.id AND h.is_current;

With (1, alice, 10) in the first batch and (1, alicia, 20) in the second, the table held:

1  alice   10  false
1  alicia  20  true

A hand-written MERGE on the left and the AUTO CDC declaration on the right

Image 5: The merge logic you write and test moves into one declaration.

With Spark 4.3: sample code

Runnable file: 08_auto_cdc_scd2.sql, and the complete pipeline in 08_auto_cdc_scd2/. With the default Parquet catalog it parses and plans, then stops with AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE; the SCD Type 2 rows need a connector with row-level operations.

-- the target table's connector must support row-level operations (MERGE)
CREATE STREAMING TABLE customers_history
FLOW AUTO CDC
FROM STREAM(cdc_events)
KEYS (id)
APPLY AS DELETE WHEN op = 'DELETE'
SEQUENCE BY version
COLUMNS * EXCEPT (op)
STORED AS SCD TYPE 2;

To version a row only when selected columns change, add TRACK HISTORY ON, with a column list or * and EXCEPT. A change to any other column updates the current row in place. This is the form the Spark parser tests use (AutoCdcParserSuite), with the names of this post:

CREATE FLOW customers_flow AS AUTO CDC INTO customers_history
FROM STREAM(cdc_events)
KEYS (id)
SEQUENCE BY version
STORED AS SCD TYPE 2
TRACK HISTORY ON (name);
-- or: TRACK HISTORY ON * EXCEPT (op, version)

The Python API takes the same choices. The pattern is the one in the Declarative Pipelines programming guide, with the SCD type set to 2:

from pyspark import pipelines as dp

dp.create_streaming_table("customers_history")

dp.create_auto_cdc_flow(
    target="customers_history",
    source="cdc_events",
    keys=["id"],
    sequence_by="version",
    apply_as_deletes="op = 'DELETE'",
    except_column_list=["op"],
    stored_as_scd_type=2,
    track_history_column_list=["name"],   # optional
)

What the Spark tests expect. In AutoCdcScd2SinglePipelineSuite, a stream carrying (id 1, alice, version 10) and (id 1, alicia, version 20) ends with the first version closed at the second event’s sequence and the second one open:

id  name    version  __START_AT  __END_AT
1   alice   10       10          20
1   alicia  20       20          NULL

In the same suite, an event flagged as a delete closes the current row and leaves nothing open for the key. The source of both examples is AutoCdcScd2SinglePipelineSuite.

__START_AT and __END_AT hold values of the SEQUENCE BY column, so join them to a timestamp only when that column is one.

When it fits, and when it doesn’t

Use it when you need the history of a dimension record and your table format supports row-level operations. If you only need the latest row, that’s SCD Type 1, and a plain Parquet target won’t work with either type. The easy mistake is pointing the flow at a Parquet table and expecting it to run.

Three change events for one key flow through AUTO CDC; Type 1 keeps only the latest row and Type 2 keeps every version with the version range it was current

Image 6: Three events for one key: Type 1 keeps the last, Type 2 keeps all three with their ranges.

3. JSON_TABLE

Since: 4.3.0 · Area: SQL · Source: SPARK-58366

JSON_TABLE is the SQL-standard function that turns a JSON document into rows and typed columns (SPARK-58366). You give it a path that picks out the repeating part of the document, then a COLUMNS list that maps paths to column names and types. It’s the construct Oracle, DB2 and MySQL queries use, so a migrated query probably already contains it. Compared with chaining from_json with a schema string and then explode, it’s one declarative query.

FOR ORDINALITY adds a 1-based row number, EXISTS PATH returns a boolean saying whether a path is present, and the function takes a column through LATERAL, so it works over a whole table of documents. With the rows {"id":10,"opt":1} and {"id":20}, a hasOpt BOOLEAN EXISTS PATH '$.opt' column prints:

10  true
20  false

Only the flat form works in 4.3.0. NESTED PATH columns aren’t supported, so a document nested more than one array deep still takes two steps.

Before Spark 4.3

Without JSON_TABLE you give from_json a schema, then explode the array. It prints the two rows.

SELECT j.id, j.n FROM (
  SELECT explode(from_json(
    '{"items":[{"id":1,"n":"a"},{"id":2,"n":"b"}]}',
    'items ARRAY<STRUCT<id: INT, n: STRING>>').items) AS j);
-- 1  a
-- 2  b

The from_json and explode form on the left and JSON_TABLE on the right, with the same two rows

Image 7: The schema string and the explode become a COLUMNS list.

With Spark 4.3: sample code

Runnable file: 01_json_table.sql.

-- seq counts the rows; id and name are typed columns read by path
SELECT t.* FROM JSON_TABLE(
  '{"items":[{"id":1,"n":"a"},{"id":2,"n":"b"}]}',
  '$.items[*]'
  COLUMNS (
    seq  FOR ORDINALITY,
    id   INT    PATH '$.id',
    name STRING PATH '$.n'
  )
) AS t;
-- 1  1  a
-- 2  2  b

When it fits, and when it doesn’t

Use it to read JSON arrays into rows, or when you’re migrating a query that already uses JSON_TABLE. If your documents nest arrays more than one level deep you’ll still need two steps, because NESTED PATH doesn’t work yet, and expecting it to is the classic mistake.

Where it helps. An order webhook with three line items becomes three typed rows in one statement, instead of a from_json schema plus an explode, and the price stays a DECIMAL(10,2):

SELECT t.* FROM JSON_TABLE(
  '{"order":"A-100","lines":[{"sku":"pen","qty":2,"price":1.50},{"sku":"ink","qty":1,"price":7.25},{"sku":"pad","qty":5,"price":0.99}]}',
  '$.lines[*]'
  COLUMNS (
    line_no FOR ORDINALITY,
    sku     STRING        PATH '$.sku',
    qty     INT           PATH '$.qty',
    price   DECIMAL(10,2) PATH '$.price'
  )
) AS t;
-- 1  pen  2  1.50
-- 2  ink  1  7.25
-- 3  pad  5  0.99

A JSON document with an items array passes through JSON_TABLE with an ordinality column, an INT path and a STRING path and becomes two typed rows

Image 8: One document on the left, two typed rows on the right.

4. UNNEST in the FROM clause

Since: 4.3.0 · Area: SQL · Source: SPARK-58419

An array column holds several values in one row. UNNEST expands it into one row per value, and in 4.3 it works directly in the FROM clause (SPARK-58419). Until now you did that with explode or LATERAL VIEW, which are Spark-specific. UNNEST is the ANSI form, so it reads the same as in other engines, and porting array-flattening queries from PostgreSQL or Trino gets much less painful. explode and LATERAL VIEW still work, so nothing has to be migrated; the gain is portability. A typical use is flattening an order’s line items into one row per item before you aggregate.

List several arrays and they expand in parallel, with the shorter ones padded with NULL to the length of the longest. WITH ORDINALITY adds the position of each value, and a LATERAL reference lets the array come from a column of the same query.

Before Spark 4.3

LATERAL VIEW explode or posexplode turned an array into rows, and arrays_zip paired two arrays. Positions from posexplode start at 0.

SELECT pos, value FROM (SELECT 1)
  LATERAL VIEW posexplode(array('a','b')) t AS pos, value;
-- 0  a
-- 1  b

SELECT z.`0` AS a, z.`1` AS b
FROM (SELECT explode(arrays_zip(array(1,2), array(10,20,30))) AS z);
-- 1     10
-- 2     20
-- NULL  30

LATERAL VIEW posexplode on the left and UNNEST with ordinality on the right

Image 9: The position now starts at 1, and the table form reads like any other FROM item.

With Spark 4.3: sample code

Runnable file: 03_unnest.sql.

-- two arrays of different length expand in parallel, the shorter padded with NULL
SELECT * FROM UNNEST(array(1,2), array(10,20,30)) AS t(a, b);
-- 1     10
-- 2     20
-- NULL  30

-- with the position of each value
SELECT * FROM UNNEST(array('a','b')) WITH ORDINALITY AS t(value, pos);
-- a  1
-- b  2

When it fits, and when it doesn’t

Use UNNEST when you want array expansion that reads the same as in other SQL engines. If your explode code works and portability isn’t a goal, leave it alone. Two things catch people out: the shorter of several arrays is padded with NULL, and positions start at 1, where posexplode starts at 0.

Three UNNEST forms: with ordinality, two arrays of different length padded with NULL, and a lateral unnest over an array column

Image 10: The three forms: with ordinality, two arrays padded to the longer, and lateral over a column.

5. ASOF JOIN

Since: 4.3.0 · Area: SQL · Source: SPARK-58092, SPARK-58124, SPARK-56887

An as-of join matches each row on the left with the closest row on the right in time, usually the closest earlier one: the quote in force when a trade happened, or the price list valid on an order date (SPARK-58092). A MATCH_CONDITION states the time comparison, and an ON clause states the key that must be equal. Without it you write a window function plus a join and get the tie-breaking right yourself. With it, attaching reference data to events by time is one join, which is the shape of most time-series enrichment.

The SQL form executes as a sort-merge join (SPARK-58124), backed by a dedicated operator (SPARK-56887). It’s behind spark.sql.join.asofJoin.enabled, default false; with the flag off the statement fails at parse time with UNSUPPORTED_FEATURE.ASOF_JOIN. Only INNER and LEFT OUTER are supported. Real-time mode doesn’t support it, and in micro-batch mode only a stream-static join with the stream on the left works. In the sample, the AAPL trade at 10:00:20 takes the 10:00:10 quote, not the 10:00:00 one, because the join picks the closest earlier row, not the first match.

Before Spark 4.3

Without ASOF JOIN, you join on q.ts <= t.ts, rank the matches with row_number() and keep the first. On the trades and quotes below it returns the same three rows.

-- setup: three trades and three quotes
CREATE OR REPLACE TEMP VIEW trades AS SELECT * FROM VALUES
  (1, 'AAPL', TIMESTAMP_NTZ '2026-11-01 10:00:05'),
  (2, 'AAPL', TIMESTAMP_NTZ '2026-11-01 10:00:20'),
  (3, 'MSFT', TIMESTAMP_NTZ '2026-11-01 10:00:07') AS t(id, sym, ts);

CREATE OR REPLACE TEMP VIEW quotes AS SELECT * FROM VALUES
  ('AAPL', TIMESTAMP_NTZ '2026-11-01 10:00:00', 100.0D),
  ('AAPL', TIMESTAMP_NTZ '2026-11-01 10:00:10', 101.0D),
  ('MSFT', TIMESTAMP_NTZ '2026-11-01 10:00:06', 200.0D) AS q(sym, ts, bid);
-- query: join, rank, keep the first
SELECT id, sym, ts, quote_ts, bid FROM (
  SELECT t.id, t.sym, t.ts, q.ts AS quote_ts, q.bid,
         row_number() OVER (PARTITION BY t.id ORDER BY q.ts DESC) AS rn
  FROM trades t LEFT JOIN quotes q ON t.sym = q.sym AND q.ts <= t.ts)
WHERE rn = 1 ORDER BY id;
-- 1  AAPL  10:00:05  10:00:00  100.0
-- 2  AAPL  10:00:20  10:00:10  101.0
-- 3  MSFT  10:00:07  10:00:06  200.0

The row_number form on the left and ASOF JOIN on the right, both returning 100.0, 101.0 and 200.0

Image 11: A join, a ranking and a filter become one join.

With Spark 4.3: sample code

Runnable file: 02_asof_join.sql.

-- enable the preview syntax for this session
SET spark.sql.join.asofJoin.enabled = true;

-- each trade takes the latest quote at or before its timestamp
SELECT t.id, t.sym, t.ts, q.ts AS quote_ts, q.bid
FROM trades t ASOF JOIN quotes q
  MATCH_CONDITION (t.ts >= q.ts)
  ON t.sym = q.sym
ORDER BY t.id;
-- 1  AAPL  10:00:05  10:00:00  100.0
-- 2  AAPL  10:00:20  10:00:10  101.0
-- 3  MSFT  10:00:07  10:00:06  200.0

Variants and edge cases

Runnable file: 19_asof_join_variants.sql. It reuses the trades and quotes above and adds three trades: a GOOG trade with no quote (id 4), a MSFT trade exactly at a quote time, 10:00:06 (id 5), and an AAPL trade with a NULL timestamp (id 6).

-- setup: the three trades above plus ids 4, 5 and 6
CREATE OR REPLACE TEMP VIEW trades AS SELECT * FROM VALUES
  (1, 'AAPL', TIMESTAMP_NTZ '2026-11-01 10:00:05'),
  (2, 'AAPL', TIMESTAMP_NTZ '2026-11-01 10:00:20'),
  (3, 'MSFT', TIMESTAMP_NTZ '2026-11-01 10:00:07'),
  (4, 'GOOG', TIMESTAMP_NTZ '2026-11-01 10:00:15'),
  (5, 'MSFT', TIMESTAMP_NTZ '2026-11-01 10:00:06'),
  (6, 'AAPL', CAST(NULL AS TIMESTAMP_NTZ)) AS t(id, sym, ts);

Direction. The operator in MATCH_CONDITION picks which row counts as closest. The left operand is the left table’s expression.

Condition Takes from the right side Direction
t.ts >= q.ts the latest row not after the trade last preceding
t.ts > q.ts the latest row strictly before the trade last strictly preceding
t.ts <= q.ts the earliest row not before the trade first following
t.ts < q.ts the earliest row strictly after the trade first strictly following

Equality operators (=, <>) are not allowed. The first-following form fits cases such as matching an alert to the next maintenance window, as in the ASOF JOIN reference. On the trades and quotes, t.ts <= q.ts gives trade 1 the 10:00:10 quote (101.0) and finds nothing after trades 2 and 3:

SELECT t.id, t.sym, t.ts, q.ts AS next_quote_ts, q.bid
FROM trades t LEFT ASOF JOIN quotes q MATCH_CONDITION (t.ts <= q.ts) ON t.sym = q.sym
ORDER BY t.id;
-- 1  AAPL  10:00:05  10:00:10  101.0
-- 2  AAPL  10:00:20  NULL      NULL
-- 3  MSFT  10:00:07  NULL      NULL
-- 4  GOOG  10:00:15  NULL      NULL
-- 5  MSFT  10:00:06  10:00:06  200.0
-- 6  AAPL  NULL      NULL      NULL

The strict forms exclude a row at the same instant. Trade 5 is at 10:00:06, exactly the MSFT quote time, so >= takes that quote and > takes nothing:

-- id 5, op            quote_ts   bid
-- 5  at_or_before     10:00:06   200.0     (t.ts >= q.ts)
-- 5  strictly_before  NULL       NULL      (t.ts >  q.ts)

INNER and LEFT. INNER is the default and drops a left row with no match. LEFT keeps it and fills the right-side columns with NULL. Using the same >= join, INNER returns trades 1, 2, 3 and 5. LEFT also returns trade 4 (GOOG has no quote) and trade 6 with NULL quote columns:

SELECT t.id, t.sym, q.ts AS quote_ts, q.bid
FROM trades t LEFT ASOF JOIN quotes q MATCH_CONDITION (t.ts >= q.ts) ON t.sym = q.sym
ORDER BY t.id;
-- 1  AAPL  10:00:00  100.0
-- 2  AAPL  10:00:10  101.0
-- 3  MSFT  10:00:06  200.0
-- 4  GOOG  NULL      NULL
-- 5  MSFT  10:00:06  200.0
-- 6  AAPL  NULL      NULL

USING. USING (sym) is the same equality as ON t.sym = q.sym, and the key column is then written once, as sym with no table prefix. The result is identical to the LEFT output above.

SELECT t.id, sym, q.ts AS quote_ts, q.bid
FROM trades t LEFT ASOF JOIN quotes q MATCH_CONDITION (t.ts >= q.ts) USING (sym)
ORDER BY t.id;

NULL never matches. A NULL on either side of MATCH_CONDITION fails the match. Trade 6 above has a NULL timestamp: INNER drops it and LEFT keeps it with NULL quote columns.

Ties are not deterministic. If several right-side rows tie for closest, Spark may return any of them. Add an equi-key to ON or USING, or compare a struct so a sequence number breaks the tie. Here three versions share the timestamp 10:00:10, and the event with sequence 2 takes version b:

SET spark.sql.join.asofJoin.enabled = true;
CREATE OR REPLACE TEMP VIEW events AS SELECT * FROM VALUES
  (1, TIMESTAMP_NTZ '2026-11-01 10:00:10', 2) AS e(id, ts, seq);
CREATE OR REPLACE TEMP VIEW versions AS SELECT * FROM VALUES
  (TIMESTAMP_NTZ '2026-11-01 10:00:10', 1, 'a'),
  (TIMESTAMP_NTZ '2026-11-01 10:00:10', 2, 'b'),
  (TIMESTAMP_NTZ '2026-11-01 10:00:10', 3, 'c') AS v(ts, seq, label);

SELECT e.id, v.label
FROM events e ASOF JOIN versions v MATCH_CONDITION ((e.ts, e.seq) >= (v.ts, v.seq));
-- 1  b

The left side drives the lookup. The join is not symmetric, so swapping the tables changes the result. Asking for the trade in force at each quote, instead of the quote in force at each trade, returns different rows:

SELECT q.sym, q.ts AS quote_ts, t.id AS trade_id, t.ts AS trade_ts
FROM quotes q LEFT ASOF JOIN trades t MATCH_CONDITION (q.ts >= t.ts) ON q.sym = t.sym
ORDER BY q.sym, q.ts;
-- AAPL  10:00:00  NULL  NULL
-- AAPL  10:00:10  1     10:00:05
-- MSFT  10:00:06  5     10:00:06

Streaming. In micro-batch mode only a stream-static join works, with the streaming side on the left. A static-stream or stream-stream ASOF JOIN is not supported, and neither is any use in real-time mode.

No distance limit. The page documents no tolerance option, so a match can be arbitrarily far away. Restrict candidates with ON or USING.

When it fits, and when it doesn’t

Use it to enrich events with the latest reference row at or before each event time: the exchange rate when a payment happened, the device configuration when a sensor reading arrived, the risk score when a transaction was scored. It can also look forward to the next row with <=. Skip it if you need an outer join other than LEFT OUTER, a stream-stream or static-stream join, or the query runs in real-time mode. Forgetting the flag is the usual surprise; two others are leaving ties unbroken, which returns an arbitrary row, and swapping the tables, which changes the result. The older form is a left join on q.ts <= t.ts, a row_number() over q.ts DESC and a filter on rn = 1, and it returns one quote per trade, the latest at or before it.

The same join stops feature leakage in a model. Each prediction should use the feature version that was published when it was made, never a later one. Runnable file: 15_asof_feature_versions.sql.

-- setup: predictions made at 10:03 and 10:07; feature versions published at 10:00 and 10:05
CREATE OR REPLACE TEMP VIEW predictions AS SELECT * FROM VALUES
  (1, TIMESTAMP_NTZ '2026-11-01 10:03:00', 0.91D),
  (2, TIMESTAMP_NTZ '2026-11-01 10:07:00', 0.42D) AS p(id, made_at, score);
CREATE OR REPLACE TEMP VIEW feature_versions AS SELECT * FROM VALUES
  ('v1', TIMESTAMP_NTZ '2026-11-01 10:00:00'),
  ('v2', TIMESTAMP_NTZ '2026-11-01 10:05:00') AS f(version, published_at);

SELECT p.id, p.made_at, p.score, f.version AS features_used, f.published_at
FROM predictions p
ASOF JOIN feature_versions f
  MATCH_CONDITION (p.made_at >= f.published_at)
ORDER BY p.id;
-- 1  2026-11-01 10:03:00  0.91  v1  2026-11-01 10:00:00
-- 2  2026-11-01 10:07:00  0.42  v2  2026-11-01 10:05:00

The 10:03 prediction gets v1 and never v2, which didn’t exist yet. A plain p.made_at >= f.published_at join returned three rows here (v1, v1 and v2) and leaves you to pick the latest one.

ASOF JOIN on a timeline: each AAPL and MSFT trade is matched to the latest quote at or before its timestamp

Image 12: Three trades matched to the quotes in force at the time: 100.0, 101.0 and 200.0.

6. VARIANT editing functions

Since: 4.3.0 · Area: Types (VARIANT) · Source: SPARK-57804

Lineage: VARIANT in 4.0, generally available in 4.1, editing functions in 4.3.

VARIANT is the Spark type for semi-structured data such as JSON, stored in a binary encoding so it’s parsed once. Before 4.3 you could read a variant but not change it without rebuilding the whole value. Now five functions return a new variant with a path set, inserted, deleted or appended to (SPARK-57804 and others), so you can patch one field in a JSON payload inside SQL without a round trip through a struct schema.

Every function returns a new value, because variants are immutable. variant_set and variant_insert differ on an existing key: set replaces it and insert raises VARIANT_DUPLICATE_KEY. The try_ forms (try_variant_set and the rest) return NULL instead of raising, which is the safer choice for dirty data. Inserting into an array shifts the later elements right: variant_insert at $[1] on ["a","b","c"] with z gives ["a","z","b","c"], and variant_array_append adds to the end. variant_strip_nulls removes null fields and null array elements, so {"a":1,"b":null,"c":[1,null]} becomes {"a":1,"c":[1]}.

Before Spark 4.3

There’s no function that edits one path, so you rebuild the value: read each field out, add the new one, write it back as JSON and parse it again.

SELECT parse_json(to_json(named_struct(
  'a', variant_get(v, '$.a', 'int'),
  'b', 3,
  'tags', variant_get(v, '$.tags', 'variant')))) AS rebuilt
FROM (SELECT parse_json('{"a":1,"tags":["x"]}') AS v);
-- {"a":1,"b":3,"tags":["x"]}

Rebuilding a variant on the left and variant_set on the right, both giving the same JSON

Image 13: You no longer name every field to change one.

With Spark 4.3: sample code

Runnable file: 04_variant_editing.sql.

-- set a new key
SELECT variant_set(parse_json('{"a":1,"tags":["x"]}'), '$.b', 3);
-- {"a":1,"b":3,"tags":["x"]}

-- delete two paths in one call
SELECT variant_delete(parse_json('{"a":1,"b":2,"items":[1,2,3]}'), '$.a', '$.items[0]');
-- {"b":2,"items":[2,3]}

-- remove null fields and null array elements
SELECT variant_strip_nulls(parse_json('{"a":1,"b":null,"c":[1,null]}'));
-- {"a":1,"c":[1]}

When it fits, and when it doesn’t

It’s the right tool when a JSON payload has no fixed schema and you need to patch a field. If the shape is fixed, a typed column or struct is easier to filter and document. The common mistake is using variant_insert on a key that already exists. Use variant_set to replace.

Five variant editing functions each take a variant on the left and return the edited variant on the right: set, insert, delete, array append and strip nulls

Image 14: Five functions, each taking a variant and returning an edited copy.

7. BIN BY

Since: 4.3.0 · Area: SQL · Source: SPARK-57133, SPARK-58003

BIN BY spreads a measure over fixed-width time bins in proportion to how much of each interval falls inside each bin (SPARK-57133). A call that runs from 10:00 to 10:25 and costs 100 becomes 40, 40 and 20 across three ten-minute bins. That’s the usual step before charting usage per interval, and without it you’re joining to a calendar table and doing overlap arithmetic. One clause now turns start and end timestamps into per-interval figures.

It’s a relation operator with its own physical execution (SPARK-58003), behind spark.sql.binByRelationOperator.enabled, default false. The two range columns must be TIMESTAMP or TIMESTAMP_NTZ; an INT column fails with BIN_BY_RANGE_TYPE_MISMATCH. The grammar also takes ALIGN TO to set the bin origin. DISTRIBUTE UNIFORM names the columns to share out evenly across the bins, and BIN_START AS and BIN_END AS name the two bin-boundary columns it adds. Use it for a quantity that accrues over the interval, such as cost, bytes or minutes of usage.

Before Spark 4.3

Without BIN BY you generate the bins with sequence, work out how much of each bin the interval covers, and share the cost in proportion. It gives the same bins.

-- setup: two calls with a cost
CREATE OR REPLACE TEMP VIEW calls AS SELECT * FROM VALUES
  (1, 'ana', TIMESTAMP_NTZ '2026-11-01 10:00:00', TIMESTAMP_NTZ '2026-11-01 10:25:00', 100.0D),
  (2, 'bob', TIMESTAMP_NTZ '2026-11-01 10:05:00', TIMESTAMP_NTZ '2026-11-01 10:15:00', 30.0D)
  AS t(id, caller, started, ended, cost);

WITH x AS (SELECT id, cost, unix_timestamp(started) AS s,
                   unix_timestamp(ended) AS e FROM calls),
b AS (SELECT id, cost, s, e,
             explode(sequence(floor(s/600), floor((e-1)/600))) AS bin FROM x)
SELECT id,
       TIMESTAMP_NTZ '1970-01-01 00:00:00' + bin * INTERVAL '10' MINUTE AS bin_start,
       TIMESTAMP_NTZ '1970-01-01 00:00:00' + (bin + 1) * INTERVAL '10' MINUTE AS bin_end,
       round(cost * (least(e, (bin+1)*600) - greatest(s, bin*600)) / (e - s), 1) AS cost
FROM b ORDER BY id, bin_start;
-- call 1: 40.0, 40.0, 20.0 and call 2: 15.0, 15.0

The hand-built bins on the left and BIN BY on the right, both giving 40, 40 and 20

Image 15: Generating bins and prorating the overlap by hand becomes one clause.

With Spark 4.3: sample code

Runnable file: 09_bin_by.sql.

-- enable the relation operator for this session
SET spark.sql.binByRelationOperator.enabled = true;

-- cost is spread over the 10-minute bins each call overlaps
SELECT id, bin_start, bin_end, cost
FROM calls
BIN BY (RANGE started TO ended BIN WIDTH INTERVAL 10 MINUTES DISTRIBUTE UNIFORM (cost)
        BIN_START AS bin_start BIN_END AS bin_end)
ORDER BY id, bin_start;
-- 1  10:00  10:10  40.0
-- 1  10:10  10:20  40.0
-- 1  10:20  10:30  20.0
-- 2  10:00  10:10  15.0   (10:05 to 10:15 costs 30: five minutes in each bin)
-- 2  10:10  10:20  15.0

When it fits, and when it doesn’t

Use it when a measure accrues over an interval and you want it per time bin. If you’re counting events rather than spreading an amount, or the range columns aren’t timestamps, it’s the wrong tool. Integer range columns fail with BIN_BY_RANGE_TYPE_MISMATCH.

Call 1, from 10:00 to 10:25 with cost 100, splits into 40, 40 and 20 across three ten-minute bins; call 2, from 10:05 to 10:15 with cost 30, splits into 15 and 15

Image 16: Each bin gets the share of the interval that falls inside it.

8. TIME(p) and nanosecond timestamps

Since: 4.3.0 · Area: Types · Source: SPARK-57551, SPARK-56876

TIME(p) is a time-of-day type with a precision p up to nine digits, which is nanoseconds (SPARK-57551). TIMESTAMP_NTZ(p) and TIMESTAMP_LTZ(p) do the same for timestamps, with and without a time zone, for p from 7 to 9 (SPARK-56876). Spark’s default timestamp keeps microseconds, six digits, so a nanosecond value gets silently shortened unless you ask for the wider type. If you work with trading systems, sensors or databases that produce nanoseconds, this stops you rounding the precision away on ingest.

Both families are behind flags: spark.sql.timeType.enabled for TIME, and spark.sql.timestampNanosTypes.enabled, which the release notes call a preview, for the timestamps. Without the first, CAST(... AS TIME(9)) fails with UNSUPPORTED_TIME_TYPE. There’s a rough edge too: the Python client couldn’t materialise a TIMESTAMP_NTZ(9) result. Selecting the column raised CANNOT_PARSE_DATATYPE, which is why the sample casts to a string. The release also threads TIME through the built-in sources: schema inference in CSV, JSON and XML, the JDBC source, and predicate pushdown to ORC (SPARK-57572, SPARK-57555, SPARK-57571).

Before Spark 4.3

The default timestamp keeps microseconds, so the last three digits of a nanosecond value are cut. It needs no flags.

SELECT CAST('2026-11-01 10:00:00.123456789' AS TIMESTAMP_NTZ);
-- 2026-11-01 10:00:00.123456

The default cast cutting the value at six digits on the left and the nine-digit type on the right

Image 17: Nine digits survive once the type and its flag are on.

With Spark 4.3: sample code

Runnable file: 05_time_and_nanosecond_types.sql.

SET spark.sql.timeType.enabled = true;
SET spark.sql.timestampNanosTypes.enabled = true;
-- the cast to STRING keeps all nine digits
SELECT CAST(CAST('2026-11-01 10:00:00.123456789' AS TIMESTAMP_NTZ(9)) AS STRING);
-- 2026-11-01 10:00:00.123456789

When it fits, and when it doesn’t

Use these types when your source produces nanosecond precision and you have to keep it. If microseconds are enough, the default timestamp is simpler and supported everywhere. The mistakes to avoid: casting to the default TIMESTAMP_NTZ and expecting nanoseconds, which get cut to six digits, and selecting a TIMESTAMP_NTZ(9) column from Python.

The input 2026-11-01 10:00:00.123456789 is cut to microseconds by the default TIMESTAMP_NTZ and kept in full by TIMESTAMP_NTZ(9); TIME(9) holds 10:15:30.123456789; each needs its own flag

Image 18: The default type cuts at six digits; the nine-digit types need their flags.

9. DataFrame.zip

Since: 4.3.0 · Area: DataFrame API · Source: SPARK-55886, SPARK-57247

DataFrame.zip appends the columns of a second DataFrame to the first, row by row, with no join key (SPARK-55886). Spark Connect has it too (SPARK-57247). Normally you combine two DataFrames with a join on a key. zip is for the case where there’s no key and the two line up by position, such as attaching a column you computed in a separate step.

The pairing is positional, so it relies on both sides keeping the same rows in the same order. The Scaladoc says the other DataFrame must derive from the same source as the receiver, which holds in the sample, where the second DataFrame is computed from the first. Two sources with different partitioning are where positional pairing isn’t safe. If you need a guarantee, join on a key.

Before Spark 4.3

Without zip, you number the rows of both frames with a window and join on that number. It returns the same three rows. A window with no partition key moves every row to one partition.

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._

val a = spark.range(3).toDF("id")
val b = a.selectExpr("id * 10 AS tenfold")

val aw = a.withColumn("rn", row_number().over(Window.orderBy("id")))
val bw = b.withColumn("rn", row_number().over(Window.orderBy("tenfold")))
aw.join(bw, "rn").drop("rn").orderBy("id").show()
// 0 0, then 1 10, then 2 20

The window numbering and join on the left and a.zip(b) on the right

Image 19: One call replaces the numbering and the join.

With Spark 4.3: sample code

Runnable file: 11_dataframe_zip.scala.

val a = spark.range(3).toDF("id")
// b is computed from a, so the two line up row for row
val b = a.selectExpr("id * 10 AS tenfold")
a.zip(b).show()
// +---+-------+
// | id|tenfold|
// +---+-------+
// |  0|      0|
// |  1|     10|
// |  2|     20|
// +---+-------+

When it fits, and when it doesn’t

Use it when the second DataFrame is derived from the first and you want its columns alongside. If the two come from independent sources or are partitioned differently, join on a key instead. The mistake to avoid is assuming zip matches rows by a key. It matches by position.

a is a DataFrame with id 0, 1, 2 and b is computed from it as id times 10; a.zip(b) appends the columns of b to a and returns the rows (0, 0), (1, 10) and (2, 20)

Image 20: The columns of b are appended to a, row by row, with no key.

10. Single-task execution for small queries

Since: 4.3.0 · Area: Performance · Source: SPARK-57851

Spark plans every query as if the data were huge: aggregates and sorts are separated by shuffles, which move rows between tasks. For a query over a handful of rows, the shuffles cost more than the work. Single-task execution (SPARK-57851), part of the effort the 4.3 announcement calls Project Feather, lets an eligible small query run in one task and skip the shuffles, so a lookup or a test over a tiny table no longer pays for the full distributed plan. It’s opt-in, behind spark.sql.optimizer.singleTaskExecution.enabled, and it changes the physical plan, not the result.

With the flag off, the sample’s plan is LocalTableScan, HashAggregate, Exchange, HashAggregate, Exchange, Sort. With the flag on it’s LocalTableScan, HashAggregate, Sort: both Exchange steps are gone, the query runs as one stage with one task, and the result is the same, [eu,40.0] and [us,25.0]. Only small inputs qualify, such as a local relation or one small file; larger inputs keep the normal plan. Opt in per session, not cluster-wide, because a query that grows past the limits needs the normal plan.

Before Spark 4.3

With the flag off, which is the default, Spark plans two shuffles for a four-row aggregate. This is the plan the code below prints.

// helper: the operator names in the executed plan, read from EXPLAIN FORMATTED
def operators(sql: String): String = {
  val plan = spark.sql("EXPLAIN FORMATTED " + sql).collect().map(_.getString(0)).mkString("\n")
  "\\(\\d+\\) (\\w+)".r.findAllMatchIn(plan).map(_.group(1)).mkString(" > ")
}

// a four-row local relation and a small aggregate over it
spark.sql("SELECT * FROM VALUES (1,'eu',10.0D),(2,'us',20.0D),(3,'eu',30.0D),(4,'us',5.0D) AS t(id, region, amount)")
  .createOrReplaceTempView("orders")
val query = "SELECT region, sum(amount) AS total FROM orders GROUP BY region ORDER BY region"

spark.conf.set("spark.sql.adaptive.enabled", "false")   // show the plain physical plan
println("OFF " + operators(query))
// OFF LocalTableScan > HashAggregate > Exchange > HashAggregate > Exchange > Sort

The default plan with two Exchange steps on the left and the single-task plan without them on the right

Image 21: With the flag on, both Exchange steps are gone.

With Spark 4.3: sample code

Runnable file: 13_single_task_execution.scala.

// same `query` and `operators` helper as above
spark.conf.set("spark.sql.optimizer.singleTaskExecution.enabled", "true")
println("ON  " + operators(query))
// ON  LocalTableScan > HashAggregate > Sort

When it fits, and when it doesn’t

It suits a session that runs lots of tiny queries, like tests or lookups over small tables. Leave it off where the data can grow, since the normal distributed plan is what you want then. And don’t expect a speed-up on a large table. The flag does nothing for data beyond the eligibility limits.

With the flag off the plan is LocalTableScan, HashAggregate, Exchange, HashAggregate, Exchange, Sort; with the flag on it is LocalTableScan, HashAggregate, Sort, so both Exchange steps are gone and the query runs as one task with the same result

Image 22: The two shuffles disappear for an eligible small query.

Smaller additions worth knowing

Feature What it does Needs
Archive reader (SPARK-57135 and others) Reads the entries of a tar or zip as files, with spark.sql.files.archive.reader.enabled=true. A tar holding two CSVs returned three rows. With the flag off, count(*) on the same tar returned 4 and raised no error A flag
New functions (SPARK-56820, SPARK-57253, SPARK-58399, SPARK-58295) counter_diff, collect_union, jaro_winkler_similarity, to_base32 and from_base32 Nothing
Arrow-native Dataset caching (SPARK-57268) Opt-in caching with compression and column statistics, set with the static spark.sql.cache.serializer A flag
Local Connect server reuse (SPARK-57787) Reuse a persistent local Connect server for faster PySpark startup, with SPARK_LOCAL_CONNECT_REUSE=1; the announcement calls it experimental Nothing
Connect REST endpoints (SPARK-57941) GET /api/v1/applications/<appId>/connect/sessions returned a session with sessionId, userId, startTimestamp, finishTimestamp, totalExecution and totalTime. /connect/operations lists operations Nothing
Connect operation IDs (SPARK-58547) Trace a request end to end Nothing
@ time travel on table names (SPARK-57421, SPARK-58012) Read a table at a version or timestamp A connector
Connect JDBC driver complex types (SPARK-57380) Return ARRAY, MAP and STRUCT through the Connect JDBC driver Nothing
SQLContext wrapper on Connect (SPARK-57021) Old SQLContext code runs against a Connect session Nothing
Security and UI hardening (SPARK-58054, SPARK-59319, SPARK-59508) A Content-Security-Policy header by default, an opt-in restricted SQL execution mode, and a restricted unpickle serializer for the Python client Nothing
Experimental transpiling of simple Python UDFs (SPARK-55206) Experimental. Turns simple, non-Arrow UDFs such as len() into Catalyst expressions in classic PySpark, behind spark.sql.experimental.optimizer.transpilePyUDFs with ANSI mode on; otherwise the Python worker still runs A flag

Smaller additions in code

Archive reader. archivePathFilter selects which entries of an archive to read. With a tar holding a.csv, b.csv and notes.txt (which holds the row 9,notes), the filter returned only the rows of the two CSV files; without it the 9,notes row comes back too. Runnable file: 10_archive_reader.sql, with 10_make_archives.sh.

-- build the archive first, in a shell:
--   printf 'id,name\n1,a\n2,b\n' > a.csv; printf 'id,name\n3,c\n' > b.csv; printf 'id,name\n9,notes\n' > notes.txt
--   mkdir -p /data && tar -cf /data/data.tar a.csv b.csv notes.txt
SET spark.sql.files.archive.reader.enabled = true;

CREATE OR REPLACE TEMP VIEW only_csv
USING csv
OPTIONS (path '/data/data.tar', header 'true', archivePathFilter '*.csv');

SELECT * FROM only_csv ORDER BY id;
-- 1  a
-- 2  b
-- 3  c

Arrow-native cache. The serializer is a static setting, so give it at start-up, not with spark.conf.set. Runnable file: 17_arrow_cache_and_udf_transpile.py.

spark-submit \
  --conf spark.sql.cache.serializer=org.apache.spark.sql.execution.columnar.ArrowCachedBatchSerializer \
  app.py

Connect operation IDs. The client generates an operation ID for each request (SPARK-58547), and the execution info of a DataFrame carries it. The same ID is the key in the server’s REST endpoints (SPARK-57941). Runnable file: 16_connect_operation_ids.py.

from pyspark.sql import SparkSession

with SparkSession.builder.remote("sc://localhost:15002").getOrCreate() as spark:
    df = spark.sql("SELECT count(*) AS n FROM range(1000000)")
    df.collect()
    print(df.executionInfo.operation_id)
    # 96661cdb-a152-4766-be72-6587e776f4f1
API=http://localhost:4040/api/v1/applications/<appId>
curl -s $API/connect/sessions
curl -s $API/connect/operations

/connect/operations returned an entry whose operationId was the printed ID, with its state (CLOSED), startTimestamp, duration, statement and sqlExecIds. /connect/sessions returned the session with sessionId, userId, totalExecution and totalTime.

Python UDF transpiling. Experimental. Only a simple, non-Arrow UDF in classic PySpark, defined in a function body that PySpark can read back from source, with ANSI mode on:

from pyspark.sql.functions import udf

spark.conf.set("spark.sql.ansi.enabled", "true")
spark.conf.set("spark.sql.experimental.optimizer.transpilePyUDFs", "true")

@udf("int", useArrow=False)
def name_length(name: str) -> int:
    return len(name)

df = spark.createDataFrame([("ana",), ("robert",)], "name string")
df.select(name_length("name").alias("n")).explain()
# Project [CASE WHEN isnull(name) THEN raise_error(...) ELSE length(name) END AS n]
# there is no Python evaluation node; the rows are 3 and 6

The NULL branch matters: where Python would raise a TypeError on len(None), the transpiled plan calls raise_error instead of returning NULL.

Version lineage

Several 4.3 features finish something that started earlier. Read the 4.3 column as what changed since 4.2.

Feature 4.0 4.1 4.2 4.3
VARIANT Introduced (SPARK-45827) Generally available, colon paths (SPARK-54454, SPARK-52494) none in the headlines Editing functions (SPARK-57804)
Real-time mode none Stateless, Scala, Kafka (SPARK-53736) PySpark trigger (SPARK-54660) Stateful: aggregation, dropDuplicates, transformWithState (SPARK-58635)
Change data and history none Declarative Pipelines (SPARK-51727) CHANGES clause, Auto CDC SCD Type 1 (SPARK-55668, SPARK-56249) Auto CDC SCD Type 2 (SPARK-58321)
Time-series SQL none none time_bucket (SPARK-56594) ASOF JOIN, BIN BY (SPARK-58092, SPARK-57133)
Small data none none none Single-task execution, Arrow caching (SPARK-57851, SPARK-57268)
Spark Connect Lightweight Python client JDBC driver (SPARK-53484) GetStatus API (SPARK-55606) REST endpoints (SPARK-57941)
Python UDFs Python UDTFs Arrow UDF decorators (SPARK-52214) Arrow-optimized UDFs on by default (SPARK-54555) Experimental transpiling (SPARK-55206)

Settings and costs

Setting Default What to set it to
spark.sql.streaming.realTimeMode.minBatchDuration 5000 ms (from the docs) The shortest allowed real-time trigger duration
spark.sql.shuffle.partitions 200 For real-time mode, the Kafka reader tasks plus this number must fit in the free task slots. At 200 on a two-slot session the query failed, needing 201 slots with 2 free
Feature Cost to plan for
Stateful real-time mode One free task slot per task across all stages, held for the life of the query
Auto CDC Each micro-batch is a MERGE, so the target must support row-level operations
BIN BY One output row per bin an interval overlaps. In the sample, a 25-minute call over 10-minute bins produced three rows
Archive reader A silent wrong result if the flag is forgotten: a two-file tar returned 4 rows and no error
Nanosecond types Behind flags, and not yet readable by the Python client

When these features bite

These are the errors you’re most likely to hit, with the text Spark prints so you can search for it. Each one has its own anchor, so you can link straight to it.

[AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE]. The engine defines STORED AS SCD TYPE 2, but a Parquet target has no row-level operations. The same shape applies to @ time travel. Fix: Check that your connector implements the feature.

[UNSUPPORTED_FEATURE.ASOF_JOIN]. ASOF JOIN is behind a flag. Fix: spark.sql.join.asofJoin.enabled=true.

[UNSUPPORTED_TIME_TYPE]. TIME(p) is behind a flag. Fix: spark.sql.timeType.enabled=true.

[FEATURE_NOT_ENABLED] for nanosecond timestamps. A preview feature, off by default. Fix: spark.sql.timestampNanosTypes.enabled=true.

CANNOT_PARSE_DATATYPE ... timestamp_ntz(9). The Python client can’t materialise a nanosecond timestamp column. Fix: CAST(... AS STRING) before collecting.

[BIN_BY_RANGE_TYPE_MISMATCH]. The BIN BY range columns must be TIMESTAMP or TIMESTAMP_NTZ. Fix: Cast the range columns.

[VARIANT_DUPLICATE_KEY]. variant_insert on a key that already exists. Fix: Use variant_set, or the try_ form that returns NULL.

count(*) is 4 on a tar of two CSVs, and no error. The archive reader is off by default, so the tar is read as plain CSV text. Fix: spark.sql.files.archive.reader.enabled=true.

STREAMING_REAL_TIME_MODE.OUTPUT_MODE_NOT_SUPPORTED, STREAMING_REAL_TIME_MODE.INPUT_STREAM_NOT_SUPPORTED and INVALID_STREAMING_REAL_TIME_MODE_TRIGGER_INTERVAL. Real-time mode needs the update output mode, a Kafka source and a trigger of at least 5,000 ms. The real-time mode guide documents these three requirements. Fix: Use update, read from Kafka, and set the trigger to 5 seconds or more.

[CONCURRENT_SCHEDULER_INSUFFICIENT_SLOT] ... needs 201 concurrent task slots ... only 2 are currently free. Every stage of a real-time query runs at once, so the cluster needs a free slot for each task. The default 200 shuffle partitions on a small session can’t fit. Fix: Set spark.sql.shuffle.partitions so that the Kafka reader tasks plus the shuffle partitions of every stateful step fit in the free slots; the message gives the count it needs.

Upgrade checklist: what can break

Most upgrades are a version bump, but check Python, connector jars and the behaviour changes below first, and run the list on a staging copy of your heaviest job.

1. Runtime and dependencies

Requirement 4.3.0 value Source
Python 3.11 or newer; 3.10 is dropped requires_python of pyspark==4.3.0 on PyPI
pandas, PyArrow, NumPy (pyspark[sql]) 2.2.0, 18.0.0 and 1.23.2 or newer requires_dist on PyPI
pyspark[connect] extras grpcio and grpcio-status 1.76.0 or newer, zstandard 0.25.0 or newer requires_dist on PyPI
Scala 2.13 only, as for all of 4.x Maven Central
Java 17, 21 or 25 Spark 4.3.0 overview
Kafka connector spark-sql-kafka-0-10_2.13:4.3.0 is published Maven Central

2. Check every connector jar before you upgrade

Connector runtimes are built per Spark minor version, so a jar built for 4.1 doesn’t mean there is one for 4.3. List the artifacts from your spark.jars.packages and ask Maven Central whether each has a 4.3.0 build, so you learn about a missing one before the cluster does.

import urllib.request

# group, artifact: edit to match your spark.jars.packages
ARTIFACTS = [
    ("org.apache.spark", "spark-sql-kafka-0-10_2.13"),
    ("org.apache.spark", "spark-avro_2.13"),
]
SPARK = "4.3.0"

for group, artifact in ARTIFACTS:
    base = f"https://repo1.maven.org/maven2/{group.replace('.', '/')}/{artifact}"
    try:
        urllib.request.urlopen(f"{base}/{SPARK}/{artifact}-{SPARK}.pom", timeout=10)
        print(f"OK       {artifact}:{SPARK}")
    except Exception:
        print(f"MISSING  {artifact}  -> no {SPARK} build published")

The output:

OK       spark-sql-kafka-0-10_2.13:4.3.0
OK       spark-avro_2.13:4.3.0

For third-party connectors, the artifact name carries the Spark line, so use the name the project documents for 4.3. A MISSING line means keep those jobs on their current Spark version.

3. Behaviour changes to test

The first rows come from the 4.3 release notes; the rest come from the official SQL and PySpark migration guides, which list more.

Change What to do Source
Python 3.10 support is dropped, and the minimum NumPy is 1.23.2 Check the Python version on every image SPARK-56889, SPARK-56928
mapInPandas functions must return a strict iterator A function that returned a list or another iterable can fail at run time SPARK-58601
spark.rdd.compress, the web UI Content-Security-Policy header and, on Kubernetes, useDriverPodIP and no privilege escalation are on by default Recheck RDD sizes, UI embedding and pod security settings SPARK-57723, SPARK-58054
ceil and floor raise overflow errors in ANSI mode Test numeric code near the limits SPARK-58052
GROUP BY GROUPING SETS (()) over empty input returns one row spark.sql.analyzer.lowerEmptyGroupingSetToGlobalAggregate.enabled=false restores no rows. The ticket’s fix version is 4.3.0, but the SQL migration guide lists the change under 4.1 to 4.2, so test on your version SPARK-57775
Whole-stage code generation for UNION is on by default Expect a plan difference if you compare plans SPARK-56805
replaceHashWithSortAgg and combineAdjacentAggregation default to true Set both spark.sql.execution.* flags to false to restore SQL migration guide
The adaptive rule DynamicJoinSelection is now DemoteBroadcastHashJoin; shuffled-hash preference moved to spark.sql.adaptive.convertSortMergeJoinToShuffledHashJoin.enabled. MergeSubplans moved packages Excluding the old rule names silently does nothing; use the new names SQL migration guide
percentile, percentile_cont and median can differ in the last ULP Loosen exact comparisons SQL migration guide
Non-deterministic filters such as rand() are no longer pushed to Data Source V2 sources None; Spark evaluates them after the scan SQL migration guide
hash() and xxhash64 include the days field of CalendarInterval Hash values over intervals change, so rebuild anything keyed on them SQL migration guide
HAVING is evaluated before window functions when the select list has a generator such as explode Recheck queries that mix them SQL migration guide
Dataset.observe counts only the last successful attempt of each task spark.sql.legacy.observeMetricsAggregateAllAttempts=true restores SQL migration guide
foreachBatch on Spark Connect receives the correct session Code that relied on the old session can break SPARK-44462
Spark Connect session errors now carry SQLSTATE 08003, not HY000 Match on 08003 or class 08 SQL migration guide
Declarative Pipelines honours spark.sql.caseSensitive, and all flows into one table must agree on it Set the same value on every flow, or spark.sql.caseSensitive=true SQL migration guide
Thrift Server sessions cannot set JVM system properties, including through set:hiveconf Remove such settings from client scripts SPARK-57441
Write privileges are checked when a statement reads and writes the same table Expect new permission errors on read-modify-write statements SPARK-58370
Non-deterministic predicates are no longer pushed into CTE definitions or DSv2 scans Results are more correct, but some queries scan more data SPARK-59434, SPARK-58112
spark.ui.xXssProtection defaults to 0 Recheck headers if a proxy or scanner expects the old value SPARK-57904

4. Roll out in this order

  1. Python first. Move to Python 3.11 or newer on your current Spark version. The change is independent and easy to reverse.
  2. Connectors. Run the script above. Leave any job whose connector is missing on its current Spark version.
  3. Stateless batch jobs. Move them to 4.3 and compare outputs and runtimes. If runtimes shift, revisit executor cores and memory before blaming the release.
  4. Streaming jobs last. Restart a copy of each job from a copy of its existing checkpoint in staging first, and keep the old checkpoint and the old Spark version until that run passes.

5. Common mistakes

  • Leaving spark.sql.shuffle.partitions at 200 for a stateful real-time query. It needs a free core for every task at once, and fails with CONCURRENT_SCHEDULER_INSUFFICIENT_SLOT.
  • Treating __START_AT and __END_AT as timestamps. They hold values of the SEQUENCE BY column.
  • Expecting foreachBatch or a stream-stream join in real-time mode. Neither is supported; use micro-batches for those.
  • Forgetting a flag. ASOF JOIN, BIN BY, TIME, nanosecond timestamps and the archive reader are off by default, and the archive reader fails silently.
  • Reusing a 4.1 connector jar on 4.3. Use the build for the 4.3 line.
  • Treating 4.3 as a long-term platform. The versioning policy gives a feature release a 6-month maintenance window, and the long-term-support release a longer one.

Known limitations in this release

  • Auto CDC SCD Type 2. The target needs row-level operations. On a plain Parquet table the flow fails with AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE.
  • Nanosecond timestamps. The Python client can’t materialise a TIMESTAMP_NTZ(9) result (CANNOT_PARSE_DATATYPE), so cast results to a string.
  • Syntax gaps. JSON_TABLE has no NESTED PATH. ASOF JOIN supports only INNER and LEFT OUTER, only as a stream-static join in micro-batch mode (stream on the left), and not in real-time mode.
  • Real-time mode. Kafka is the only source, the output mode must be update, and foreachBatch, stream-stream joins and PySpark transformWithState aren’t supported.
  • Single-task execution. Only small inputs qualify; larger ones keep the normal plan.
  • Spark Connect. /connect/sessions and /connect/operations are new REST endpoints, and the operation IDs, JDBC complex types, SQLContext wrapper and @ time travel are new in this release. @ time travel needs a connector that supports it.

Cheat sheet

Spark 4.3 cheat sheet: the syntax of each feature and what it needs first, such as a flag, a Kafka source or a connector with row-level operations

Image 23: The syntax of each feature and what has to be on first.

Download the cheat sheet as a PNG.

Frequently Asked Questions

What is new in Apache Spark 4.3?

Spark 4.3.0, released on 30 October 2026, makes real-time mode stateful (aggregation, dropDuplicates and Scala or Java transformWithState), adds SCD Type 2 to Auto CDC, and adds JSON_TABLE, UNNEST in FROM, ASOF JOIN, BIN BY, VARIANT editing functions, nanosecond timestamps, DataFrame.zip and single-task execution for small queries.

Which features work without a flag?

JSON_TABLE, UNNEST, the VARIANT editing functions, DataFrame.zip and the new functions such as counter_diff run as they are. ASOF JOIN, BIN BY, TIME, nanosecond timestamps, the archive reader and single-task execution are off until you set their flags.

Does real-time mode now support stateful queries?

Yes: streaming aggregation, dropDuplicates and Scala or Java transformWithState. It needs the update output mode, a Kafka source and a checkpoint location, and it’s no longer marked experimental.

Why does my real-time query fail with CONCURRENT_SCHEDULER_INSUFFICIENT_SLOT?

All stages run at once, so the cluster needs a free task slot for every task. Lower spark.sql.shuffle.partitions to what the cluster can run together.

Why is my real-time latency around 50 ms?

The streaming shuffle flushes a buffer when it fills or when spark.shuffle.streaming.networkBufferMaxWaitTimeMs expires, 50 ms by default. A lower value reduces latency and increases the number of small network writes.

Why does my ASOF JOIN fail with UNSUPPORTED_FEATURE.ASOF_JOIN?

The syntax is off by default. Set spark.sql.join.asofJoin.enabled=true. Only INNER and LEFT OUTER are supported, and it does not run in real-time mode.

Can I use Auto CDC with SCD Type 2 on a Parquet table?

No. Each micro-batch is applied as a MERGE, so the target connector must support row-level operations. Otherwise the flow fails with AUTOCDC_TARGET_DOES_NOT_SUPPORT_MERGE.

Does DataFrame.zip need a join key?

No. It pairs rows by position, so both sides must come from the same source with the same row order. Join on a key when you need a guarantee.

Why does pip install pyspark==4.3.0 say no matching distribution?

The wheel requires Python 3.11 or newer, and pip hides it on older interpreters. Check python3 --version.

Are nanosecond timestamps ready for production?

They are a preview behind spark.sql.timestampNanosTypes.enabled, and the Python client can’t read the column yet, so cast it to a string before collecting.

How often will Spark ship feature releases now?

4.3.0 is the first release under the quarterly cadence in the versioning policy. Feature releases get a 6-month maintenance window, and the long-term-support release gets a longer one.

Summary

Spark 4.3 is about two things. Streaming queries can finally keep state under real-time mode, and SQL picks up standard syntax for jobs people used to do with workarounds: JSON_TABLE and UNNEST for nested data, ASOF JOIN and BIN BY for time series, and SCD Type 2 for history.

Pay attention to the flags. TIME, nanosecond timestamps, ASOF JOIN, BIN BY and the archive reader are all off by default, and a feature that parses isn’t a feature that’s on. Auto CDC needs a connector with row-level operations, and real-time mode needs a free task slot for every task. Check those before you plan around either.

Further reading

Trademarks

Apache Spark, Apache Kafka, Apache Parquet and Apache are either registered trademarks or trademarks of The Apache Software Foundation in the United States and other countries. The Apache Software Foundation doesn’t endorse this post.

Found this useful?

These posts and tools are free. If one saved you an afternoon, you can buy me a coffee.

Buy me a coffee

Comments

Questions, corrections and reviews are welcome. Sign in with GitHub to post; comments are stored in this site's public GitHub Discussions.