A Spark Structured Streaming job grows state until OOM and writes repeated window rows — find the causes
The job below (Spark 4.x) counts clicks per page in 5-minute event-time windows and writes them to PostgreSQL. Three symptoms: executor memory and the state store grow every day until the job dies with OOM; dwh.page_clicks_5m holds several rows per (window, page) with rising counts; after a restart some rows appear twice with identical values. Switching to outputMode("append") made the query fail at start. The producer also re-sends some clicks under the same click_id on retries.
Constraints: clicks arrive up to 30 minutes late; each (window, page) must end up as one row with the final count; the job must stay restartable.
from pyspark.sql import functions as F
clicks = (spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", "kafka:9092")
.option("subscribe", "clicks")
.load()
.select(F.from_json(F.col("value").cast("string"), schema).alias("c"))
.select("c.*")) # click_id, page_id, event_ts
per_window = (clicks
.groupBy(F.window("event_ts", "5 minutes"), "page_id")
.count())
def write_batch(df, batch_id):
df.write.mode("append").jdbc(PG_URL, "dwh.page_clicks_5m", properties=PG_PROPS)
(per_window.writeStream
.outputMode("update")
.foreachBatch(write_batch)
.option("checkpointLocation", "s3://chk/page_clicks")
.start())Diagnose every cause and fix the job.
No withWatermark: every window's state is kept forever and append mode is refused; update re-emits changed windows, and appending them adds rows. foreachBatch is at-least-once, the checkpoint never dedupes topic copies — add a watermark, dropDuplicatesWithinWatermark, append mode, an upsert by key.
- Believing append mode silently emits nothing without a watermark, when Spark rejects the query at start
- Expecting the checkpoint to deduplicate records the producer wrote to the topic twice
- Restarting a query with a newly added watermark or dedup on the old checkpoint, which Spark does not allow for changed stateful operators
- Why does complete output mode never drop state, even with a watermark set?
- How would you use
batch_idto make a non-transactional sink safe against a re-run micro-batch?
There are three causes, all visible in the code.
- No
withWatermark. A windowed aggregation without a watermark never knows a window is finished, so it keeps the state of every window since the start — hence the growing state store and the OOM. For the same reason Spark rejects append mode: an aggregate row can still change, and append emits a row only once. With a watermark, append emits a window once the watermark passes its end and drops its state. - Update mode plus appending. Update re-emits, on every micro-batch, each window whose count changed.
mode("append")over JDBC stores those intermediate values side by side — hence several rows per (window, page) with rising counts. foreachBatchis at-least-once. If the write succeeded but Spark died before the batch was recorded in the checkpoint, the samebatch_idruns again after the restart — exact duplicates. Copies the producer wrote to the topic under different offsets are not removed by the checkpoint either: it holds the offsets read and the state, not event ids.
import psycopg
from pyspark.sql import functions as F
per_window = (clicks
.withWatermark("event_ts", "30 minutes") # clicks arrive up to 30 min late
.dropDuplicatesWithinWatermark(["click_id"]) # producer re-sends
.groupBy(F.window("event_ts", "5 minutes"), "page_id")
.count())
UPSERT = """
INSERT INTO dwh.page_clicks_5m (window_start, window_end, page_id, clicks)
VALUES (%s, %s, %s, %s)
ON CONFLICT (window_start, page_id) DO UPDATE SET clicks = EXCLUDED.clicks
"""
def write_batch(df, batch_id):
rows = [(r["window"]["start"], r["window"]["end"], r["page_id"], r["count"])
for r in df.collect()] # append: only closed windows, a few rows
with psycopg.connect(PG_DSN) as conn: # a re-run of the same batch_id rewrites the same rows
conn.cursor().executemany(UPSERT, rows)
(per_window.writeStream
.outputMode("append") # one window, one output with the final count
.foreachBatch(write_batch)
.option("checkpointLocation", "s3://chk/page_clicks_v2") # new checkpoint
.start())The checkpoint is new: adding the watermark and the dedup changes the stateful operators, and restarting a changed stateful query on the old checkpoint is not allowed. The new query reads Kafka from startingOffsets, which defaults to latest for a streaming query and applies only to a fresh checkpoint. So set startingOffsets or startingTimestamp safely before the start of the oldest window that was not yet closed — the needed stretch is re-read, and the upsert on (window_start, page_id) makes the overlap harmless. ON CONFLICT needs a unique key on (window_start, page_id): delete the accumulated duplicates, then add the constraint. The price of append is that a window reaches the table about 30 minutes after its end; if intermediate counts are needed, keep update mode but still write an upsert on the window key.