Spark & PySpark
Writing Production-Grade PySpark - Patterns That Scale
Most PySpark Code Works in Dev and Breaks in Production. Here Are the Patterns That Survive Both.

TL;DR
inferSchema=Truereads your entire dataset to guess types — and guesses wrong when upstream data changes; define schemas explicitly- Nulls behave differently in different aggregations —
SUMignores them,COUNT(*)counts them, nulls ingroupBykeys create a hidden null group that corrupts totals silently - Copy-pasted transformation logic across pipelines produces subtly different results for the same business concept; centralise it into tested, shared functions
- Testing PySpark transformations locally with a lightweight
SparkSessioncuts feedback time from 20 minutes to 10 seconds — test the logic, not the cluster - A pipeline that fails visibly on bad data is easier to fix than one that silently produces wrong output; add row count checks and schema assertions at key checkpoints
Dev code handles the happy path. Production code handles everything else.
The revenue pipeline had been running for four months. Clean code. No errors. Dashboard updated daily.
One Monday morning, the upstream team added acurrency_codecolumn to the events table.inferSchema=Trueread the new column, inferred it as a string, and kept going.
Except two downstream transformations were casting every column after position 7 by index rather than by name. The new column shiftedamountto position 8. The cast hitcurrency_codeinstead.amountbecame null.
Revenue showed zero for three days. Nobody noticed until a VP asked why the weekly number hadn’t updated.
An explicit schema would have crashed on the unexpected column immediately. Instead it adapted silently — and broke everything downstream.
The Code That Works in Dev and Breaks in Production
Dev data is clean, small, and predictable. Production data is messy, large, and evolves without warning. The PySpark code that handles the first rarely handles the second without modification — because dev code optimises for getting to a result, while production code optimises for staying correct when conditions change.
The five patterns below are the ones that separate jobs that run correctly for six months from jobs that quietly corrupt data starting on the day something upstream changes.
Pattern 1: Schema Enforcement at Ingestion
Why inferSchema Is a Production Risk
inferSchema=True samples a portion of your data, guesses at column types, and returns a DataFrame. In development this is convenient. In production it has three problems.
First, it is slow — Spark reads enough of the dataset to infer types, which can add significant startup cost on large tables. The exact sampling behavior depends on format and Spark version, but the overhead is real and unnecessary when you already know the schema.
Second, it is non-deterministic on mixed-type data. A column that is mostly integers but contains one string value will be inferred as string. Whether that string is in the sample determines the inferred type. Whether the sample contains it depends on file ordering.
Third, and most importantly: it adapts silently to schema changes. When an upstream team adds a column, renames a field, or changes a type, inferSchema adjusts without complaint. Your downstream code may not.
Defining and Enforcing Schemas Explicitly
from pyspark.sql.types import (
StructType, StructField,
StringType, DoubleType, LongType, TimestampType, BooleanType
)
TRANSACTION_SCHEMA = StructType([
StructField("transaction_id", StringType(), nullable=False),
StructField("merchant_id", StringType(), nullable=False),
StructField("amount", DoubleType(), nullable=False),
StructField("currency", StringType(), nullable=True),
StructField("transaction_ts", TimestampType(), nullable=False),
StructField("is_refund", BooleanType(), nullable=False),
StructField("customer_id", LongType(), nullable=True),
])
# Read with explicit schema — fails fast if data doesn't match
df = (
spark.read
.schema(TRANSACTION_SCHEMA)
.option("mode", "FAILFAST")
.parquet("s3://bucket/transactions/")
)
# Explicit schema + FAILFAST:
# malformed records fail immediately instead of being silently coercedFAILFAST mode throws an exception on any record that doesn't match the schema. The alternative is PERMISSIVE (default) — which sets non-conforming fields to null and logs a corrupt record.
For trusted internal sources where an unexpected record means something upstream broke, FAILFAST is often preferable — it crashes loudly rather than silently producing nulls. For external feeds, clickstreams, or event pipelines where bad records are expected and should be quarantined rather than blocking the job, PERMISSIVE with a dead-letter queue is the more appropriate pattern.
Validating Schema on Arrival
Even with an explicit schema, it is worth validating that the actual columns present match what your pipeline expects — before running any transformations:
def validate_schema(df, expected_schema: StructType):
expected_fields = {f.name: f.dataType for f in expected_schema.fields}
actual_fields = {f.name: f.dataType for f in df.schema.fields}
missing = set(expected_fields) - set(actual_fields)
extra = set(actual_fields) - set(expected_fields)
mistyped = {
col for col in expected_fields
if col in actual_fields
and expected_fields[col] != actual_fields[col]
}
if missing:
raise ValueError(f"Missing columns: {missing}")
if mistyped:
raise ValueError(f"Type mismatches: {mistyped}")
if extra:
# Log extra columns as a warning — upstream may be adding fields
print(f"WARNING: unexpected columns present: {extra}")
validate_schema(df, TRANSACTION_SCHEMA)Missing columns and type mismatches crash the job immediately with a clear message. Extra columns produce a warning but do not block — your pipeline selects only the columns it needs, so extras are harmless.
Pattern 2: Null Handling That Doesn’t Silently Corrupt
Nulls are the most common source of silent correctness failures in PySpark. The rules are consistent but non-obvious, and getting them wrong produces aggregations that are subtly wrong rather than obviously broken.
How Nulls Behave in Aggregations
# The rules — know these before writing any aggregation
# SUM: nulls are ignored (not treated as zero)
# SUM([100, null, 200]) = 300, not 300 + null
# COUNT(*): counts all rows including nulls
# COUNT(*) on [row1, row2_with_nulls, row3] = 3
# COUNT(col): counts non-null values only
# COUNT(amount) on [100, null, 200] = 2
# AVG: ignores nulls in both numerator and denominator
# AVG([100, null, 200]) = 150 (not 100)
# MIN/MAX: ignores nulls
# MIN([null, 100, 200]) = 100The dangerous case: a pipeline that computes SUM(amount) assumes nulls are missing data and should be excluded. But if amount being null actually means the transaction amount was not recorded — and should be treated as zero for revenue reporting — then SUM silently undercounts revenue.
The fix is to decide the null strategy per column before aggregating:
from pyspark.sql import functions as F
# Explicit null strategy — documented in code
df_clean = df.withColumn(
"amount",
# null amount = failed transaction = zero revenue contribution
F.coalesce(F.col("amount"), F.lit(0.0))
).withColumn(
"merchant_id",
# null merchant = unknown — keep as null, exclude from merchant aggregations
F.col("merchant_id") # explicit no-op: null handling is intentional
)Nulls in GroupBy Keys
This one bites engineers repeatedly. When a groupBy key contains nulls, Spark creates a group for null keys — a bucket that holds all rows where the key is null. This group appears in the output as a row with a null key.
# Example: groupBy on a nullable merchant_id
result = df.groupBy("merchant_id").agg(F.sum("amount"))
# Output includes:
# | merchant_id | sum(amount) |
# | M001 | 15000.0 |
# | M002 | 8200.0 |
# | null | 3400.0 | ← all rows where merchant_id is null
# If you are computing "total revenue per merchant" and summing the result,
# the null group is included in the total.
# Whether that is correct depends on your business definition.
# The point: it is never implicit — you must decide.
# Option 1: exclude null keys before groupBy
df.filter(F.col("merchant_id").isNotNull()) \
.groupBy("merchant_id") \
.agg(F.sum("amount"))
# Option 2: keep and handle explicitly
df.groupBy("merchant_id") \
.agg(F.sum("amount")) \
.filter(F.col("merchant_id").isNotNull()) # remove null group from outputDefensive Null Patterns
# Pattern: null audit before transformation
def audit_nulls(df, columns: list[str], threshold: float = 0.05):
"""Raise if null rate exceeds threshold for any critical column."""
total = df.count()
for col in columns:
null_count = df.filter(F.col(col).isNull()).count()
null_rate = null_count / total
if null_rate > threshold:
raise ValueError(
f"Column '{col}' has {null_rate:.1%} null rate "
f"(threshold: {threshold:.1%}). "
f"Investigate upstream before proceeding."
)
print(f" {col}: {null_rate:.2%} nulls — OK")
# Run before any aggregation on critical columns
audit_nulls(df, columns=["amount", "transaction_id", "merchant_id"])This does a count-based check — not free, but worth it at ingestion time for critical columns. Run it once per pipeline run, not once per transformation.
Pattern 3: Reusable Transformation Functions
The Copy-Paste Problem
A business rule — “active customer is one with a transaction in the last 30 days” — gets implemented in five pipelines by five engineers. Each implementation is slightly different: different date arithmetic, different null handling, different column naming. The customer activity report and the fraud model now disagree on which customers are “active.” Both are wrong in different ways.
This is not a communication failure. It is an architecture failure. Business logic belongs in one place.
A Transformation Library Pattern That Actually Works
The pattern is simple: transformations are functions that take a DataFrame and return a DataFrame. Business rules are expressed as named functions with documented intent.
# transformations/customer.py
from pyspark.sql import DataFrame
from pyspark.sql import functions as F
from datetime import date, timedelta
def flag_active_customers(
df: DataFrame,
transaction_date_col: str = "transaction_date",
lookback_days: int = 30,
output_col: str = "is_active_customer"
) -> DataFrame:
"""
Flag customers with at least one transaction in the last `lookback_days`.
Definition: a transaction_date within [today - lookback_days, today].
Null transaction_date rows are treated as inactive.
Args:
df: DataFrame with customer_id and transaction_date columns
transaction_date_col: name of the date column
lookback_days: lookback window in days (default: 30)
output_col: name of the boolean output column
Returns:
DataFrame with output_col added
"""
cutoff = date.today() - timedelta(days=lookback_days)
return df.withColumn(
output_col,
F.when(
F.col(transaction_date_col).isNotNull() &
(F.col(transaction_date_col) >= F.lit(cutoff)),
True
).otherwise(False)
)
def normalize_amount(
df: DataFrame,
amount_col: str = "amount",
output_col: str = "amount_usd",
exchange_rate_col: str = "exchange_rate"
) -> DataFrame:
"""
Normalize transaction amount to USD using exchange_rate.
Null amounts → 0.0. Null exchange rates → 1.0 (assume USD).
"""
return df.withColumn(
output_col,
F.coalesce(F.col(amount_col), F.lit(0.0)) *
F.coalesce(F.col(exchange_rate_col), F.lit(1.0))
)Using these in a pipeline:
from transformations.customer import flag_active_customers, normalize_amount
result = (
df
.transform(lambda df: flag_active_customers(df, lookback_days=30))
.transform(lambda df: normalize_amount(df))
.groupBy("customer_id", "is_active_customer")
.agg(F.sum("amount_usd").alias("total_spend_usd"))
)The .transform() method is the idiomatic way to chain transformation functions in PySpark. It keeps the pipeline readable and makes each step independently testable.
The functions above are in a shared library. Every pipeline that needs the “active customer” definition imports and calls flag_active_customers. When the definition changes — say, 30 days becomes 60 days — it changes in one place.
Pattern 4: Testing PySpark Locally
The feedback loop for PySpark development without local tests: write code, submit to cluster, wait 15–20 minutes, see the error, fix, repeat. For a transformation bug, that is an hour of debugging what should be a 5-minute fix.
A local SparkSession running in-memory costs about 10 seconds to start and runs transformations on small DataFrames in milliseconds. The transformation logic is the same in both environments — only the data size changes.
Setting Up the Test Environment
# conftest.py — shared test fixtures
import pytest
from pyspark.sql import SparkSession
@pytest.fixture(scope="session")
def spark():
"""
Lightweight local SparkSession for unit testing transformations.
Session scope means it is created once per test run, not once per test.
"""
return (
SparkSession.builder
.master("local[2]") # 2 threads — enough for unit tests
.appName("test-suite")
.config("spark.sql.shuffle.partitions", "2") # avoid 200-partition overhead
.config("spark.ui.enabled", "false") # no UI for test runs
.getOrCreate()
)# tests/test_customer_transforms.py
from transformations.customer import flag_active_customers
from datetime import date, timedelta
import pyspark.sql.functions as F
def test_flag_active_customers_basic(spark):
today = date.today()
recent = today - timedelta(days=10)
old = today - timedelta(days=45)
df = spark.createDataFrame([
("C001", recent),
("C002", old),
("C003", None),
], ["customer_id", "transaction_date"])
result = flag_active_customers(df, lookback_days=30)
rows = {r.customer_id: r.is_active_customer
for r in result.collect()}
assert rows["C001"] is True, "recent customer should be active"
assert rows["C002"] is False, "old customer should be inactive"
assert rows["C003"] is False, "null transaction date should be inactive"What to Test and What Not To
Test the transformation logic — the business rules, the null handling, the edge cases. These are the things that break silently in production and are completely invisible in a cluster run.
Do not test Spark internals — whether partitioning works, whether broadcast joins execute correctly, whether the cluster scales. Spark’s own test suite covers those. Your tests cover your logic.
Testing the Edge Cases That Break Production Jobs
def test_flag_active_customers_all_nulls(spark):
"""All null transaction dates — should not raise, should return all False."""
df = spark.createDataFrame(
[("C001", None), ("C002", None)],
["customer_id", "transaction_date"]
)
result = flag_active_customers(df)
assert result.filter(F.col("is_active_customer") == True).count() == 0
def test_normalize_amount_null_exchange_rate(spark):
"""Null exchange rate should default to 1.0 (assume USD), not propagate null."""
df = spark.createDataFrame(
[(100.0, None), (200.0, 1.5)],
["amount", "exchange_rate"]
)
result = normalize_amount(df).collect()
assert result[0].amount_usd == 100.0, "null rate should default to 1.0"
assert result[1].amount_usd == 300.0, "200 * 1.5 should be 300.0"
def test_normalize_amount_null_amount(spark):
"""Null amount should become 0.0, not null."""
df = spark.createDataFrame(
[(None, 1.5)],
["amount", "exchange_rate"]
)
result = normalize_amount(df).collect()
assert result[0].amount_usd == 0.0These are the tests that catch the bugs that only appear in production — where null rates are higher, where edge cases that never appear in sample data show up at scale.
Pattern 5: Fail Fast, Fail Visibly
A pipeline that crashes on bad data is easier to fix than one that silently produces wrong output. The goal is to make failures loud and early.
Row Count Validation
def assert_row_count(
df,
min_rows: int,
checkpoint_name: str = "checkpoint"
):
"""
Crash the pipeline if row count is below minimum.
Use at key pipeline checkpoints to catch upstream data loss early.
"""
count = df.count()
if count < min_rows:
raise ValueError(
f"{checkpoint_name}: expected at least {min_rows:,} rows, "
f"got {count:,}. Upstream data may be missing or filtered incorrectly."
)
print(f"{checkpoint_name}: {count:,} rows — OK")
return df
# Use at checkpoints
df_ingested = (
spark.read.schema(TRANSACTION_SCHEMA).parquet("s3://bucket/transactions/")
.pipe(assert_row_count, min_rows=1_000_000, checkpoint_name="ingestion")
)
df_clean = (
df_ingested
.filter(F.col("is_refund") == False)
.pipe(assert_row_count, min_rows=800_000, checkpoint_name="after-refund-filter")
)The minimum row count should be calibrated against recent production data — typically 80–90% of the expected minimum. Fixed thresholds work well for stable pipelines but become operational debt for seasonal workloads, post-outage backfills, or pipelines with naturally variable volume. For those cases, comparing against a rolling historical baseline is more reliable than a static number — flag when today’s count is more than 2–3 standard deviations below the 30-day average rather than below an absolute floor.
Schema Assertions After Transformation
def assert_no_nulls(df, columns: list[str], stage: str = ""):
"""Crash if any critical column has nulls after transformation."""
for col in columns:
null_count = df.filter(F.col(col).isNull()).count()
if null_count > 0:
raise ValueError(
f"{stage}: column '{col}' has {null_count:,} null values. "
f"Expected zero after transformation."
)
return df
# After normalization — amount_usd should never be null
df_normalized = (
df_clean
.transform(lambda df: normalize_amount(df))
.pipe(assert_no_nulls,
columns=["amount_usd", "transaction_id"],
stage="post-normalization")
)The Production Readiness Checklist
Before promoting a PySpark job from dev to production, run through this list. Every unchecked item is a potential silent failure waiting to surface.
Schema and ingestion
□ Schema is defined explicitly — no inferSchema in production code
□ FAILFAST or DLQ strategy is chosen and documented
□ Unexpected columns produce a warning, not silent acceptance
Null handling
□ Null strategy is defined for every column used in aggregations
□ GroupBy keys are either validated non-null or null groups are handled explicitly
□ Critical columns are audited for null rate at ingestion
Transformation quality
□ Business logic lives in shared functions, not copy-pasted across pipelines
□ Each transformation function has documented null handling and edge case behavior
□ Column references use names, not positional index
Testing
□ Each transformation function has a local unit test
□ Edge cases tested: all nulls, empty DataFrame, boundary date values
□ Tests run in under 60 seconds on a local machine
Operational correctness
□ Row count validation at ingestion and at major filter checkpoints
□ Critical output columns asserted non-null after transformation
□ Schema of output validated before writing to the sink
Documentation
□ Null strategy for critical columns is documented in code comments
□ Business rule source is referenced (ticket, spec, or doc link)
□ On-call runbook includes what to check when the job failsA job that passes this checklist fails loudly when something breaks. A job that skips it fails silently when something changes.
Final Takeaway
The patterns above are not optimization techniques. They are correctness techniques. Schema enforcement, null handling, reusable functions, local tests, and visible failures do not make jobs faster — they make jobs stay correct when data changes, when business definitions evolve, and when engineers who didn’t write the original code need to maintain it.
Dev code solves the problem at hand. Production code solves the problem at hand and handles everything that changes around it.
📌 Core Principle
The gap between dev and production is not infrastructure. It is the set of edge cases your sample data never contained. Write for those cases.
Next in Series
Spark Structured Streaming in Production — The Complete Operational Guide
Your batch jobs are solid.
Next: what it takes to keep a streaming job running for days without dying — checkpoint configuration that actually works, the right trigger type for your use case, how to monitor streaming jobs effectively, and how to handle schema evolution when your stream’s schema changes mid-flight.