Structured Streaming basics in Apache Spark - Time & Space Complexity
We want to understand how the time it takes to process data grows as the amount of streaming data increases.
How does the processing time change when more data arrives in a stream?
Analyze the time complexity of the following Structured Streaming code snippet.
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("streaming_example").getOrCreate()
streamingDF = spark.readStream.format("socket") \
.option("host", "localhost") \
.option("port", 9999) \
.load()
query = streamingDF.writeStream.format("console").start()
query.awaitTermination()
This code reads streaming data from a socket and writes it to the console as it arrives.
- Primary operation: Processing each batch of streaming data as it arrives.
- How many times: Once per micro-batch, repeating continuously as new data comes in.
Each micro-batch processes all new data received since the last batch.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 records | Processes 10 records |
| 100 records | Processes 100 records |
| 1000 records | Processes 1000 records |
Pattern observation: The processing time grows roughly in direct proportion to the number of new records in each batch.
Time Complexity: O(n)
This means the time to process each batch grows linearly with the number of new records in that batch.
[X] Wrong: "The streaming job processes all data from the start every time, so time grows much faster."
[OK] Correct: Structured Streaming processes only new data in each micro-batch, not all past data again, so time grows with new data size, not total data size.
Understanding how streaming data processing time grows helps you design efficient real-time systems and shows you can reason about continuous data flows.
"What if we changed the trigger interval to process smaller batches more often? How would the time complexity per batch change?"
Practice
Solution
Step 1: Understand Structured Streaming concept
Structured Streaming is designed to handle data streams, meaning data that arrives continuously over time.Step 2: Compare with other options
Batch processing handles static data, storing data is not the main function, and visualization is separate from streaming.Final Answer:
To process live data continuously as it arrives -> Option DQuick Check:
Structured Streaming = continuous live data processing [OK]
- Confusing streaming with batch processing
- Thinking streaming stores data permanently
- Assuming streaming is for visualization
Solution
Step 1: Identify streaming read syntax
To read streaming data, usereadStreamwith format and load.Step 2: Eliminate non-streaming options
readis for batch,writeStreamis for output, so onlyreadStreamwithloadis correct.Final Answer:
spark.readStream.format("json").load("path") -> Option BQuick Check:
Streaming read uses readStream [OK]
- Using read instead of readStream for streaming data
- Confusing writeStream with readStream
- Using writeStream with load instead of start
df = spark.readStream.format("csv").option("header", "true").load("/data/clicks")
df.printSchema()Solution
Step 1: Understand schema inference in streaming CSV
When reading CSV with header option true, Spark infers schema as strings by default for streaming.Step 2: Check if explicit schema is required
Explicit schema is recommended but not mandatory; Spark infers schema as string types if not provided.Final Answer:
Schema with columns inferred from CSV header as strings -> Option CQuick Check:
CSV header + streaming = inferred string schema [OK]
- Assuming streaming can't infer schema
- Expecting integer types without schema
- Thinking explicit schema is always required
streamDF = spark.readStream.format("json").load("/data/events")
query = streamDF.writeStream.format("console").start()
query.awaitTermination(10)Solution
Step 1: Check writeStream requirements
In Structured Streaming,writeStreamrequiresoutputMode()(e.g., "append") to be specified beforeformat()for sinks like console.Step 2: Verify other parts
awaitTermination(10)accepts a timeout argument, format 'console' is correct lowercase, andstart()must be called beforeawaitTermination().Final Answer:
Missing option to specify output mode in writeStream -> Option AQuick Check:
writeStream requires outputMode [OK]
- Missing outputMode in writeStream
- Thinking awaitTermination does not take timeout
- Misusing start and awaitTermination order
Solution
Step 1: Understand streaming word count steps
Streaming word count requires reading live data, splitting lines into words, grouping by word, and counting occurrences continuously.Step 2: Check options for correctness
Read stream from socket, split lines into words, group by word, count, write stream to console follows the correct streaming steps with writeStream to console. Read batch from socket, split lines into words, group by word, count, write batch to file uses batch, not streaming. Read stream from socket, count lines directly, write stream to console counts lines, not words. Read stream from socket, split lines into words, filter empty words, write batch to console writes batch, not stream, and misses counting.Final Answer:
Read stream from socket, split lines into words, group by word, count, write stream to console -> Option AQuick Check:
Streaming word count = readStream + split + groupBy + count + writeStream [OK]
- Using batch read instead of streaming
- Counting lines instead of words
- Writing batch output instead of streaming
Ready to prove it?
Pass the test and this pattern moves unknown
