Sub topic 2
Reading from streaming sources
This chapter assumes you know basic PySpark DataFrame operations, Delta Lake tables, and how to use a Databricks notebook with Unity Catalog. It covers how a streaming query reads its input and which sources you will meet most often.
What a streaming source does
A streaming source is anything Spark can read incrementally. You start a read with spark.readStream instead of spark.read. The result is a streaming DataFrame. It looks like a normal DataFrame, but Spark does not run it until you attach a sink and start a query.
Each source must be able to tell Spark which data is new. It does this with offsets, which are positions in the input such as a Kafka offset or a Delta table version. Spark records the offsets it has processed in the checkpoint, so a restarted query continues from where it stopped.
Common sources
| Source | Format name | Typical use |
|---|---|---|
| Files with Auto Loader | `cloudFiles` | Ingesting files that land in cloud storage or a volume |
| Delta table | `readStream.table(...)` | Reading another table's changes downstream |
| Kafka | `kafka` | Reading events from a message broker |
Auto Loader and Delta sources get their own chapters. Here we focus on the general pattern and on Kafka.
Reading from a Delta table
Pass a table name to readStream.table. Spark treats each new commit to the table as new input.
events = spark.readStream.table("main.demo.orders_bronze")The source table should only receive appends. If upstream jobs update or delete rows, the stream fails by default, because those changes are not new rows. Later chapters cover the options for handling this.
Reading from Kafka
The Kafka source needs the broker addresses and a topic to read. The startingOffsets option applies only the first time the query runs. After that, the checkpoint decides where to resume.
from pyspark.sql import functions as F
raw = (
spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", "broker1:9092")
.option("subscribe", "orders")
.option("startingOffsets", "latest")
.load()
)
parsed = raw.select(F.col("value").cast("string").alias("json"), "timestamp")Kafka returns key and value as binary. It also returns the metadata columns topic, partition, offset, timestamp and timestampType. Cast value to a string, then parse it, for example with from_json.
Common errors
- Using
spark.readby mistake. This gives a one-time batch read. The query will not pick up new data. - Calling
show()orcollect()on a streaming DataFrame. Streaming DataFrames cannot be used with these actions. Write to a sink withwriteStreaminstead. - Reading binary Kafka data as text. Without the cast, the
valuecolumn holds bytes that look unreadable. - Expecting
startingOffsetsto rewind a running query. To start over, you must use a new checkpoint location. - Reading a Delta table with updates or deletes. The stream stops with an error until you handle those changes.
Checking that a DataFrame is streaming
You can confirm what you built before starting a query.
print(parsed.isStreaming)This prints True for a streaming DataFrame and False for a batch one.
Exercise
You start a Kafka query with startingOffsets set to earliest, stop it, and restart it with the same checkpoint location after changing the option to latest. Where does the query resume, and why?
Show answer
It resumes from the offsets stored in the checkpoint, not from the latest offsets. startingOffsets is used only when the query has no checkpoint yet. To start from the latest data, you must use a new checkpoint location.