The idea: an unbounded table
๐New files land
orders_2026-10-01.csv, -02.csv, -03.csvโฆ
๐readStream
Same DataFrame API, schema required
๐งฎQuery
filter + groupBy, updated incrementally
๐พSink + checkpoint
Results out; progress remembered
Read a folder as a stream
We simulate a landing folder: two daily files have arrived so far.
from pyspark.sql import SparkSession, functions as F
spark = (SparkSession.builder.appName("shopkart").master("local[*]")
.config("spark.ui.showConsoleProgress", "false").getOrCreate())
spark.sparkContext.setLogLevel("ERROR")
schema = ("order_id INT, customer_id INT, product_id INT, quantity INT, "
"unit_price DECIMAL(10,2), status STRING, order_ts TIMESTAMP")
import os, shutil
shutil.rmtree("out/stream", ignore_errors=True)
os.makedirs("out/stream/incoming")
for day in ["2026-10-01", "2026-10-02"]: # two files have "arrived" so far
shutil.copy(f"data/orders/orders_{day}.csv", "out/stream/incoming/")
stream = (spark.readStream
.option("header", True)
.schema(schema) # streams need a schema up front
.csv("out/stream/incoming/"))
print(stream.isStreaming)TrueRun it, then add a file
daily = (stream.filter(F.col("status") == "DELIVERED")
.groupBy(F.to_date("order_ts").alias("day"))
.agg(F.count("*").alias("orders"), F.sum(F.col("quantity") * F.col("unit_price")).alias("revenue")))
def run_once():
q = (daily.writeStream
.outputMode("complete") # rewrite the whole result each time
.format("memory").queryName("daily_revenue")
.option("checkpointLocation", "out/stream/checkpoint")
.trigger(availableNow=True) # process what's there, then stop
.start())
q.awaitTermination()
print("new rows processed this run:", q.lastProgress["numInputRows"])
spark.sql("SELECT * FROM daily_revenue ORDER BY day").show()
run_once()new rows processed this run: 135
+----------+------+---------+
| day|orders| revenue|
+----------+------+---------+
|2026-10-01| 60|161518.00|
|2026-10-02| 75|150211.00|
+----------+------+---------+trigger(availableNow=True) processed everything available and stopped. The count is rows that passed the DELIVERED filter (Spark applies it while reading). Now the next day's file arrives:
shutil.copy("data/orders/orders_2026-10-03.csv", "out/stream/incoming/") # a new file arrives
run_once()new rows processed this run: 65
+----------+------+---------+
| day|orders| revenue|
+----------+------+---------+
|2026-10-01| 60|161518.00|
|2026-10-02| 75|150211.00|
|2026-10-03| 65|137518.00|
+----------+------+---------+Only the new file was read: 65 new rows, not all three files again. The checkpoint remembered which files were done, and the complete output mode rewrote the full 3-day result.
| Output mode | Writes | Use for |
|---|---|---|
| append | Only new rows | Raw events, or aggregations with a watermark |
| complete | The whole result every trigger | Small aggregations (like ours) |
| update | Only rows that changed | Aggregations into sinks that can update |
foreachBatch: plug in any batch code
def upsert_batch(batch_df, batch_id):
print(f"batch {batch_id}: {batch_df.count()} rows") # here you'd MERGE into a Delta table
q = (stream.writeStream.foreachBatch(upsert_batch)
.option("checkpointLocation", "out/stream/checkpoint_fb")
.trigger(availableNow=True).start())
q.awaitTermination()batch 0: 280 rowsforeachBatch hands you each micro-batch as an ordinary DataFrame, here all 280 rows of the three files in batch 0 (a new checkpoint, so it starts from scratch). Inside you can do anything a batch job does, most commonly a Delta MERGE (lesson 7) to upsert changes into a table.
Triggers and real sources
| Trigger | Behaviour |
|---|---|
| (default) | Start the next micro-batch as soon as the previous one finishes |
| processingTime='1 minute' | A micro-batch every minute |
| availableNow=True | Process all available data, then stop (scheduled incremental jobs) |
Real pipelines read from Kafka, Azure Event Hubs, Kinesis or cloud folders (on Databricks, Auto Loader). For aggregations over event time, add a watermark (withWatermark("ts", "10 minutes")) so Spark knows when a time window is complete and can drop old state.
๐ฏ Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is Structured Streaming?Fresher+
Q2How does Spark achieve exactly-once processing?1โ3 yrs+
Q3What is a watermark?1โ3 yrs+
Q4How would you upsert a stream into a Delta table?3+ yrs+
Key takeaways
- โStreaming in Spark is mostly the batch code you already know.
- โThe checkpoint is what makes 'only new data, exactly once' work.
- โavailableNow turns streaming into efficient scheduled incremental jobs.
- โforeachBatch + MERGE is the standard upsert pattern.
Frequently asked questions
What is Structured Streaming?
Spark's streaming engine: you write the same DataFrame code as for batch, and Spark runs it incrementally as new data arrives, from files, Kafka, Event Hubs and more, keeping track of progress in a checkpoint.
What does the checkpoint store?
Which input has been processed (offsets, or which files were read) and any state such as running aggregations. Restart a query with the same checkpoint and it continues exactly where it stopped. Never share one checkpoint between two queries.
What is trigger(availableNow=True)?
Process everything available now (in one or more batches), then stop. It gives streaming's exactly-once bookkeeping on a schedule, like a batch job that only reads new data. Great for jobs run every hour by a scheduler.
complete, append or update output mode?
append writes only new rows (for non-aggregated streams, or aggregations with watermarks). complete rewrites the whole result table each trigger (aggregations; small results). update writes only rows that changed since the last trigger.
๐ง Quick check: streaming
1. The second run processed how many new rows?
2. Why must a file stream have a schema?
3. foreachBatch is used to...
4. Two streaming queries share one checkpoint folder. Result?
Checking your accessโฆ