The problem from last lesson
Our bronze step loaded orders_{run_date}.json, and we had to pass the right date. What if two files arrive in one day? A file arrives late? Someone re-runs yesterday by mistake and duplicates it? We need the platform to track which files are new. That's exactly what Auto Loader does.
Structured Streaming in one picture
Spark treats a stream as a table that keeps growing. You write normal DataFrame code; Spark runs it again on each new chunk of data (a micro-batch) and appends the result.
πSource
New files (Auto Loader), Kafka, a Delta table
πMicro-batches
Your DataFrame code runs on each chunk of new data
πΎSink
A Delta table (or foreachBatch)
πCheckpoint
Saves progress + state after every batch
Auto Loader into bronze
from pyspark.sql import functions as F
query = (spark.readStream
.format("cloudFiles") # Auto Loader
.option("cloudFiles.format", "json")
.schema(orders_schema) # the columns we expect
.load("/Volumes/shopkart/raw/landing/orders/")
.withColumn("_ingested_at", F.current_timestamp())
.withColumn("_source_file", F.col("_metadata.file_path"))
.writeStream
.option("checkpointLocation", "/Volumes/shopkart/raw/checkpoints/bronze_orders")
.trigger(availableNow=True) # process every new file, then stop
.toTable("shopkart.bronze.orders_stream"))
query.awaitTermination()format("cloudFiles")= Auto Loader.cloudFiles.formatis the file type (json, csv, parquet...).checkpointLocation: where progress is saved. One per stream, never shared.trigger(availableNow=True): process every new file, then stop. Schedule it daily or hourly.toTable(...): write to a Delta table.awaitTermination()waits for it to finish.
Schema inference and evolution
Instead of .schema(...), you can let Auto Loader infer it: set cloudFiles.schemaLocation and it stores the schema there. New columns are handled by cloudFiles.schemaEvolutionMode:
| Mode | When a new column appears |
|---|---|
| addNewColumns (default) | Stream stops once, schema is updated, next run includes the column |
| rescue | Schema never changes; unexpected data goes into the _rescued_data column |
| failOnNewColumns | Stream fails until you update the schema |
| none | New columns are ignored |
_rescued_data catches values that don't fit the schema (wrong type, unexpected column), so nothing is silently lost.
| Option | How Auto Loader finds new files |
|---|---|
| Directory listing (default) | Lists the folder each run. Simple, no setup |
| File notification | Cloud events (e.g. S3 β SQS) tell it about new files. Better for millions of files |
Triggers: how often it runs
| Trigger | Behaviour | Use it for |
|---|---|---|
| (default) | Next micro-batch as soon as the previous finishes | Low-latency, always-on |
| processingTime='5 minutes' | One micro-batch every 5 minutes | Near real-time at lower cost |
| availableNow=True | Everything new, in batches, then stop | Scheduled incremental jobs (most common) |
| Real-time mode (Databricks) | Very low latency for operational streams | Fraud checks, live features |
Upserts from a stream: foreachBatch
A stream can only append to a table by default. To MERGE (update existing orders), use foreachBatch: Spark hands you each micro-batch as a normal DataFrame, and you can do anything with it.
CREATE TABLE IF NOT EXISTS shopkart.silver.orders_stream (
order_id STRING, customer_id STRING, product STRING, quantity INT, price DOUBLE,
status STRING, order_ts TIMESTAMP, updated_at TIMESTAMP,
_ingested_at TIMESTAMP, amount DOUBLE
);from pyspark.sql import Window
from delta.tables import DeltaTable
def upsert_orders(batch_df, batch_id):
"""Runs once per micro-batch: clean the new rows, then MERGE them into silver."""
latest_first = Window.partitionBy("order_id").orderBy(F.desc("updated_at"))
clean = (batch_df
.filter(F.col("customer_id").isNotNull() & (F.col("quantity") > 0))
.withColumn("amount", F.round(F.col("quantity") * F.col("price"), 2))
.withColumn("rn", F.row_number().over(latest_first))
.filter("rn = 1")
.drop("rn", "_source_file"))
(DeltaTable.forName(batch_df.sparkSession, "shopkart.silver.orders_stream").alias("t")
.merge(clean.alias("s"), "t.order_id = s.order_id")
.whenMatchedUpdateAll(condition="s.updated_at > t.updated_at")
.whenNotMatchedInsertAll()
.execute())
(spark.readStream.table("shopkart.bronze.orders_stream")
.writeStream
.foreachBatch(upsert_orders)
.option("checkpointLocation", "/Volumes/shopkart/raw/checkpoints/silver_orders")
.trigger(availableNow=True)
.start()
.awaitTermination())Result we checked: 7 unique valid orders in silver (O1009 from day 3 included), with O1003 correctly DELIVERED. Note the de-duplication inside the batch: one micro-batch can contain two versions of the same order.
Exactly-once and checkpoints
If the cluster dies mid-batch, the restarted stream reads the checkpoint, sees that batch wasn't committed, and redoes it. Delta sinks commit atomically, so the redo doesn't create duplicates. With foreachBatch, exactly-once depends on your code being idempotent, and a MERGE on a key is.
Watermarks: limiting memory in stateful streams
De-duplication and windowed aggregations need state: Spark must remember what it saw. Without limits, state grows forever. A watermark says: βdata later than X is too late; forget state older than thatβ.
# Streaming de-duplication: remember order_ids for 1 day, then forget them (keeps state small).
deduped = (spark.readStream.table("shopkart.bronze.orders_stream")
.withWatermark("updated_at", "1 day")
.dropDuplicates(["order_id", "updated_at"]))COPY INTO: the SQL alternative
COPY INTO shopkart.bronze.orders_copy
FROM '/Volumes/shopkart/raw/landing/orders/'
FILEFORMAT = JSON
COPY_OPTIONS ('mergeSchema' = 'true'); -- re-running skips files already loadedπ― Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What is Auto Loader and why use it?Fresher+
Q2What is the purpose of a checkpoint in Structured Streaming?1β3 yrs+
Q3How do you run streaming code as a daily batch job?1β3 yrs+
Q4How do you upsert streaming data into a Delta table?1β3 yrs+
Q5Explain watermarking.3+ yrs+
Q6A new column appears in the source files and the Auto Loader stream fails. What happened and what do you do?3+ yrs+
Key takeaways
- βAuto Loader solves 'which files are new?' so bronze never loads a file twice.
- βStreaming code with availableNow is the standard way to build incremental pipelines.
- βforeachBatch + MERGE brings upserts to streams.
- βCheckpoints and watermarks keep streams correct and memory bounded.
Frequently asked questions
What is Auto Loader?
Auto Loader is Databricks' way to load files incrementally: point it at a folder and it processes only files it hasn't seen before, remembering them in a checkpoint. It's used with spark.readStream.format("cloudFiles").
Is streaming only for real-time data?
No. With trigger(availableNow=True), a stream processes everything new and then stops, like a batch job that remembers where it left off. Many daily pipelines use streaming code this way.
What is a checkpoint?
A folder where Spark saves the stream's progress: which files or offsets were processed, and any state. If the job restarts, it continues from the checkpoint instead of starting over. Each stream needs its own checkpoint.
Auto Loader or COPY INTO?
Both load only new files. COPY INTO is a simple SQL command, fine for thousands of files. Auto Loader scales to millions of files, supports schema inference and evolution, and can use file notifications. Databricks recommends Auto Loader for most cases.
What does exactly-once mean in Structured Streaming?
Each input record affects the output exactly one time, even if the job crashes and restarts. Spark gets this from replayable sources, checkpoints, and idempotent sinks like Delta tables.
π§ Quick check: Auto Loader and streaming
1. What does Auto Loader remember between runs?
2. trigger(availableNow=True) means...
3. Two streams share one checkpoint folder. What happens?
4. How do you MERGE streaming data into a Delta table?
Checking your accessβ¦