VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Spark & PySpark

Handling Late Data & Watermarking in Spark Streaming

💡 Because not all data arrives on time — and Spark knows how to deal with it.

Spark & PySparkKafka & Streaming
TL;DR: Learn how Spark Structured Streaming uses event-time windows and watermarks to gracefully handle late-arriving data — without breaking your pipelines.

🚀 Introduction

In the real world, data rarely behaves perfectly.
Network latency, retries, or device disconnections can cause events to arrive late — sometimes seconds or even minutes after their actual timestamp.

Without proper handling, these late events can skew aggregations, duplicate metrics, or even corrupt dashboards.

That’s where Watermarking comes in — one of the most powerful (and underrated) features of Spark Structured Streaming.

In this post, we’ll explore:

  • What late data means in streaming
  • How Spark handles it using event-time windows and watermarks
  • Real working code to see it in action
  • A real-world case study showing how watermarking saves production pipelines

By the end, you’ll understand how to build robust, time-aware streaming pipelines that handle data like a pro.


⏱️ 1. Understanding Late Data

Imagine you’re processing real-time transaction data from multiple stores across cities.

Each transaction event includes:

  • Store name
  • Amount
  • Timestamp

If a few transactions get delayed (say, due to poor network in one branch), Spark may receive them after the time window they belong to has already been processed.

Without special handling, these events are ignored or miscounted — hurting your downstream accuracy.

That’s why event-time and watermarks exist:

  • Event time: when the data was generated
  • Processing time: when Spark receives it

The difference between the two defines how late the data is.


💾 2. Creating a Sample Dataset

Let’s simulate a small dataset representing streaming transactions from different cities, with timestamps (and a few intentionally late ones).

from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StringType, TimestampType, IntegerType
from pyspark.sql.functions import expr
from datetime import datetime, timedelta

spark = SparkSession.builder.appName("LateDataWatermarking").getOrCreate()

# Create schema
schema = StructType() \
.add("city", StringType()) \
.add("amount", IntegerType()) \
.add("timestamp", TimestampType())

# Create sample streaming-like data
data = [
("Bangalore", 200, datetime.now()),
("Delhi", 150, datetime.now() - timedelta(seconds=5)),
("Bangalore", 300, datetime.now() - timedelta(seconds=10)), # slightly late
("Delhi", 120, datetime.now() - timedelta(seconds=20)), # late event
("Bangalore", 180, datetime.now() - timedelta(seconds=25)) # very late
]

df = spark.createDataFrame(data, schema)
df.show(truncate=False)

📊 Output Example:


⚡ 3. Simulating a Streaming Source

We’ll now simulate this as if it’s coming from a streaming input directory, where new files arrive periodically.

import os
import time

stream_dir = "/tmp/stream_data"
os.makedirs(stream_dir, exist_ok=True)

# Save static DataFrame as if it’s incoming streaming data
df.write.mode("overwrite").json(f"{stream_dir}/batch1")

# Wait and simulate late data arrival
time.sleep(5)
late_data = [( "Delhi", 100, datetime.now() - timedelta(seconds=30) )]
spark.createDataFrame(late_data, schema).write.mode("append").json(f"{stream_dir}/batch2")

Here we wrote two micro-batches — the second one simulates late data.


🧠 4. Defining a Streaming Query with Watermarking

Now let’s read the same directory as a streaming source and apply a watermark.

from pyspark.sql.functions import window

stream_df = (
spark.readStream
.schema(schema)
.option("maxFilesPerTrigger", 1)
.json(stream_dir)
)

# Apply watermark and windowed aggregation
aggregated = (
stream_df
.withWatermark("timestamp", "15 seconds")
.groupBy(
window("timestamp", "10 seconds", "5 seconds"),
"city"
)
.sum("amount")
)

query = (
aggregated.writeStream
.outputMode("update")
.format("console")
.option("truncate", "false")
.start()
)

In this example:

  • We apply a watermark of 15 seconds, meaning Spark will wait for up to 15 seconds for late events before finalizing that window.
  • Any data older than that watermark will be ignored for aggregation.

🧩 5. What Happens Internally

When Spark applies a watermark:

  1. It tracks the maximum event time seen so far.
  2. It discards any data with a timestamp older than (max event time — watermark interval).
  3. It only updates the results for open windows (not finalized ones).

In our example:
If Spark has seen events up to 23:45:00 and watermark = 15s,
then anything older than 23:44:45 is considered too late.


🧮 6. Example Output (Console Sink)

Expected console output for the above code might look like:

+------------------------------------------+----------+-----------+
|window |city |sum(amount)|
+------------------------------------------+----------+-----------+
|{2025-11-08 23:44:50, 2025-11-08 23:45:00}|Bangalore |500 |
|{2025-11-08 23:44:45, 2025-11-08 23:44:55}|Delhi |150 |
+------------------------------------------+----------+-----------+

Notice how the “very late” Bangalore and Delhi records (older than watermark threshold) were dropped.


🧱 7. Why Watermarking Matters

Without watermarks, Spark keeps all windows open forever, waiting for possible late data.
This causes:

  • Memory leaks
  • Slower state updates
  • High CPU load

Watermarking solves this by allowing Spark to:
✅ Retain accuracy for “slightly late” data
✅ Automatically discard “too old” events
✅ Control state size and memory usage


📊 8. Common Time-Based Transformations

Here are some essential time-based transformations used alongside watermarks to handle event-time aggregations efficiently.

📊 Table 1 : Key time-based transformations used in Spark Structured Streaming — combining event-time windows, watermarks, and deduplication to handle late-arriving data efficiently.

🌍 9. Real-World Example: IoT Sensor Streams

A smart factory processes thousands of IoT sensor readings per minute.
Occasionally, some sensors send updates several seconds late due to connectivity drops.

Using watermarking:

  • Spark waits 20 seconds for late arrivals
  • Aggregates data per machine every minute
  • Writes the results to Delta Lake for dashboards

💡 Result: Real-time metrics remain accurate, while memory use dropped by 40%.

Without watermarking, this pipeline would’ve over-counted and overloaded the cluster.


🧭 10. Best Practices for Late Data Handling

Before wrapping up, here’s a quick reference guide that summarizes how Spark handles different late-data scenarios — and what you, as a data engineer, should do in each case.

📊 Table 2 : Best practices for managing late-arriving data in Spark Structured Streaming — from watermark tuning to event-time alignment.

⚙️ 11. Where to Run This

⚙️ Note:
This example is meant for
Databricks or a local Spark setup with streaming sources (like file or Kafka).
Google Colab cannot maintain persistent streaming sessions or simulate continuous event ingestion.

🧩 12. Real-World Impact: Robust Real-Time Pipelines

Companies using watermarking in Spark Streaming often report:

  • 2–3× reduction in job memory usage
  • Significantly lower latency during high-traffic spikes
  • Higher accuracy for windowed metrics like “transactions per minute”

In short — watermarking isn’t just about performance. It’s about trust in your real-time data.


🔧 Debugging These Failures in Practice

If you’re hitting errors like these in production — Airflow failures, Spark OOM,Kafka SSL issues — I built a tool to help.

Paste your broken code + error logs into Vayu and get back:

→ Exact root cause

→ Before/After code fix

→ Confidence score (HIGH/MEDIUM/LOW)

Free to try at vayufix.com

No signup needed for first 3 fixes.


🧾 Conclusion

Late data is inevitable — whether it’s IoT devices, mobile apps, or financial systems.
But with event-time processing and watermarking, Spark helps you ensure your analytics stay accurate, consistent, and efficient.

So next time your dashboards seem off by a few seconds, remember:
Spark isn’t behind — it’s just waiting for stragglers. ⚡


🔜 Next in Series

Coming Up Next:
👉 “Checkpointing & Fault Tolerance in Streaming Applications”
We’ll explore how Spark ensures reliability through checkpointing, recovery, and exactly-once guarantees — even if your cluster crashes mid-stream.


🔔 Follow for More

If you found this helpful, follow TheDataForge for your daily Spark in Data Engineering & Machine Learning ⚡

Let’s connect — I post daily Big Data & Spark insights at DataForgeX on X.
💬 Comment below — what’s the biggest challenge you’ve faced with late-arriving data?


🏷️ Tags

#ApacheSpark #PySpark #BigData #DataEngineering #DataForge #SparkOptimization #LazyEvaluation #DAG #RealTimeData #StructuredStreaming