All posts

What's new in Apache Spark 4.1

Spark 4.1 new features: Declarative Pipelines, stateless real-time mode, SQL scripting, recursive CTEs, VARIANT colon paths, parameter markers, sketch functions and Arrow Python UDFs. Each feature has its area, a source ticket, the code before and with 4.1, and a plain note on what needs a flag, a package or a connector.

32 min read Spark

Spark 4.1.0 came out on 16 December 2025, 207 days after 4.0.0. The release notes count over 1,800 Jira tickets from more than 230 people, and it’s the second release of the 4.x line.

The theme is moving work that used to live outside Spark into Spark. Pipelines are no longer a script that runs steps in the right order: you declare the datasets and Spark works out the order. SQL picks up scripts, loops and recursion, so logic that lived in a Python driver can move into a query. Structured Streaming gets a real-time trigger for low-latency, stateless queries. And Python UDFs get an Arrow-native flavour that skips the pandas conversion.

Below are eight features. Each one shows the code you’d have written before 4.1, the code you write now, and what it needs before it works: nothing, a flag, a package or a connector. If you’re new to Spark 4, start with the glossary. The install steps come right after the overview images. Spark 4.0 is the release before this one and Spark 4.2 the one after. The features-by-release post puts them side by side.

Spark 4.1.0 in numbers: over 1,800 Jira tickets closed, more than 230 contributors, 207 days since Spark 4.0.0, on a timeline from 4.0 to 4.1

Image 1: Spark 4.1.0 in numbers, and the gap since 4.0.

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

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

Key takeaways

  • Declarative Pipelines let you state the datasets and leave the run order to Spark. The CLI needs a handful of extra Python packages.
  • SQL scripting is on by default, and recursive CTEs and parameter markers make SQL able to do jobs that used to need a driver program.
  • VARIANT is generally available, with a colon-path syntax that reads like the JSON you’re querying.
  • Real-time mode runs stateless Scala queries with only a trigger change. Python can’t use it yet.
  • Arrow-native UDFs skip the pandas conversion, and Python 3.9 is no longer supported.

Features at a glance

Feature Area On by default? How to turn it on
Declarative Pipelines Pipelines Yes, a separate CLI pip install "pyspark[pipelines]", then spark-pipelines
Real-time mode Streaming Yes, with the trigger Trigger.RealTime("5 seconds") in Scala, Kafka source, stateless query
SQL scripting SQL scripting Yes Nothing
Recursive CTEs SQL Yes Nothing; WITH RECURSIVE
VARIANT colon paths Types Yes Nothing
Parameter markers SQL Yes Nothing
Sketch functions SQL Yes Nothing
Arrow-native Python UDFs Python Yes PyArrow installed; @arrow_udf

Before you start

What you need

Need Detail
Java 17 or 21, per the Spark 4.1.4 overview. The apache/spark:4.1.4-python3 image ships Java 21
Python, for PySpark 3.10 or newer
Spark pip install pyspark==4.1.4, the apache/spark:4.1.4-python3 image, or the 4.1.4 release tarball
PyArrow and pandas For feature 8: pip install "pyspark[sql]" brings them
Pipeline packages For feature 1: pip install "pyspark[pipelines]", or pyyaml, grpcio, grpcio-status, protobuf, googleapis-common-protos, zstandard, pandas (2.2.0 or newer), pyarrow and numpy by hand
Kafka A broker, for feature 2 only

Install Spark 4.1

You’ve got two ways in. 4.1.4 is the latest 4.1 release (4.1.0 shipped on 16 December 2025 and 4.1.4 on 27 October 2026).

Option 1: pip. The wheel bundles Spark, so you need Java (17 or 21) and Python 3.10 or newer. The sql and pipelines extras add what features 1 and 8 need.

python3 -m venv .venv && source .venv/bin/activate
pip install "pyspark[sql,pipelines]==4.1.4"
python -c "import pyspark; print(pyspark.__version__)"

The last command prints 4.1.4. Point PYSPARK_PYTHON at the same interpreter if your shell’s python3 is older, because the workers use it.

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.1.4/spark-4.1.4-bin-hadoop3.tgz
curl -s https://archive.apache.org/dist/spark/spark-4.1.4/spark-4.1.4-bin-hadoop3.tgz.sha512
shasum -a 512 spark-4.1.4-bin-hadoop3.tgz   # compare with the line above
sudo tar -xzf spark-4.1.4-bin-hadoop3.tgz -C /opt
sudo ln -sfn /opt/spark-4.1.4-bin-hadoop3 /opt/spark
export SPARK_HOME=/opt/spark PATH=/opt/spark/bin:$PATH
spark-submit --version

The file is 572,969,525 bytes (about 546 MiB). Add the two export lines to ~/.zshrc or ~/.bashrc to keep them. If the version printed isn’t 4.1.4, an older SPARK_HOME in your shell is winning; start with env -u SPARK_HOME.

Glossary

Term Meaning
Declarative pipeline A set of datasets, each defined by a query, whose run order Spark derives from their references
Materialized view A dataset whose result Spark computes and stores
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
Recursive CTE A named subquery that refers to itself, used to walk hierarchies and graphs
Parameter marker A :name placeholder in SQL whose value is passed separately
Sketch A small summary of a large set that answers an approximate question
Arrow The columnar in-memory format Spark uses to move data between the JVM and Python

1. Spark Declarative Pipelines

Since: 4.1.0 · Area: Pipelines · Source: SPARK-51727

Lineage: new in 4.1.

A pipeline is a set of datasets, each defined by a query, where some read others. Declarative Pipelines lets you state those datasets and leave the run order, parallelism and retries to Spark (SPARK-51727). A project is a spark-pipeline.yml file plus a folder of Python or SQL files, and you run it with the spark-pipelines command. A materialized view is a dataset whose result Spark computes and stores.

Nothing in the files says what runs first. Spark builds a graph from the references between datasets, which is why orders runs before revenue_by_region: the SQL view reads it. spark-pipelines dry-run checks syntax, analysis and cycles without writing anything.

The CLI works through Spark Connect, and the official image lacks the Python packages it needs. The first run fails with ModuleNotFoundError: No module named 'yaml', and then, with pandas and PyArrow missing too, with PACKAGE_NOT_INSTALLED. Install pyspark[pipelines] and both go away. The spec file needs a storage path, or the CLI stops with PIPELINE_SPEC_MISSING_REQUIRED_FIELD.

Before Spark 4.1

Before, the order lived in your driver script. You created each table yourself, in the right sequence, and you were the one who had to remember that revenue_by_region reads orders.

Runnable file: 10_declarative_pipeline_before.py.

spark.sql("DROP TABLE IF EXISTS orders")
spark.sql("""CREATE TABLE orders USING parquet AS
  SELECT * FROM VALUES (1,'eu',10.0D),(2,'us',20.0D),(3,'eu',30.0D),(4,'us',5.0D)
  AS t(id, region, amount)""")

# you keep the order right: this one has to come second
spark.sql("DROP TABLE IF EXISTS revenue_by_region")
spark.sql("""CREATE TABLE revenue_by_region USING parquet AS
  SELECT region, sum(amount) AS total, count(*) AS orders
  FROM orders GROUP BY region""")

A driver script that creates both tables in order on the left and the pipeline files on the right, both ending with eu 40.0 over 2 orders and us 25.0 over 2

Image 3: The run order moves out of your script and into the dependency between datasets.

With Spark 4.1: sample code

Runnable files: 07_declarative_pipelines.

# transformations/orders.py: a materialized view defined in Python
from pyspark import pipelines as dp
from pyspark.sql import DataFrame, SparkSession
spark = SparkSession.active()

@dp.materialized_view
def orders() -> DataFrame:
    return 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)")
-- transformations/revenue.sql: reads orders, so it runs after it
CREATE MATERIALIZED VIEW revenue_by_region AS
SELECT region, sum(amount) AS total, count(*) AS orders
FROM orders GROUP BY region;
# spark-pipeline.yml: the project spec; `storage` (checkpoint directory) is required
name: revenue
storage: file:///tmp/pipeline-storage
libraries:
  - glob:
      include: transformations/**
spark-pipelines dry-run   # syntax, analysis and cycle errors, nothing written
spark-pipelines run       # eu 40.0 over 2 orders, us 25.0 over 2

When it fits, and when it doesn’t

It’s a good fit for a chain of related tables, bronze to silver to gold say, where hand-written code today encodes the run order. You declare each dataset, Spark derives the order, and a dry run validates the graph before anything is written. It’s not the tool when a pipeline mixes many engines and an external orchestrator already owns the schedule, or when you need a custom schedule. And the classic first stumble is running spark-pipelines on the official image without the Python packages.

The pipeline project files feed spark-pipelines, which derives a graph in which orders runs before revenue_by_region because the SQL view reads it

Image 4: Nothing in the files states the order. Spark reads it from the dependency.

2. Real-time mode for stateless queries

Since: 4.1.0 · Area: Streaming · Source: SPARK-53736

Lineage: new in 4.1, for stateless Scala queries.

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 (SPARK-53736). The release notes say stateless queries can get down to single-digit milliseconds of latency, and that’s the honest pitch: this is for the cases where waiting for a batch is too slow.

You turn it on by changing the trigger, Trigger.RealTime("5 seconds"). The query stays an ordinary Structured Streaming query. The limits in 4.1 are real, though. It’s Scala only: PySpark’s trigger() doesn’t know about realTime yet, and passing it raises TypeError: DataStreamWriter.trigger() got an unexpected keyword argument 'realTime'. It’s stateless, so no aggregation. The source is Kafka, and the cluster needs a free task slot for every task, so size spark.sql.shuffle.partitions to what it can run at once.

Before Spark 4.1

The same query used the micro-batch trigger, and rows showed up when each batch finished.

Runnable file: 11_real_time_before_and_after.scala.

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

// stateless: uppercase every record
val out = spark.readStream.format("kafka")
  .option("kafka.bootstrap.servers", "kafka:29092")
  .option("subscribe", "events").option("startingOffsets", "latest").load()
  .select(upper(col("value").cast("string")).alias("v"))

// micro-batch trigger: rows appear when each batch ends
out.writeStream.format("console").outputMode("update")
  .option("checkpointLocation", "/tmp/ckpt_micro")
  .trigger(Trigger.ProcessingTime("5 seconds")).start()

The micro-batch trigger on the left and the real-time trigger on the right for the same uppercase query over a Kafka topic

Image 5: Only the trigger changes: micro-batches before 4.1, the real-time trigger with 4.1.

With Spark 4.1: sample code

Runnable file: 08_real_time_mode.scala.

// needs a Kafka broker; `out` is the same source and select as above
spark.conf.set("spark.sql.shuffle.partitions", "4")

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

Sending hello and world printed them as HELLO and WORLD in one batch. Run it with --packages org.apache.spark:spark-sql-kafka-0-10_2.13:4.1.4.

When it fits, and when it doesn’t

Use it for a stateless Scala query over Kafka where each record should be delivered as it lands, such as a filter or a projection feeding an alert. If you need a running count, state of any kind or Python, it’s not ready, and if micro-batch latency is fine you’ve got no reason to change. The classic mistake is trying to pass realTime from PySpark.

Micro-batches as numbered boxes on one lane and records flowing through an uppercase step to the console on the other

Image 6: Records on the left, results on the right, and no batch boundary in between.

3. SQL scripting

Since: 4.1.0 · Area: SQL scripting · Source: SPARK-54499, SPARK-53621, SPARK-52998

Lineage: SQL UDFs and session variables arrived in 4.0; scripting is generally available and on by default in 4.1.

SQL scripting lets a BEGIN ... END block declare variables, loop, branch and handle errors, all in SQL. In 4.1 it’s generally available and on by default (SPARK-54499), so spark.sql.scripting.enabled reads true with no setting from you. You get WHILE and FOR loops, IF, exit handlers and variable declarations, and 4.1 adds several variables in one DECLARE (SPARK-52998) and a fix for how NULL behaves in conditions (SPARK-52345).

A handler is code that runs when some condition occurs. An exit handler leaves the block after running. CONTINUE handlers (SPARK-53621) exist too, but they’re behind the internal flag spark.sql.scripting.continueHandlerEnabled, which is off by default. Treat them as unfinished.

Before Spark 4.1

If a task needed a loop or a bit of string-building around queries, the logic sat in a Python driver, with SQL as the thing it called.

Runnable file: 12_sql_scripting_before.py.

rows = spark.sql("""SELECT region, sum(amount) AS total
                    FROM orders GROUP BY region ORDER BY region""").collect()
print(" ".join(f"{r.region}={r.total}" for r in rows))   # eu=40.0 us=25.0

A Python loop over collected rows on the left and a SQL FOR loop on the right, both producing eu=40.0 us=25.0

Image 7: The loop moves from the driver into the query.

With Spark 4.1: sample code

Runnable file: 01_sql_scripting.sql.

-- a WHILE loop and two variables
BEGIN
  DECLARE total INT DEFAULT 0;
  DECLARE i INT DEFAULT 1;
  WHILE i <= 5 DO
    SET total = total + i;
    SET i = i + 1;
  END WHILE;
  SELECT total, i;     -- 15  6
END;
-- an exit handler catches the error and leaves the block
BEGIN
  DECLARE result DOUBLE DEFAULT 0;
  DECLARE EXIT HANDLER FOR DIVIDE_BY_ZERO
  BEGIN
    SET result = -1;
    SELECT 'caught divide by zero' AS status, result;
  END;
  SET result = 1 / 0;
  SELECT 'not reached' AS status, result;
END;
-- caught divide by zero  -1.0
-- a FOR loop over the rows of a query
BEGIN
  DECLARE msg STRING DEFAULT '';
  FOR r AS SELECT region, sum(amount) AS total FROM orders GROUP BY region ORDER BY region DO
    SET msg = msg || r.region || '=' || CAST(r.total AS STRING) || ' ';
  END FOR;
  SELECT trim(msg) AS summary;    -- eu=40.0 us=25.0
END;

Run a script through spark.sql(...) or the SQL runner of your choice. The spark-sql -f command splits a file at each ;, so a BEGIN ... END block gets cut into pieces and fails with PARSE_SYNTAX_ERROR.

When it fits, and when it doesn’t

It fits logic that has a few steps and a loop, like a maintenance job, a sequence of dependent statements, or error handling you’d otherwise write in a driver. Skip it when a set-based query will do, which is most of the time, and skip CONTINUE handlers until the flag is gone. The usual stumble is feeding a script to spark-sql -f and getting a parse error.

A BEGIN END block with a WHILE loop leads to three results: the loop total 15, an exit handler catching a divide by zero, and a FOR loop building eu=40.0 us=25.0

Image 8: One block, three behaviours: a loop, an exit handler and a loop over query rows.

4. Recursive common table expressions

Since: 4.1.0 · Area: SQL · Source: SPARK-24497

Lineage: new in 4.1.

A common table expression, a CTE, is a named subquery you define with WITH. A recursive one refers to itself, so it can walk a hierarchy or a graph: an org chart, a bill of materials, a folder tree (SPARK-24497). You write the starting rows, then UNION ALL, then a step that joins back to the CTE, and Spark repeats the step until it returns no rows.

There are guard rails. The default limit is 100 levels (spark.sql.cteRecursionLevelLimit) and a million rows (spark.sql.cteRecursionRowLimit). A query that never runs out of rows stops with RECURSION_LEVEL_LIMIT_EXCEEDED, and the message even tells you how to raise it: WITH RECURSIVE t(col) MAX RECURSION LEVEL 200.

Before Spark 4.1

Without recursion you looped in a driver, joining the previous level to the table once per level, and you had to know the depth up front.

Runnable file: 13_recursive_cte_before.py.

from pyspark.sql.functions import col, lit

spark.sql("""CREATE OR REPLACE TEMP VIEW emp AS SELECT * FROM VALUES
  ('ceo', CAST(NULL AS STRING)), ('vp', 'ceo'), ('dir', 'vp'), ('mgr', 'dir') AS t(name, boss)""")
emp = spark.table("emp")
level = spark.sql("SELECT name, 0 AS lvl FROM emp WHERE boss IS NULL")
result = level
for i in range(1, 4):                       # the depth has to be known up front
    level = (level.alias("o").join(emp.alias("e"), col("e.boss") == col("o.name"))
             .select(col("e.name").alias("name"), lit(i).alias("lvl")))
    result = result.union(level)
result.orderBy("lvl").show()                # ceo 0, vp 1, dir 2, mgr 3

A Python loop of joins on the left and a WITH RECURSIVE query on the right, both returning ceo 0, vp 1, dir 2 and mgr 3

Image 9: A loop of joins with a fixed depth becomes one query that stops by itself.

With Spark 4.1: sample code

Runnable file: 02_recursive_cte.sql.

-- count to five
WITH RECURSIVE t(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM t WHERE n < 5
) SELECT n FROM t;                       -- 1 2 3 4 5
-- walk an org chart from the top
CREATE OR REPLACE TEMP VIEW emp AS SELECT * FROM VALUES
  ('ceo', CAST(NULL AS STRING)), ('vp', 'ceo'), ('dir', 'vp'), ('mgr', 'dir') AS t(name, boss);

WITH RECURSIVE org(name, lvl) AS (
  SELECT name, 0 FROM emp WHERE boss IS NULL
  UNION ALL
  SELECT e.name, o.lvl + 1 FROM emp e JOIN org o ON e.boss = o.name
) SELECT * FROM org ORDER BY lvl;       -- ceo 0, vp 1, dir 2, mgr 3

When it fits, and when it doesn’t

Use it when the depth isn’t known in advance: an org chart, a folder tree, a parts explosion, a graph walk. If the hierarchy is a fixed two or three levels, plain joins are simpler. Make sure the step eventually returns nothing; a step that never does stops at the 100-level limit with RECURSION_LEVEL_LIMIT_EXCEEDED, which is the usual stumble.

An org chart with ceo at level 0, vp at 1, dir at 2 and mgr at 3, next to the recursive query that produces it

Image 10: Each level comes from the one above it, until a step returns no rows.

5. VARIANT, generally available, with colon paths

Since: 4.1.0 · Area: Types · Source: SPARK-54454, SPARK-52494, SPARK-53659

Lineage: VARIANT was introduced in 4.0 (SPARK-45827); 4.1 makes it generally available.

VARIANT is the Spark type for semi-structured data such as JSON, stored in a binary encoding so it’s parsed once. 4.0 introduced it. 4.1 makes it generally available and enabled by default (SPARK-54454), reads VARIANT in CSV and XML scans (SPARK-51298, SPARK-51503), and adds shredding, which infers a schema when writing Parquet so frequent fields can be read faster (SPARK-53659), with the Parquet VARIANT logical type annotated and readable (SPARK-54306, SPARK-54410).

You’ll type the colon-path operator (SPARK-52494) more than anything else here. v:user::string reads the user field of v and casts it to a string. A missing field returns NULL, and schema_of_variant tells you the type Spark found for a field: it reports BIGINT for the number 3 and STRING for the text "x".

Before Spark 4.1

You could read a field, but it took variant_get with a path string and a type string, which is a lot of typing for every field.

Runnable file: 14_variant_before.sql.

-- setup: two documents as VARIANT
CREATE OR REPLACE TEMP VIEW ev AS SELECT parse_json(j) v FROM VALUES
  ('{"user":"a","n":3,"tags":["x","y"]}'), ('{"user":"b","n":"x"}') AS t(j);

SELECT variant_get(v, '$.user', 'string') AS user,
       variant_get(v, '$.tags[0]', 'string') AS first_tag
FROM ev ORDER BY 1;
-- a  x
-- b  NULL

variant_get with a path and a type on the left and a colon path with a cast on the right, both returning a, x and b, NULL

Image 11: A path string and a type string become a colon path and a cast.

With Spark 4.1: sample code

Runnable file: 03_variant_colon_paths.sql.

SELECT v:user::string AS user,
       v:tags[0]::string AS first_tag,
       schema_of_variant(v:n) AS n_type
FROM ev ORDER BY 1;
-- a  x     BIGINT
-- b  NULL  STRING

When it fits, and when it doesn’t

It’s the right type for payloads whose shape varies from row to row, like events with different fields, and the colon path makes reading them painless. If the shape is fixed, a typed column or struct is easier to filter and document. The usual surprise is that a missing field is NULL rather than an error, so a typo in a path just gives you a column of nulls.

Two VARIANT rows pass through three colon-path expressions and come out as a and b, x and NULL, and BIGINT and STRING

Image 12: The same colon paths over two documents: the second has no tags, so that field comes back as NULL.

6. Parameter markers anywhere

Since: 4.1.0 · Area: SQL · Source: SPARK-53573

Lineage: parameter markers in expressions existed before; 4.1 allows them nearly anywhere.

A parameter marker is a :name placeholder in SQL whose value you pass separately. Earlier releases accepted them in expressions, like a value in a WHERE. 4.1 allows them nearly anywhere (SPARK-53573), through a pre-parser: a row count in LIMIT :n, a table name through IDENTIFIER(:t), even a default value inside a script. The values never become part of the SQL text, so there’s nothing to splice into a string and nothing to escape.

That last point is the real win. The usual workaround for a table name or a limit was an f-string, which works until somebody passes something nasty.

Before Spark 4.1

For anything that wasn’t a plain value you built the statement as a string.

Runnable file: 15_parameter_markers_before.py.

t, n = "orders", 2
spark.sql(f"SELECT * FROM {t} ORDER BY id LIMIT {n}").show()   # works, until the input is hostile

A Python f-string building the SQL on the left and a statement with IDENTIFIER and LIMIT markers plus an args dictionary on the right, both returning ids 1 and 2

Image 13: The values move out of the SQL text and into a separate dictionary.

With Spark 4.1: sample code

Runnable file: 05_parameter_markers.py.

spark.sql("SELECT * FROM IDENTIFIER(:t) ORDER BY id LIMIT :n",
          args={"t": "orders", "n": 2}).show()      # ids 1 and 2

spark.sql("""BEGIN
  DECLARE x INT DEFAULT :start;
  SET x = x + 1;
  SELECT x;
END""", args={"start": 41}).show()                  # 42

When it fits, and when it doesn’t

Use markers whenever a value, a table name or a limit comes from outside the query. They’d be overkill for a literal you type once. The common slip is forgetting IDENTIFIER(...) around a marker that stands for a name: a bare :t is a value, not an identifier.

Three SQL fragments with markers, LIMIT :n, IDENTIFIER(:t) and a DECLARE default, each fed by a separate args value

Image 14: Three places a marker can go, each with its value passed separately.

7. Sketch functions

Since: 4.1.0 · Area: SQL · Source: SPARK-52515, SPARK-54199, SPARK-52407

Lineage: new in 4.1.

A sketch is a small summary of a large set that answers an approximate question. It’s cheap to build, small to store, and, importantly, sketches from different pieces of data can be merged. 4.1 adds three families to SQL: approx_top_k for the most frequent values (SPARK-52515, with approx_top_k_combine in SPARK-52798), KLL sketches for quantiles (SPARK-54199, SPARK-53991) and Theta sketches for distinct counts and set operations (SPARK-52407). bitmap_and_agg (SPARK-53877) is part of the same batch of new functions.

The merge is the whole point. You can build a sketch per day or per partition, store it, and combine them later without going back to the raw data.

Before Spark 4.1

For a distinct count across two sets you counted exact distincts over the combined rows, which means keeping or re-reading the rows. percentile_approx covered quantiles, but its result isn’t a sketch you can store and merge.

Runnable file: 16_sketches_before.sql.

SELECT count(DISTINCT x) FROM (
  SELECT 1 AS x UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 3 UNION ALL SELECT 4);
-- 4

An exact count of distinct values on the left and a merged Theta sketch estimate on the right, both returning 4

Image 15: The exact count needs the rows. The sketch estimate needs only the two small sketches.

With Spark 4.1: sample code

Runnable file: 04_sketch_functions.sql.

-- the most frequent values
CREATE OR REPLACE TEMP VIEW clicks AS
SELECT * FROM VALUES ('a'),('b'),('a'),('c'),('a'),('b'),('d') AS t(page);
SELECT approx_top_k(page, 2) FROM clicks;                  -- [{a, 3}, {b, 2}]

-- quantiles of 1,000 latencies from a KLL sketch
CREATE OR REPLACE TEMP VIEW lat AS SELECT id AS ms FROM range(1, 1001);
SELECT kll_sketch_get_quantile_bigint(kll_sketch_agg_bigint(ms), 0.5D)  AS p50,
       kll_sketch_get_quantile_bigint(kll_sketch_agg_bigint(ms), 0.99D) AS p99
FROM lat;                                                  -- about 500 and 990

A KLL sketch is approximate, so the median can land a few ranks off the exact 500 (three runs in a row gave 500, 502 and 500).

-- two Theta sketches, merged: the distinct values of {1,2,3} and {3,4}
SELECT theta_sketch_estimate(theta_union_agg(s)) FROM (
  SELECT theta_sketch_agg(x) s FROM VALUES (1),(2),(3) AS a(x)
  UNION ALL
  SELECT theta_sketch_agg(x)   FROM VALUES (3),(4)   AS b(x));    -- 4

When it fits, and when it doesn’t

Sketches fit when exactness isn’t needed and the data is big enough that keeping it around hurts: top pages, latency percentiles, unique visitors per day, merged into a weekly figure. For a small table, an exact answer is cheap and better. Remember that the quantiles are approximate: for the numbers 1 to 1,000 the sketch gave a median of 500 and a 99th percentile of 990, and the median came back as 502 on another run.

Three tiles for approx_top_k, a KLL sketch and a Theta union, each showing its small result: the top two values, a p50 and p99, and four distinct values

Image 16: Three kinds of sketch, each a small summary of a larger set.

8. Arrow-native Python UDFs and UDTFs

Since: 4.1.0 · Area: Python · Source: SPARK-52214, SPARK-52979

Lineage: pandas_udf existed before; the Arrow-native decorators are new in 4.1.

A Python UDF runs in a Python worker, and Spark hands it data in Arrow batches. A pandas_udf converts each batch to a pandas Series first. In 4.1 the @arrow_udf decorator (SPARK-52214) and its table-function cousin (SPARK-52979) hand your function the PyArrow arrays directly, so you can use pyarrow.compute and skip the conversion. In the plan the node is ArrowEvalPython.

It needs PyArrow. The official apache/spark:4.1.4-python3 image doesn’t ship it, and a plain import pyarrow fails with ModuleNotFoundError: No module named 'pyarrow'. Install pyspark[sql] or add pyarrow and pandas to the image.

Before Spark 4.1

A pandas_udf was the vectorised option, and your function received a pandas Series.

Runnable file: 17_arrow_udf_before_pandas.py.

import pandas as pd
from pyspark.sql.functions import pandas_udf, col

df = spark.sql("SELECT * FROM VALUES (1, 10.0D), (2, 20.0D) AS t(id, amount)")

@pandas_udf("double")
def with_tax(amount: pd.Series) -> pd.Series:
    return amount * 1.18

df.select("id", with_tax(col("amount")).alias("gross")).show()   # 11.799999999999999, 23.599999999999998

A pandas UDF on the left and an Arrow UDF on the right, both returning 11.8 and 23.6 for the two amounts

Image 17: The function receives PyArrow arrays instead of pandas Series.

With Spark 4.1: sample code

Runnable file: 06_arrow_udf.py.

import pyarrow as pa
import pyarrow.compute as pc
from pyspark.sql.functions import arrow_udf, col

@arrow_udf("double")
def with_tax(amount: pa.Array) -> pa.Array:
    return pc.multiply(amount, 1.18)

df.select("id", with_tax(col("amount")).alias("gross")).show()   # same two values
df.select("id", with_tax(col("amount")).alias("gross")).explain()
# ArrowEvalPython [with_tax(amount)], [pythonUDF0], 250

When it fits, and when it doesn’t

Reach for arrow_udf when your logic is already expressible in pyarrow.compute and you’d like to avoid the pandas detour. Stick with pandas_udf if the function leans on pandas features. In 4.1 the Arrow path isn’t the default for plain Python UDFs (spark.sql.execution.pythonUDF.arrow.enabled is false), and the usual stumble is running without PyArrow installed.

Two lanes: a pandas UDF goes from JVM rows through Arrow batches to a pandas Series, while an Arrow UDF goes through Arrow batches to a PyArrow array

Image 18: The Arrow UDF skips the pandas Series step.

Smaller additions worth knowing

Feature What it does Needs
Stored procedures API (SPARK-44167) Catalogs can expose stored procedures through a new API A connector
Python Data Source filter pushdown (SPARK-51271) Filters reach Python data sources, and streaming ones can use Arrow writers (SPARK-53030) Nothing
JDBC driver for Spark Connect (SPARK-53484) A JDBC driver that talks to a Connect server A Connect server
ML on Connect (SPARK-51236) Generally available in the Python client, with smarter model caching A Connect server
DSv2 join pushdown (SPARK-52187) Joins push down to JDBC sources such as Postgres, Oracle, MySQL and SQL Server A JDBC source
MERGE INTO schema evolution (SPARK-54274) and table constraints (SPARK-51207) Engine support that a connector implements A connector
State store hardening (SPARK-51972, SPARK-51358) RocksDB file checksums, snapshot lag detection and memory accounting Nothing
Checksum-based shuffle retry (SPARK-51756) A stage retries in full when shuffle data doesn’t match its checksum Nothing
Large Spark Connect plans zstd-compressed protobuf plans and chunked Arrow result streaming Nothing
77 new built-in functions Including uuid with a seed (SPARK-53654), try_to_date, chr and bitmap_and_agg Nothing

Smaller additions in code

New functions. chr, try_to_date and a seeded uuid work out of the box:

Runnable file: 18_recursion_limit_and_new_functions.sql.

SELECT chr(65) AS c, try_to_date('not a date') AS d, uuid(42) = uuid(42) AS same;
-- A  NULL  true

The recursion limit. A recursive query that never runs out of rows stops at the level limit, and the message says how to raise it:

WITH RECURSIVE t(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM t) SELECT count(*) FROM t;
-- [RECURSION_LEVEL_LIMIT_EXCEEDED] Recursion level limit 100 reached but query has not exhausted,
-- try increasing it like 'WITH RECURSIVE t(col) MAX RECURSION LEVEL 200'.

Added in patch releases

Patch releases are mostly bug fixes, and I only list additions here. Going through the 4.1.1 to 4.1.4 changes, two small ones qualify, both in 4.1.2:

  • Binary sketch aggregations in KLL (SPARK-54785): the KLL sketch functions from feature 7 gain support for binary sketch aggregations.
  • Hidden columns in DataFrame column resolution (SPARK-55070): a hidden column can now be resolved through the DataFrame API.

Nothing else in 4.1.1, 4.1.3 or 4.1.4 adds a feature.

Version lineage

Several 4.1 features build on 4.0. Read the 4.1 column as what this release added.

Feature 4.0 4.1
VARIANT Introduced (SPARK-45827) Generally available, colon paths, shredding (SPARK-54454, SPARK-52494)
Procedural SQL Session variables, SQL UDFs (SPARK-42849, SPARK-46057) SQL scripting generally available, recursive CTEs (SPARK-54499, SPARK-24497)
Pipelines none Declarative Pipelines (SPARK-51727)
Real-time streaming none Real-time mode, stateless Scala (SPARK-53736)
Python UDFs Polymorphic Python UDTFs Arrow UDF and UDTF decorators (SPARK-52214, SPARK-52979)
Approximate analytics none approx_top_k, KLL and Theta sketches (SPARK-52515, SPARK-54199, SPARK-52407)

Settings and costs

Setting Default What it does
spark.sql.scripting.enabled true SQL scripting
spark.sql.scripting.continueHandlerEnabled false, internal CONTINUE handlers in scripts
spark.sql.cteRecursionLevelLimit 100 How many levels a recursive CTE may run
spark.sql.cteRecursionRowLimit 1000000 How many rows a recursive CTE may produce
spark.sql.execution.pythonUDF.arrow.enabled false Arrow for plain Python UDFs
spark.sql.execution.pandas.convertToArrowArraySafely true PyArrow raises on unsafe conversions in Arrow-enabled UDFs
spark.sql.shuffle.partitions 200 For real-time mode, the number of task slots the cluster can run at once
Feature Cost to plan for
Declarative Pipelines A Connect-based CLI and extra Python packages, and a materialized view stores its result
Real-time mode One free task slot per task, held for the life of the query
Recursive CTEs A level limit of 100 and a row limit of a million, both configurable
Sketches Approximate answers; the quantiles are off by a little
Arrow UDFs PyArrow must be installed

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.

ModuleNotFoundError: No module named 'yaml'. The official image lacks the Python packages spark-pipelines needs. Fix: pip install "pyspark[pipelines]".

[PIPELINE_SPEC_MISSING_REQUIRED_FIELD] Pipeline spec missing required field storage. The spark-pipeline.yml has no storage entry. Fix: Add storage, a directory where checkpoints for the pipeline’s streaming tables are stored, for example storage: file:///tmp/pipeline-storage. The programming guide marks it required.

[PACKAGE_NOT_INSTALLED] Pandas >= 2.2.0 must be installed. The pipelines CLI imports the Spark Connect client, which needs pandas and PyArrow. Fix: pip install "pyspark[pipelines]", or install pandas, pyarrow and numpy next to the other pipeline packages.

ModuleNotFoundError: No module named 'pyarrow'. The official image has no PyArrow, so arrow_udf can’t import. Fix: pip install "pyspark[sql]".

TypeError: DataStreamWriter.trigger() got an unexpected keyword argument 'realTime'. Real-time mode is Scala only in 4.1. Fix: Use Trigger.RealTime from Scala.

[RECURSION_LEVEL_LIMIT_EXCEEDED]. A recursive CTE ran 100 levels without running out of rows. Fix: Make the step terminate, or raise the limit with MAX RECURSION LEVEL.

[PARSE_SYNTAX_ERROR] on the first line of a BEGIN ... END script run with spark-sql -f. The command splits the file at each ;, so a script is cut into pieces. Fix: Run the script through spark.sql(...).

TypeError: unsupported operand type(s) ... 'type' and 'type' from a Python worker. Python 3.9 can’t run 4.1, and the workers started with it. Fix: Use Python 3.10 or newer, and point PYSPARK_PYTHON at it.

Upgrade checklist: what can break

Most upgrades are just a version bump, but Python, connector jars and a handful of behaviour changes can catch you out. Work through this list on a staging copy of your heaviest job first.

1. Runtime and dependencies

Requirement 4.1 value Source
Python 3.10 or newer; 3.9 is dropped requires_python of pyspark==4.1.4 on PyPI (SPARK-52561)
pandas, PyArrow, NumPy (pyspark[sql]) 2.2.0, 15.0.0 and 1.21 or newer requires_dist on PyPI (SPARK-52928)
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, version 2.13.17 the release notes (SPARK-53585)
Java 17 or 21 Spark 4.1.4 overview
Kafka connector spark-sql-kafka-0-10_2.13:4.1.4 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.0 does not mean there is one for 4.1. List the artifacts from your spark.jars.packages and ask Maven Central whether each has a 4.1.4 build, so you learn about a missing one before the cluster does.

Runnable file: 19_check_maven_artifacts.py.

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.1.4"

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.1.4
OK       spark-avro_2.13:4.1.4

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

3. Behaviour changes to test

The first rows come from the 4.1 release notes; the rest come from the official SQL and PySpark migration guides.

Change What to do Source
BinaryType maps to Python bytes everywhere in PySpark spark.sql.execution.pyspark.binaryAsBytes=false restores bytearray PySpark migration guide, SPARK-53696
Arrow-enabled UDFs raise on unsafe conversions such as overflow and truncation spark.sql.execution.pandas.convertToArrowArraySafely=false restores PySpark migration guide, SPARK-52904
Arrow-optimized UDFs take UDT input and output, and skip the pandas conversion, which changes type coercion spark.sql.execution.pythonUDF.arrow.legacy.fallbackOnUDT and spark.sql.legacy.execution.pythonUDF.pandas.conversion.enabled restore PySpark migration guide
DataFrame['name'] on Spark Connect no longer validates the column eagerly Set PYSPARK_VALIDATE_COLUMN_NAME_LEGACY=1 to restore PySpark migration guide
The pandas API on Spark works under ANSI mode Check the compute.ansi_mode_support option PySpark migration guide, SPARK-53295
The Parquet reader no longer assumes a struct is null when all requested fields are missing spark.sql.legacy.parquet.returnNullStructIfAllFieldsMissing=true restores SQL migration guide
The Thrift Server returns a 1-based ORDINAL_POSITION from GetColumns spark.sql.legacy.hive.thriftServer.useZeroBasedColumnOrdinalPosition=true restores SQL migration guide
spark.checkpoint.compress and BloomFilter V2 are on by default, and the S3 Magic Committer is the default for S3 buckets Recheck checkpoint sizes, filters and S3 committers SPARK-52174, SPARK-47547, SPARK-47618
Native Netty transports are preferred, and double-quote escaping follows the SQL specification Recheck network settings and strings with doubled quotes SPARK-54032, SPARK-52545

4. Roll out in this order

  1. Python first. Move to Python 3.10 or newer, with PyArrow 15.0.0 or newer, on your current Spark version. It’s independent and easy to reverse.
  2. Python UDFs and data sources. Check the bytes change and the unsafe-conversion errors.
  3. Connectors. Run the script above. Keep any job whose connector is missing where it is.
  4. Batch jobs. Move stateless batch jobs to 4.1 and compare outputs and runtimes.
  5. 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

  • Running spark-pipelines on the official image. Install pyspark[pipelines] first.
  • Using arrow_udf without PyArrow. The official image doesn’t include it.
  • Passing realTime from PySpark. Real-time mode is Scala only in 4.1.
  • Feeding a script to spark-sql -f. Use spark.sql(...) for BEGIN ... END blocks.
  • Recursing without a stop. The step must eventually return no rows, or you hit the 100-level limit.

Known limitations in this release

  • Real-time mode. Scala only, stateless, Kafka as the source. PySpark can’t use the trigger.
  • Declarative Pipelines. The CLI needs extra Python packages and runs through Spark Connect.
  • SQL scripting. CONTINUE handlers sit behind an internal flag that is off by default.
  • Recursive CTEs. 100 levels and a million rows by default.
  • Arrow UDFs. PyArrow has to be installed, and plain Python UDFs don’t use Arrow by default.
  • Connector features. Stored procedures, table constraints and MERGE schema evolution are engine support that a connector has to implement.

Cheat sheet

Spark 4.1 cheat sheet: the syntax of each feature and what it needs first, such as a package, a Kafka source or PyArrow

Image 19: 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.1?

Spark 4.1.0, released on 16 December 2025, adds Declarative Pipelines, stateless real-time mode, generally available SQL scripting and VARIANT, recursive CTEs, parameter markers almost anywhere, sketch functions and Arrow-native Python UDFs.

Which features work without a flag?

SQL scripting, recursive CTEs, VARIANT, parameter markers and the sketch functions work as they are. Declarative Pipelines needs the pipelines packages, arrow_udf needs PyArrow, and real-time mode needs the trigger, a Kafka source and Scala.

Why does spark-pipelines fail with No module named 'yaml'?

The official image doesn’t include the packages the CLI needs. Install pyspark[pipelines].

Can I use real-time mode from PySpark?

Not in 4.1. trigger(realTime=...) raises a TypeError. It’s Scala only, and stateless.

Why does my recursive query fail with RECURSION_LEVEL_LIMIT_EXCEEDED?

The step never returned an empty result, so Spark stopped at the 100-level limit. Fix the stop condition, or raise the limit with MAX RECURSION LEVEL.

Can I use a parameter marker for a table name?

Yes, through IDENTIFIER(:t). A bare :t is a value.

Why does arrow_udf fail to import?

PyArrow isn’t installed. The official image doesn’t ship it, and pip install "pyspark[sql]" adds it.

Does Spark 4.1 still support Python 3.9?

No. 4.1 needs Python 3.10 or newer, and the minimum PyArrow is 15.0.0 and pandas 2.2.0.

Which Spark 4.1 release should I use?

4.1.4 is the latest 4.1 release. Fixes land in the patch releases, so start there.

Why does pip install pyspark==4.1.4 fail?

The wheel requires Python 3.10 or newer. Check python3 --version.

Summary

Spark 4.1 is about taking things you used to script around Spark and doing them inside it. Pipelines declare their own order, SQL gets scripts, loops, recursion and safe parameters, and VARIANT and the sketch functions make semi-structured and approximate data easier to handle. Most of it works with no setup. A few things need a package, PyArrow or a Scala-only trigger, so check those before you plan around them.

If you only test one thing before upgrading, make it the Python side: the version floor moved to 3.10, bytes is now the Python type for binary columns everywhere, and Arrow-enabled UDFs raise on unsafe conversions.

Further reading

Trademarks

Apache Spark, Apache Kafka, Apache Parquet, Apache Arrow and Apache are either registered trademarks or trademarks of The Apache Software Foundation in the United States and other countries. The Apache Software Foundation does not 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.