Bird
Raised Fist0
Apache Sparkdata~20 mins

Watermarking for late data in Apache Spark - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Watermarking Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Watermarking with Late Data
Given the following Spark Structured Streaming code snippet, what will be the output count of events after applying watermarking and window aggregation?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import window

spark = SparkSession.builder.appName('WatermarkExample').getOrCreate()

# Sample streaming data simulating event time and value
input_data = [
    ("2024-01-01 10:00:00", 1),
    ("2024-01-01 10:01:00", 2),
    ("2024-01-01 10:05:00", 3),  # Late event
    ("2024-01-01 10:02:00", 4)
]

schema = "event_time STRING, value INT"

# Create DataFrame
streaming_df = spark.createDataFrame(input_data, schema=schema)

# Convert event_time to timestamp
from pyspark.sql.functions import col, to_timestamp
streaming_df = streaming_df.withColumn('event_time', to_timestamp(col('event_time')))

# Apply watermark and window aggregation
result_df = streaming_df.withWatermark('event_time', '2 minutes') \
    .groupBy(window(col('event_time'), '5 minutes')) \
    .count()

result_df.show(truncate=False)
A[{window: [2024-01-01 10:00:00, 10:05:00), count: 4}]
B[]
C[{window: [2024-01-01 10:00:00, 10:05:00), count: 2}]
D[{window: [2024-01-01 10:00:00, 10:05:00), count: 3}]
Attempts:
2 left
💡 Hint
Remember that watermark drops events later than 2 minutes behind the max event time seen so far.
🧠 Conceptual
intermediate
1:30remaining
Understanding Watermarking Purpose
What is the main purpose of watermarking in Apache Spark Structured Streaming?
ATo increase the window size for aggregations automatically
BTo speed up batch processing by caching data in memory
CTo limit the amount of state data by dropping late events beyond a threshold
DTo guarantee exactly-once processing of all events
Attempts:
2 left
💡 Hint
Think about how Spark handles late data and state management.
🔧 Debug
advanced
1:30remaining
Identify the Error in Watermark Usage
What error will this Spark code produce?
Apache Spark
df.withWatermark('event_time', '5 minutes')\
  .groupBy('event_time')\
  .count()
AAnalysisException: Watermark can only be applied on event time columns used in window aggregation
BRuntimeException: groupBy requires a window function when watermark is used
CTypeError: withWatermark expects a timestamp column but got string
DNo error, code runs successfully
Attempts:
2 left
💡 Hint
Watermarking requires window aggregation to work properly.
❓ data_output
advanced
2:00remaining
Resulting Rows After Watermark and Window
Given this streaming data and watermark, how many rows will the aggregation output produce?
Apache Spark
input_data = [
    ("2024-06-01 12:00:00", 10),
    ("2024-06-01 12:01:00", 20),
    ("2024-06-01 12:06:00", 30),  # Late event
    ("2024-06-01 12:02:00", 40),
    ("2024-06-01 12:07:00", 50)   # Late event
]

# Watermark set to 3 minutes
# Window duration 5 minutes

# Events beyond watermark threshold are dropped

# How many window groups will be output?
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Consider which events fall into which 5-minute windows and which are dropped by watermark.
🚀 Application
expert
2:30remaining
Choosing Watermark Duration for Real-Time Analytics
You are designing a real-time dashboard that shows user activity aggregated in 1-minute windows. Users can have network delays causing events to arrive up to 10 minutes late. Which watermark duration is best to balance accuracy and resource use?
ASet watermark to 10 minutes to include all late events
BSet watermark to 5 minutes to balance late data and resource constraints
CSet watermark to 1 minute to minimize latency and resource use
DDo not use watermark to ensure no data is dropped
Attempts:
2 left
💡 Hint
Think about trade-offs between waiting for late data and keeping system responsive.

Practice

(1/5)
1. What is the main purpose of watermarking in Apache Spark streaming?
easy
A. To handle late data by setting a threshold time for event processing
B. To speed up the streaming job by skipping data
C. To permanently store all incoming data
D. To convert batch data into streaming data

Solution

  1. Step 1: Understand watermarking concept

    Watermarking sets a time limit to wait for late data in streaming.
  2. Step 2: Identify purpose in streaming

    It helps to ignore data that arrives too late to keep results timely.
  3. Final Answer:

    To handle late data by setting a threshold time for event processing -> Option A
  4. Quick Check:

    Watermarking = handle late data [OK]
Hint: Watermarking sets max wait time for late events [OK]
Common Mistakes:
  • Thinking watermark speeds up jobs by skipping all data
  • Confusing watermark with data storage
  • Assuming watermark converts batch to streaming
2. Which of the following is the correct syntax to add a watermark on a streaming DataFrame df with event time column eventTime and delay threshold of 10 minutes?
easy
A. df.withWatermark(eventTime, 10)
B. df.withWatermark("eventTime", "10 minutes")
C. df.watermark("eventTime", 10)
D. df.withWatermark("eventTime", 10)

Solution

  1. Step 1: Recall correct method signature

    The method is withWatermark with two string arguments: column name and delay duration.
  2. Step 2: Match correct syntax

    df.withWatermark("eventTime", "10 minutes") uses correct method and string format for delay "10 minutes".
  3. Final Answer:

    df.withWatermark("eventTime", "10 minutes") -> Option B
  4. Quick Check:

    Correct syntax uses strings for both args [OK]
Hint: Use strings for column and delay in withWatermark() [OK]
Common Mistakes:
  • Passing column name without quotes
  • Using integer instead of string for delay
  • Using wrong method name like watermark()
3. Given the following Spark Structured Streaming code snippet, what will be the output schema's watermark column after applying watermark?
val streamingDF = spark.readStream.format("csv")
  .option("header", "true")
  .load("/data/events")

val withWatermarkDF = streamingDF.withWatermark("eventTime", "5 minutes")
withWatermarkDF.printSchema()
medium
A. eventTime: timestamp (nullable = true) with watermark
B. eventTime: string (nullable = true) with watermark
C. eventTime: timestamp (nullable = false) without watermark
D. No watermark added to schema

Solution

  1. Step 1: Understand watermark effect on schema

    Watermark adds metadata to the event time column, which must be timestamp type.
  2. Step 2: Check expected schema output

    Schema shows eventTime as timestamp with watermark metadata.
  3. Final Answer:

    eventTime: timestamp (nullable = true) with watermark -> Option A
  4. Quick Check:

    Watermark adds metadata to timestamp column [OK]
Hint: Watermark adds metadata to timestamp event column [OK]
Common Mistakes:
  • Assuming eventTime remains string type
  • Thinking watermark changes nullability
  • Believing watermark does not affect schema
4. Identify the error in the following Spark Structured Streaming code that uses watermarking:
val df = spark.readStream.format("json")
  .load("/stream/data")

val result = df.withWatermark("timestamp", "1 minute")
  .groupBy(window(col("timestamp"), "30 seconds"))
  .count()
medium
A. withWatermark must be called after groupBy
B. Column name "timestamp" should be "eventTime"
C. Window duration cannot be "30 seconds"
D. Watermark delay must be shorter than window duration

Solution

  1. Step 1: Check watermark and window durations

    Watermark delay must be shorter than window duration to ensure the query emits results.
  2. Step 2: Compare durations in code

    Watermark is 1 minute but window is 30 seconds, watermark delay longer than window duration and causes error.
  3. Final Answer:

    Watermark delay must be shorter than window duration -> Option D
  4. Quick Check:

    Watermark < window duration [OK]
Hint: Watermark delay must be < window duration [OK]
Common Mistakes:
  • Assuming any column name works
  • Thinking window duration cannot be "30 seconds"
  • Calling withWatermark after groupBy
5. You have a streaming dataset with event times and want to aggregate counts per 10-minute window. Late data can arrive up to 15 minutes late. Which watermark delay should you set to ensure correct results without excessive delay?
hard
A. "25 minutes"
B. "10 minutes"
C. "15 minutes"
D. "5 minutes"

Solution

  1. Step 1: Understand watermark delay role

    Watermark delay should cover the maximum expected lateness of data to include late events.
  2. Step 2: Match delay to late data arrival

    Since late data can arrive up to 15 minutes late, watermark delay must be at least 15 minutes.
  3. Step 3: Avoid setting delay too short or too long

    Setting delay less than 15 minutes risks dropping late data; too long delays output.
  4. Final Answer:

    "15 minutes" -> Option C
  5. Quick Check:

    Watermark delay = max late arrival [OK]
Hint: Set watermark delay to max expected late arrival [OK]
Common Mistakes:
  • Setting delay equal to window size instead of late arrival
  • Using shorter delay than late data time
  • Using unnecessarily long delay causing latency
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard