Sub topic 12
Setting up file notification mode
This chapter assumes you can already build a basic cloudFiles stream, that you know what a checkpoint and a schema location are, and that you have admin or near-admin access to a cloud account. Chapter 10 compared directory listing with file notification discovery. This chapter covers how to turn notification mode on, what it creates in your cloud account, and what can go wrong.
What notification mode changes
In directory listing mode, Auto Loader lists the input path on each micro-batch and compares the result with the file state in the checkpoint. In file notification mode, Auto Loader subscribes to events from your storage account instead. When a file lands, the storage service publishes an event, a queue stores it, and Auto Loader reads the queue to learn which files are new.
The cost of discovery then depends on how many files arrive, not on how many files already sit in the directory. This helps most with very large directories, deep partition trees, and streams that run frequently over a path that rarely changes.
The services behind it
The services Auto Loader creates depend on the cloud.
| Cloud | Event source | Queue |
|---|---|---|
| AWS | S3 event notifications through SNS | SQS |
| Azure | Event Grid subscription | Azure Queue Storage |
| Google Cloud | Cloud Storage notifications | Pub/Sub subscription |
Auto Loader creates these services for you the first time the stream starts, if the credentials you give it have permission. Alternatively, you can create them yourself and point the stream at the existing queue.
Turning it on
One option switches the mode: cloudFiles.useNotifications. Everything else in the stream stays the same. This example uses AWS.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/events")
.option("cloudFiles.useNotifications", "true")
.option("cloudFiles.region", "us-east-1")
.load("s3://my-bucket/landing/events"))
(df.writeStream
.option("checkpointLocation", "/Volumes/main/raw/_checkpoints/events")
.trigger(availableNow=True)
.toTable("main.bronze.events"))The cloudFiles.region option names the region where the bucket lives. Auto Loader uses it when it creates the SNS topic and SQS queue. If you leave it out, Auto Loader tries to use the region of the workspace, which is wrong when the bucket is in another region.
Permissions
For the automatic setup to work, the identity that runs the stream needs permission to create and manage the notification resources. On AWS this means rights on S3 bucket notification configuration, SNS topics and subscriptions, and SQS queues. On Azure the service principal needs rights on Event Grid and queue storage. On Google Cloud it needs Pub/Sub rights. The Databricks documentation lists the exact permissions for each cloud, and those lists change, so check the current version.
On Azure you also pass identity details as options, for example cloudFiles.subscriptionId, cloudFiles.resourceGroup, cloudFiles.tenantId, cloudFiles.clientId, and cloudFiles.clientSecret. Read the secret from a Databricks secret scope. Never put it in the notebook text.
client_secret = dbutils.secrets.get(scope="ingest", key="sp-secret")
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "csv")
.option("header", "true")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/events_az")
.option("cloudFiles.useNotifications", "true")
.option("cloudFiles.subscriptionId", "<subscription-id>")
.option("cloudFiles.resourceGroup", "<resource-group>")
.option("cloudFiles.tenantId", "<tenant-id>")
.option("cloudFiles.clientId", "<client-id>")
.option("cloudFiles.clientSecret", client_secret)
.load("abfss://[email protected]/events"))Replace the angle-bracket values with your own identifiers before you run it.
Bringing your own queue
Some organizations do not let a streaming job create infrastructure. A platform team creates the topic, queue, and bucket notification ahead of time, and the stream only reads from the queue. On AWS you point the stream at the queue with cloudFiles.queueUrl.
df = (spark.readStream
.format("cloudFiles")
.option("cloudFiles.format", "json")
.option("cloudFiles.schemaLocation", "/Volumes/main/raw/_schemas/events")
.option("cloudFiles.useNotifications", "true")
.option("cloudFiles.region", "us-east-1")
.option("cloudFiles.queueUrl",
"https://sqs.us-east-1.amazonaws.com/123456789012/events-landing")
.load("s3://my-bucket/landing/events"))With a queue you supplied, the stream needs only permission to read and delete messages from that queue and to read the files. It no longer needs rights to change bucket notifications. This is the least-privilege setup, and it is the one to prefer in a locked-down account.
Existing files and notification mode
Events describe only files that arrive after the subscription exists. Files already in the folder produce no event. To avoid silently skipping them, Auto Loader does an initial listing of the path when a stream starts for the first time, then switches to the queue. The cloudFiles.includeExistingFiles option controls this. It defaults to true, so existing files are ingested. Set it to false only if you want to ingest new files alone. It is read when the stream first starts, so changing it later has no effect on an existing checkpoint.
If a stream is down for a while, the queue keeps the messages, subject to the retention period of the queue. A restart then picks up the backlog. If the downtime exceeds the retention period, messages expire and those files are never announced, which leads to the next point.
Notifications are not a guarantee
Event delivery is reliable in practice but is not a hard guarantee. Events can be delayed, and misconfiguration or expired queue retention can lose them. Auto Loader therefore lets you run a periodic safety listing with cloudFiles.backfillInterval.
.option("cloudFiles.backfillInterval", "1 day")With this set, Auto Loader performs an asynchronous backfill listing at that interval and ingests any file the queue missed. The checkpoint prevents files that were already ingested from loading twice. A daily or weekly interval costs very little compared with listing on every batch, and it turns "almost always complete" into "eventually complete."
Throughput and tuning
Rate limits from the previous chapter still apply. cloudFiles.maxFilesPerTrigger and cloudFiles.maxBytesPerTrigger cap how much a micro-batch reads once the queue has told Auto Loader about the files. Notification mode adds one more tuning option: cloudFiles.fetchParallelism sets how many threads read messages from the queue. Raise it when the queue backs up during bursts of very small files. Start with the default and change it only if queue depth keeps growing.
Lifecycle and cleanup
The resources Auto Loader creates live in your cloud account, outside the Databricks workspace. This has three consequences.
- Stopping the stream does not remove them. The topic, queue, and bucket notification stay in place and continue to receive events and incur small costs. Deleting a table or a checkpoint folder does not remove them either.
- The queue belongs to the checkpoint. Auto Loader records the queue it uses in the checkpoint. If you delete the checkpoint and restart, the stream creates a new queue, and the old one is left behind.
- Limits apply per bucket or account. Clouds cap the number of notification configurations on one bucket or storage account. Many notification-mode streams on the same bucket can hit that cap, and the failure appears at stream start.
Databricks provides a resource manager API, available in Scala and callable from Python, for listing and tearing down the notification services that Auto Loader created. Use it when you retire a stream, and run it on a schedule if you create streams often. Read the current API reference before you use it, because it is tied to the runtime version.
Common errors
| Symptom | Likely cause |
|---|---|
| Stream fails at start with an access denied error | The identity lacks rights to create topics, queues, or subscriptions. Grant them, or supply `cloudFiles.queueUrl`. |
| Stream runs but ingests nothing new | The bucket notification was removed, points at a different prefix, or the queue is not the one the stream reads. |
| Some files are missing from the table | Lost or expired events. Add `cloudFiles.backfillInterval`. |
| Queue depth keeps growing | Ingestion is slower than arrival. Raise cluster size, check rate limits, or raise `cloudFiles.fetchParallelism`. |
| Orphaned queues after redeployments | Checkpoints were deleted without cleaning up the old resources. |
Choosing between the modes
Start with directory listing. It needs no cloud setup and works well for modest directories. Move to notification mode when listing time dominates your batch duration, when the path holds millions of files, or when you run the stream so often that repeated listing costs more than the queue. Bear in mind that notification mode adds infrastructure to secure, monitor, and clean up. If your workspace uses Unity Catalog external locations, check whether your runtime offers managed file events. That feature lets Databricks manage the notification plumbing for you, and it could remove most of the setup described here.
Exercise
A stream in notification mode has been stopped for two weeks. The SQS queue retention is four days. Which files will the stream miss when it restarts, and which option would have prevented the loss?
Show answer
It will miss files that arrived in the first ten days of the outage, because their messages expired from the queue after four days. Setting cloudFiles.backfillInterval makes Auto Loader run a periodic listing and ingest files the queue never delivered, with the checkpoint preventing duplicates. A longer queue retention period also helps.
Exercise
Your security team forbids the streaming job from changing S3 bucket notifications. How do you run Auto Loader in notification mode, and which option do you set?
Show answer
Have the platform team create the SNS topic, SQS queue, and bucket notification ahead of time. In the stream, set cloudFiles.useNotifications to true, set cloudFiles.region, and set cloudFiles.queueUrl to the existing queue. The job then needs only rights to read and delete queue messages and to read the files.