Challenge - 5 Problems
Incremental Processing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Spark Structured Streaming with Watermark
Consider the following Spark Structured Streaming code snippet that reads a stream of events with timestamps and applies a watermark to handle late data. What will be the output count of events after the watermark is applied and aggregation is done?
Apache Spark
from pyspark.sql import SparkSession from pyspark.sql.functions import window, col spark = SparkSession.builder.appName('WatermarkExample').getOrCreate() # Sample streaming DataFrame simulating event data input_data = [ ("2024-06-01 10:00:00", "event1"), ("2024-06-01 10:01:00", "event2"), ("2024-06-01 09:55:00", "event3"), # Late event ("2024-06-01 10:02:00", "event4") ] schema = "timestamp STRING, event STRING" # Create static DataFrame to simulate streaming input static_df = spark.createDataFrame(input_data, schema=schema) # Convert timestamp string to timestamp type streaming_df = static_df.withColumn('timestamp', col('timestamp').cast('timestamp')) # Apply watermark and group by window agg_df = streaming_df.withWatermark('timestamp', '5 minutes') \ .groupBy(window(col('timestamp'), '10 minutes')) \ .count() result = agg_df.collect() output = [(row['window'].start.strftime('%Y-%m-%d %H:%M:%S'), row['count']) for row in result] print(output)
Attempts:
2 left
💡 Hint
Remember that watermark drops events older than the watermark threshold relative to the max event time seen.
✗ Incorrect
The watermark of 5 minutes means events older than 5 minutes from the max event timestamp are dropped. The event at 09:55:00 is within 5 minutes of the max timestamp 10:02:00, so it is included. The window groups events from 10:00:00 to 10:10:00, so the count is 3 events in that window.
❓ data_output
intermediateResulting DataFrame after Incremental Batch Processing
You have a batch DataFrame with user transactions and a checkpoint storing the last processed transaction ID. You want to process only new transactions with IDs greater than the checkpoint. Given the following code, what will be the resulting DataFrame after filtering?
Apache Spark
from pyspark.sql import SparkSession from pyspark.sql.functions import col spark = SparkSession.builder.appName('IncrementalBatch').getOrCreate() # Sample transactions transactions = [ (1, 'user1', 100), (2, 'user2', 150), (3, 'user3', 200), (4, 'user1', 250) ] schema = 'transaction_id INT, user STRING, amount INT' df = spark.createDataFrame(transactions, schema=schema) last_checkpoint = 2 # Filter new transactions new_transactions = df.filter(col('transaction_id') > last_checkpoint) result = new_transactions.collect() output = [(row['transaction_id'], row['user'], row['amount']) for row in result] print(output)
Attempts:
2 left
💡 Hint
Filter selects transactions with ID strictly greater than the checkpoint.
✗ Incorrect
Filtering with transaction_id > 2 selects transactions with IDs 3 and 4 only.
🔧 Debug
advancedIdentify the Error in Incremental Stream Processing Code
The following Spark Structured Streaming code attempts to read a stream, apply a watermark, and write the output to console. However, it raises an error. What is the cause?
Apache Spark
from pyspark.sql import SparkSession from pyspark.sql.functions import col spark = SparkSession.builder.appName('StreamError').getOrCreate() streaming_df = spark.readStream.format('csv').option('header', 'true').load('/path/to/stream') # Apply watermark on a non-timestamp column agg_df = streaming_df.withWatermark('event_time', '10 minutes').groupBy('user').count() query = agg_df.writeStream.outputMode('append').format('console').start() query.awaitTermination()
Attempts:
2 left
💡 Hint
Check the data type of the column used in withWatermark.
✗ Incorrect
Watermark requires the column to be of timestamp type. If 'event_time' is not timestamp, Spark raises AnalysisException.
❓ visualization
advancedVisualizing Incremental Data Processing with Micro-batches
You run a Spark Structured Streaming job with micro-batch interval of 5 seconds. The job processes data arriving every 3 seconds. Which visualization best represents the processing timeline of micro-batches and data arrival?
Attempts:
2 left
💡 Hint
Micro-batch interval controls how often batches start, independent of data arrival frequency.
✗ Incorrect
Micro-batches start at fixed intervals (5 seconds). Data arriving every 3 seconds accumulates and is processed in these batches, causing some overlap in data arrival times within batches.
🧠 Conceptual
expertChoosing the Best Incremental Processing Pattern for Late Data
You have a streaming data source with frequent late-arriving events. You want to ensure accurate aggregation results while minimizing state size and latency. Which incremental processing pattern is best suited for this scenario?
Attempts:
2 left
💡 Hint
Consider how watermarking helps manage late data and state size.
✗ Incorrect
Watermarking with allowed lateness lets Spark drop very late events and clean up state, balancing accuracy and resource use. Processing-time triggers or no watermarking either ignore late data or cause unbounded state growth.
