Skip to content

Architecture

One protocol, one Rust core, two front-ends. This project reimplements the Spark Connect client - plan building, gRPC transport, and Arrow result decoding - in Rust, and exposes it both as a native Rust library and, through PyO3, as a drop-in pyspark package.

The one big idea

A Spark Connect client does three things: it builds a protobuf plan from your DataFrame/SQL operations, sends it over gRPC to a Spark Connect server, and decodes the Arrow result the server streams back. The reference client does all three in Python.

Here, those three jobs live in Rust crates. On top of that core sit two thin front-ends that share it: a synchronous Rust API shaped like PySpark, and a pyspark Python package (a PyO3 extension) that is byte-for-byte compatible with the reference client. Same spark.connect protocol, same server, same results.

End-to-end picture

flowchart TD
    subgraph front["Front-ends"]
        PY["User PySpark code (unchanged)"]
        SKIN["python/pyspark - drop-in package"]
        EXT["_pyspark - PyO3 extension (crates/pyspark-rs)"]
        RS["User Rust code"]
    end

    subgraph core["Rust core"]
        API["apache-spark-connect - DataFrame / Column / functions / SQL"]
        PLAN["Plan builder - spark.connect protobuf"]
        XPORT["apache-spark-connect-core - gRPC channel, retries, reattach, artifacts"]
        ARROW["Arrow result decode"]
    end

    SERVER["Spark Connect server (Spark 4.3+, :15002)"]
    OUT["Rows / Arrow - optionally DataFusion or Polars (Rust); pandas (Python)"]

    PY --> SKIN --> EXT --> API
    RS --> API
    API --> PLAN --> XPORT
    XPORT -->|"ExecutePlan (gRPC/HTTP2)"| SERVER
    SERVER -.->|"Arrow IPC batches"| XPORT
    XPORT --> ARROW --> OUT
    OUT -.-> PY
    OUT -.-> RS

Everything below the front-ends is shared: the Python package doesn't reimplement anything the Rust API doesn't already do - it calls straight into the same core through the _pyspark extension.

The crates

A Cargo workspace of library crates, plus a Python skin:

Component Path Responsibility
apache-spark-connect-proto crates/spark-connect-proto Generated spark.connect.* gRPC/protobuf types
apache-spark-connect-core crates/spark-connect-core Transport: channel, retries, reattach, artifacts, errors
apache-spark-connect crates/spark-connect The DataFrame API: session, dataframe, column, functions, plan, group, catalog, window, readwriter, streaming, types
apache-spark-connect-macros crates/spark-connect-macros The #[spark_wasm_udf] procedural macro of a Rust UDF
apache-spark-connect-build crates/spark-connect-build The build.rs helper that compiles a crate's Rust UDFs to a WebAssembly module
pyspark-rs crates/pyspark-rs PyO3 bindings - builds the _pyspark extension module
Python skin python/pyspark The drop-in pyspark package (+ vendored pyspark.pandas, cloudpickle, pyspark.testing)
flowchart LR
    PROTO["spark-connect-proto"] --> CORE["spark-connect-core"]
    CORE --> SC["spark-connect (DataFrame API)"]
    SC --> PYO3["pyspark-rs (PyO3)"]
    PYO3 --> SKIN["python/pyspark skin"]
    SC --> RUSTAPP["your Rust app"]
    MACROS["spark-connect-macros (UDF macro)"] --> RUSTAPP
    BUILD["spark-connect-build (UDF build.rs)"] --> RUSTAPP

A query's lifecycle

When you call an action such as count() or show(), the lazily-built plan is serialized and sent to the server; results stream back as Arrow batches.

Day-time intervals use signed 64-bit microseconds in Rust (Value::DayTimeInterval) and Python datetime.timedelta values. createDataFrame supports inferred and explicit interval schemas, including nested structs, lists, maps, and nulls. Collected rows can be passed back with their schema. As in PySpark, an int or a float for an interval field is taken as microseconds, and a value outside the signed 64-bit microsecond range is an error.

sequenceDiagram
    participant App as Your code (Rust or pyspark)
    participant API as spark-connect
    participant Core as spark-connect-core
    participant Srv as Spark Connect server

    App->>API: range(...).select(...).filter(...)
    Note over API: builds a spark.connect Plan (lazy)
    App->>API: count() / show()  (action)
    API->>Core: execute(plan)
    Core->>Srv: ExecutePlan(plan)  [gRPC/HTTP2]
    Srv-->>Core: ExecutePlanResponse* (Arrow IPC batches)
    Note over Core,Srv: ReattachExecute resumes a broken stream
    Core->>API: decoded Arrow batches
    API-->>App: rows / count / DataFrame

Transformations are lazy - they only build up the plan. Only an action triggers ExecutePlan. If the response stream breaks mid-flight, or the server ends it before the result is complete (as it does after spark.connect.execute.reattachable.senderMaxStreamDuration or senderMaxStreamSize), the core's reattachable-execute iterator resumes from the last response it saw, so long results survive transient disconnects. Like the reference client, it releases each response it has read, and the whole execution once the result is complete, so the server does not keep them.

spark.sql() is the exception, as in the reference client: it sends the statement at once. A command such as CREATE VIEW or SET takes effect there, and its DataFrame holds the result the server returned; a statement that does not parse or resolve fails there. A query's DataFrame still runs at an action.

Each plan node gets its plan ID once, the first time it is sent, and keeps it, as in the reference client. Re-executing a DataFrame therefore sends the same relation, and a DataFrame built on another keeps that input's plan IDs, so the server's per-session plan cache (spark.connect.session.planCache.*) can reuse the plans it already resolved instead of resolving them again. As with the reference client, a re-executed DataFrame can then use its earlier resolution. A DataFrame from spark.read.parquet(path), for example, keeps the file listing it resolved: once the files under path are overwritten, running it again fails with FAILED_READ_FILE.FILE_NOT_EXIST, while a new spark.read.parquet(path) reads the new files. Setting spark.connect.session.planCache.enabled to false turns the cache off, on the server or for a session with spark.conf.set.

Python Arrow table handoff

toArrow() reads the Arrow schema of the analyzed schema of the DataFrame first, as PySpark's does, so that a type which PySpark does not convert to Arrow raises before the query runs. It then collects decoded batches, uses arrow-rs's IntoPyArrow for one boxed RecordBatchReader, and casts the table to that schema. Compatible value and offset buffers are shared; network decoding, sliced validity bitmaps, the cast and pandas conversion may still copy. Batch schema consistency is validated before export. Field names or timezones containing NUL use IPC over the collected batches, without another RPC. Empty batch vectors retain the empty-schema behavior. _to_table(), PySpark's private method, gives the table of this handoff, with the schema that the server sent, cast without a copy to the metadata that PySpark reads of the server's IPC stream: {} for the schema and for each field without metadata, nested ones too, and the keys of a field's metadata in the server's order, which the decoded batches do not keep. With spark.sql.execution.arrow.pyspark.selfDestruct.enabled, toPandas copies each column of each batch into its own allocation before the conversion, as PySpark's _execute_and_fetch does.

createDataFrame(pyarrow_table) uses the reverse boundary: Spark's schema and timestamp conversion helpers normalize the table, then arrow-rs imports its RecordBatchReader through the C Stream interface. A table of a field name that holds a NUL, at any depth, which the C strings of that interface end at, is read of its IPC stream instead, which holds the names whole, as PySpark's stream does. The Rust core serializes those batches to IPC for the local relation sent to Spark. No Python rows are materialized; casts, buffer alignment, and IPC serialization may still copy. Empty tables require an explicit schema, matching PySpark Connect. Every createDataFrame of data that is not empty, of any kind, reads the settings of all of its conversions in one Config request before it converts any data, as PySpark's does: the 13 keys that PySpark 4.3.0 reads, in its order (the timestamp type and the session time zone, the local-relation settings, the pandas and inference settings, and Arrow's large types). Every conversion path takes its settings from that request, including the relation's cache threshold, and empty data reads none. Under spark.sql.execution.arrow.useLargeVarTypes, the strings and binaries of every path that converts to a schema, local rows and columns and the pandas string columns of the binding's fast path too, are sent as Arrow's large types, as PySpark's to_arrow_type makes them, but those of a variant, a geometry and a geography. Each path compares the cache threshold with the size of the Arrow data as pyarrow's nbytes counts it, of its len offsets per string, binary, list or map array, as PySpark compares _table.nbytes. The Rust API's create_dataframe and create_dataframe_from_columns read the same settings in one request, once they have converted their rows or columns, and apply the cache threshold at any size too. Of no rows, or columns of no rows, they send the schema alone and read none, as PySpark's empty data does, and so does create_dataframe_from_arrow of batches of no rows and a schema. Every pandas DataFrame, of any class, labels and arrays, converts with PySpark's conversion of each column to Arrow, in the session time zone (prepare_pandas_table and prepare_inferred_pandas_table of pyspark/sql/_pandas_input.py, of the vendored create_arrow_table_from_pandas, as pyspark.sql.connect.session binds the conversions as PySpark Connect's module of the session binds them), whose table this importer sends, as PySpark's createDataFrame does, with the json() of the struct as the schema of the relation, which reads the attributes of the types as the conversion reads them, of a Python subclass or a patched class too (pyspark_schema_json_text of src/types.rs). Fast paths take plain frames of some columns, of which they make the values of that conversion without its per-column work; the frames that they decline, such as a subclass or a frame of customized hooks, take PySpark's conversion. Without PyArrow, which that conversion needs, the native row path of the session converts every frame from its rows of Python values, and no fast path is taken (see dev/parity/known-differences.md). verifySchema remains ignored for pandas input, matching Spark Connect. The fast paths: - Pandas inputs with only NumPy int64 or pandas nullable Int64 columns use this importer, preserving integer precision and null masks without Python rows. Small frames (fewer than 1,000 rows) with only NumPy columns are left to PySpark's conversion; nullable Int64 columns take this path at any size. It accepts inferred schemas, complete string column names, and explicit StructType schemas whose fields are all LongType. - Pandas frames whose columns are all datetime64 of microseconds (or nanoseconds of whole microseconds), with an explicit StructType of TimestampType fields, use this importer: aware columns, and naive ones on a UTC host of a UTC session, whose values are their instants as they are. - Pandas frames of at least 100,000 rows whose columns are all NumPy float64, with an explicit StructType of DoubleType fields, are encoded to Arrow IPC from their columns, with pandas' missing values as nulls, and sent inline below the cache threshold. - Pandas object columns containing exact datetime.date values or None use the Arrow importer at 10,000 rows or more with an explicit StructType of DateType fields. - Pandas frames of at least 10,000 rows whose columns are all kept in pandas' Arrow string storage (string[pyarrow] in pandas 2.2 and later, and the str dtype of pandas 3), with an explicit StructType of StringType fields, pass that storage to this importer as Arrow string columns, without Python rows; columns of exact str objects are encoded to Arrow IPC natively, a checkpoint of the conversion budget a value. Inputs at or above spark.sql.session.localRelationCacheThreshold are serialized into independent IPC streams and uploaded as session-scoped cache artifacts. The plan carries ChunkedCachedLocalRelation hashes instead of embedding the entire payload. Spark infers omitted schemas from the Arrow streams; explicit schemas travel in the local relation or a separate schema artifact. Chunk sizes, upload batch sizes, and the total relation size limit follow the server's local-relation settings; artifact RPC messages use 32 KiB pieces, with SHA-256 deduplication and CRC checks.

Two front-ends, one core

use spark_connect::{SparkSession, functions as f};

let spark = SparkSession::builder()
    .remote("sc://localhost:15002")
    .get_or_create()?;
spark.range(100)?.select([f::col("id")]).show(20)?;
from pyspark.sql import SparkSession, functions as sf

spark = SparkSession.builder.remote("sc://localhost:15002").getOrCreate()
spark.range(0, 100).select(sf.col("id")).show(20)

Both paths build the same protobuf plan through the same Rust core and get the same Arrow results back. The Python package is a compatibility skin over pyspark-rs; it does not fork or reimplement the client logic.

Rust UDFs on the executors

Beyond the client, a Rust function can be compiled to WebAssembly and run as a Spark UDF on the executors - shipped inside a standard PythonUDF and executed with wasmtime, so nothing Rust-specific is needed server-side.

flowchart LR
    RUSTFN["#[spark_wasm_udf] fn"] -->|"build.rs -> wasm32"| WASM[".wasm module (embedded)"]
    WASM -->|"cloudpickled into a PythonUDF"| SRV["Spark executors"]
    SRV -->|"wasmtime runs it per batch or row"| RES["UDF result column"]

See Rust UDFs via WebAssembly for the full story.

Design principles

  1. Don't fork PySpark's semantics - mirror the public API and match the reference client's protobuf output, verified by golden-proto tests.
  2. One core, thin front-ends - the Python package adds no client logic the Rust API doesn't already have.
  3. Correctness is gated in CI - golden-proto tests guard plan building; the official Apache Spark Connect test suite guards transport and Arrow paths (see the CI notes under dev/design/).
  4. Version = Spark version - a release's crate/wheel version is that of the Spark release it targets, so the number tells you which Spark it speaks. master carries the next development version.

For the deeper design write-ups (design notes, CI, the official test suite, and acceptance criteria), see dev/design/ in the repository.