Watermarking and Late Data
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 12 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Lesson: Mastering Watermarking and Late Data in Streaming Systems
Introduction: The Challenge of Time in Distributed Systems
In the world of batch processing, time is often a luxury. You wait for all the data to arrive, organize it into files, and then process it at your leisure. However, modern businesses operate on real-time data where events happen continuously and need to be analyzed as they occur. This shift toward streaming data introduces a fundamental problem: the "Event Time vs. Processing Time" dilemma. In a distributed environment, data rarely arrives in the order it was generated. Networks lag, mobile devices go offline, and servers experience varying degrees of load, all of which cause events to arrive at your processing engine out of sequence or significantly delayed.
Watermarking is the primary mechanism that allows streaming systems to handle this chaos. It acts as a logical clock that tells your system how long to wait for delayed events before concluding that no further data for a specific time window will arrive. Understanding how to implement watermarking correctly is the difference between a system that provides accurate, reliable insights and one that produces misleading or incomplete results. This lesson explores the mechanics of watermarking, how to configure it effectively, and the strategies for handling late data that inevitably slips through the cracks.
Not read yet
Understanding the Two Times: Event Time vs. Processing Time
Before diving into watermarking, we must clearly distinguish between the two ways we measure time in a streaming pipeline. If you confuse these, your entire analytical model will fail.
Processing Time
Processing time is the time at which an event is actually received and processed by your streaming application. It is simple to implement because it relies on the local system clock of the machine executing the code. However, it is inherently unreliable for analytical accuracy. If a network outage occurs and data is buffered for an hour, the "processing time" will suggest the events happened during the outage, rather than when they were actually generated.
Event Time
Event time is the time at which an event actually occurred at the source (e.g., when a user clicked a button on a website or a sensor recorded a temperature reading). This is the "truth" of your data. While event time is much more accurate for business reporting, it is significantly harder to track because events can arrive in the system in an arbitrary order.
Callout: The "Clock" Distinction Think of Processing Time as the clock on your wall at the office—it tells you when you are doing the work. Think of Event Time as the timestamp on a letter sent through the mail—it tells you when the message was actually written. If you want to know when a conversation occurred, you must look at the letter's date, not the date you opened the envelope.
Not read yet
What is Watermarking?
Watermarking is a threshold mechanism used by streaming engines to track the progress of event time. Essentially, a watermark is a declaration by the system that says: "We believe we have received all events with an event time up to X."
When you define a watermark, you are setting a "slack" period. If you set a watermark of 10 seconds, you are telling the engine: "I am willing to wait 10 seconds for late data to arrive." If the current maximum event time seen by the system is 12:00:20, and the watermark delay is 10 seconds, the watermark is 12:00:10. Any event that arrives with a timestamp older than 12:00:10 will be considered "late" and potentially dropped or sent to a side output, depending on your configuration.
How Watermarking Flows
- Source Tracking: As events flow into the streaming engine, the system tracks the maximum event time observed so far.
- Threshold Calculation: The engine subtracts the configured watermark delay from the maximum event time.
- Window Closing: As the watermark advances, the engine identifies which time windows are now "complete" and triggers the final computation for those windows.
- State Cleanup: Once a window is complete and the watermark has passed its end time, the system can safely discard the state associated with that window to free up memory.
Not read yet
Implementing Watermarking: Practical Examples
Most modern streaming frameworks, such as Apache Spark Structured Streaming or Apache Flink, handle watermarking through declarative APIs. Let’s look at how this works in practice using a common scenario: counting user clicks per minute.
Example: Spark Structured Streaming
In Spark, watermarking is defined using the withWatermark method. This method must be called on a DataFrame before any windowed aggregation.
# Assuming 'events' is your streaming DataFrame
# We define a watermark of 10 minutes on the 'timestamp' column
windowed_counts = events \
.withWatermark("timestamp", "10 minutes") \
.groupBy(
window(col("timestamp"), "1 minute"),
col("user_id")
) \
.count()
In this example, the system tracks the maximum timestamp seen in the stream. If we see an event at 12:10:00, the watermark becomes 12:00:00. If an event arrives at 11:59:59 after the watermark has moved to 12:00:00, it is considered late and will be ignored by the aggregation.
Why the 10-minute delay?
The choice of "10 minutes" is a business decision. If your network is generally stable, a short watermark (e.g., 5-30 seconds) is preferred to keep latency low. If you are dealing with mobile devices that have intermittent connectivity, you might need a much longer watermark (e.g., 1 hour) to ensure that the data eventually makes it into the window.
Tip: Balancing Latency and Accuracy Always remember that the watermark delay is a direct trade-off between latency and accuracy. A larger watermark delay gives you more accuracy for late-arriving data but forces your downstream systems to wait longer for the results of a window to be finalized.
Not read yet
Handling Late Data
Even with a well-tuned watermark, data will sometimes arrive after the watermark has passed. This is known as "late data." You have three primary strategies for handling this:
1. Dropping Late Data
This is the default behavior in many systems. If the data is too old, it is simply discarded. This is appropriate for use cases where absolute precision is less important than speed, such as real-time dashboards or trending topics, where one or two missing clicks will not change the overall conclusion.
2. Updating Previous Results
Some systems allow you to emit "updates" to a window after it has been closed. If you are writing to a database that supports upserts (like an RDBMS or a NoSQL store), you can update the record for that specific window time. This ensures accuracy but increases the load on your storage layer.
3. Side Outputs (Dead Letter Queues)
This is the industry-standard approach for mission-critical data. Instead of dropping the late data, you route it to a secondary storage system (like a file in S3 or a separate Kafka topic) for offline processing. This allows you to perform a "re-run" or a "correction" job later to account for the missing data without slowing down your real-time pipeline.
Not read yet
Comparison of Late Data Strategies
| Strategy | Complexity | Accuracy | Cost/Load | Best Use Case |
|---|---|---|---|---|
| Drop | Low | Low | Low | Real-time monitoring, dashboards |
| Update | Medium | High | High | Financial reporting, billing |
| Side Output | High | High | Medium | Data auditing, compliance, debugging |
Best Practices and Common Pitfalls
Pitfall 1: Clock Skew at the Source
A common mistake is assuming that all event sources are perfectly synchronized. If you have 100 sensors and one has a clock that is 5 minutes ahead of the others, that sensor will effectively "advance" the watermark for the entire system, causing data from the other 99 sensors to be incorrectly classified as late. Always normalize event times at the ingestion layer if you cannot guarantee synchronized clocks at the source.
Pitfall 2: The "Watermark Stalling" Problem
If a partition in your stream stops receiving data entirely, the watermark for that partition may stall. In many frameworks, the watermark is the minimum of all partition watermarks. If one partition stops sending data, the entire global watermark stops advancing, which prevents windows from closing and causes memory usage to balloon as state is never cleaned up.
Warning: The Stalling Trap Monitor your watermark progress constantly. If you see your "watermark lag" increasing over time, it is a clear indicator that one of your input partitions is not receiving data, and your system is holding onto state indefinitely.
Best Practice: Use "Allowed Lateness"
In addition to the watermark, some systems (like Google Cloud Dataflow/Apache Beam) provide an "allowed lateness" parameter. This allows you to define a window for late data that is distinct from the watermark. The watermark triggers the initial computation, while the allowed lateness keeps the window open in state so that late arrivals can update the result.
Best Practice: Data Quality Monitoring
You should always log the number of late events that are dropped or sent to side outputs. This metric is a key health indicator for your entire data pipeline. If you see a sudden spike in late data, it usually indicates a network issue, a source failure, or a configuration drift in your watermark settings.
Not read yet
Step-by-Step Configuration Guide
To configure watermarking effectively in a production environment, follow these steps:
- Analyze your Data Latency: Before setting a watermark, look at your historical data. Measure the distribution of the delay between
event_timeandprocessing_time. Aim to set your watermark at the 95th or 99th percentile of that delay. - Define the Window Size: Ensure your window size is significantly larger than your watermark delay. If you have a 10-minute window and a 10-minute watermark, you are essentially asking for trouble, as the window will close almost immediately after the watermark passes.
- Set the Watermark: In your code, apply the
withWatermarktransformation as early as possible in the stream, ideally right after the source ingestion. - Choose an Output Mode: If you are using Spark, decide between
Append,Update, orCompletemode.Appendis best for sinks where you only want finalized results.Updateis better if you need to see changes as they happen. - Monitor State Size: Use your streaming engine's metrics dashboard to track the "state store" size. If it is growing linearly without bound, your watermark is not effectively cleaning up old windows.
Not read yet
Advanced Concept: Multi-Source Watermarking
In complex pipelines, you often join data from multiple sources. For example, you might join a stream of "User Clicks" with a stream of "Ad Impressions." Both streams might have different latency profiles and different watermarks.
When joining these streams, the streaming engine must align the watermarks. The general rule is that the join operator will use the minimum of the watermarks from the two input streams. This ensures that the system waits for the "slowest" stream before finalizing the join.
Code Example: Joining Streams
# Stream A: Clicks
clicks_with_watermark = clicks.withWatermark("timestamp", "5 minutes")
# Stream B: Impressions
impressions_with_watermark = impressions.withWatermark("timestamp", "2 minutes")
# Join the streams
# The system will wait for both to progress before emitting results
joined_stream = clicks_with_watermark.join(
impressions_with_watermark,
expr("click_time = impression_time AND user_id = user_id"),
"inner"
)
This alignment is crucial. If you join a stream with a 1-hour watermark to a stream with a 1-second watermark, the join will be forced to wait for the 1-hour watermark, significantly increasing the latency of the entire joined result.
Not read yet
Troubleshooting Common Issues
Issue: "My results are missing data!"
If you are seeing missing data, check your watermark delay. It is likely too aggressive. If your data takes 30 seconds to arrive on average, but you have a 10-second watermark, you are dropping 20 seconds worth of data. Increase the watermark delay and observe if the missing data reappears.
Issue: "My application is running out of memory!"
This is almost always related to state management. If your watermark is not advancing, the engine keeps every window in memory, waiting for the "late" data that never comes. Check your source partitions. Are they all active? Is there an idle partition? If you have idle partitions, consider repartitioning your data or using a "Watermark Policy" that ignores idle partitions.
Issue: "My real-time dashboard is too slow!"
If the dashboard is slow, your watermark might be too generous. If you have a 1-hour watermark, the dashboard will only show results for events that happened an hour ago. Reduce the watermark delay to the minimum possible value that still captures the majority of your late data.
Not read yet
Comparison: Watermarking vs. Batch Processing
It is helpful to understand how watermarking conceptually replaces the need for batch re-processing.
| Feature | Batch Processing | Streaming with Watermarking |
|---|---|---|
| Data Arrival | Must wait for all data | Processes as data arrives |
| Completeness | Guaranteed (eventually) | Probabilistic (based on watermark) |
| Latency | High (hours/days) | Low (seconds/minutes) |
| Complexity | Simple | High (requires state management) |
| Late Data | Handled by re-running the job | Handled by watermarking/side outputs |
Designing for Resilience: The "Lambda" Approach
While modern streaming systems are powerful, some engineers prefer a "Lambda Architecture" to ensure absolute correctness. In this pattern, you run two pipelines:
- The Speed Layer: A streaming pipeline with a short watermark for real-time, approximate results.
- The Batch Layer: A daily or hourly batch job that re-processes the raw data to produce the "final, correct" version of the data.
This approach acknowledges that watermarking is an approximation. By using this dual-layer strategy, you get the benefit of real-time insights for decision-making while maintaining the integrity of your historical records for reporting and compliance.
Not read yet
Implementing Side Outputs in Practice
If you are using a framework like Apache Beam, side outputs are a first-class citizen. Here is a conceptual look at how you might route late data to a "dead letter" storage:
# Conceptual Beam Side Output
class LateDataFilter(beam.DoFn):
def process(self, element, window=beam.DoFn.WindowParam):
# If the element timestamp is before the watermark, tag it as 'late'
if element.timestamp < current_watermark:
yield pvalue.TaggedOutput('late_data', element)
else:
yield element
# In your pipeline:
results = input_stream | beam.ParDo(LateDataFilter()).with_outputs('late_data', main='results')
# Write the late data to a separate storage
results.late_data | "WriteLateData" >> beam.io.WriteToText("gs://my-bucket/late-data")
This pattern is highly recommended for any production system where data loss is not an option. It shifts the problem from "how to avoid losing data" to "how to process the data we caught."
Not read yet
Summary of Key Takeaways
- Time is Relative: Always distinguish between Event Time (when it happened) and Processing Time (when your system saw it). Analytics should almost always be performed on Event Time.
- Watermarks are Clocks: A watermark is a logical clock that defines how long a system waits for late data. It is a fundamental trade-off between latency and data completeness.
- State Cleanup: Proper watermarking is the only way to effectively clean up state in a streaming system. Without it, your memory usage will grow until the application crashes.
- Choose Your Late Data Strategy: Decide early on whether you will drop, update, or divert late data. Each choice has significant implications for system load and analytical accuracy.
- Monitor Your Lag: Always track the "watermark lag." If it grows, it is a sign that your source data is not arriving as expected, which will lead to either inaccurate data or memory exhaustion.
- Beware of Idle Sources: A single idle partition in a distributed stream can freeze the global watermark. Use modern streaming features like "idle source detection" to prevent this.
- The Hybrid Reality: For mission-critical systems, don't rely solely on streaming for historical accuracy. Use a side output for late data or a batch reconciliation process to ensure your final numbers are 100% correct.
By mastering these concepts, you move beyond simply "moving data" and start building reliable, accurate, and scalable streaming systems that can handle the unpredictable nature of real-world event streams. Take the time to experiment with your watermark settings in a staging environment—there is no "magic number" that works for every use case. Your data, your network, and your business requirements will ultimately dictate the configuration that works best for you.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- VNet Injection and Private Link
- VNet Injection and Private Link Quiz5q
- Access Control and Authentication
- Access Control and Authentication Quiz5q
- Secret Management with Azure Key Vault
- Secret Management with Azure Key Vault Quiz5q
- Workspace Administration Best Practices
- Workspace Administration Best Practices Quiz5q
- Exam Domain Review
- Exam Domain Review Quiz5q
- Azure Databricks Best Practices
- Best Practices Quiz5q
- Troubleshooting Databricks Issues
- Troubleshooting Quiz5q
- Cost Optimization Strategies
- Cost Optimization Quiz5q
- DP-750 Practice Exam
- DP-750 Practice Exam Quiz5q
- Databricks SQL Warehouses
- SQL Warehouses Quiz5q
- Lakehouse Architecture Concepts
- Lakehouse Architecture Quiz5q
- Final Comprehensive Review
- Final Comprehensive Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock DP-750 exam-style practice questions.
Practice for DP-750