Load files from Azure Data Lake Storage Gen2 (ADLS Gen2) using Auto Loader

Auto Loader incrementally and efficiently processes new data files as they arrive in ADLS Gen2 (abfss://). Auto Loader can also be used to ingest data from Azure Blob Storage (wasbs://) as well as ADLS Gen1 (adl://).

Auto Loader provides a Structured Streaming source called cloudFiles. Given an input directory path on the cloud file storage, the cloudFiles source automatically processes new files as they arrive, with the option of also processing existing files in that directory.

The Auto Loader works with DBFS paths as well as direct paths to the data source.


Databricks Runtime 7.2 or above.

If you created streams using Databricks Runtime 7.1 or below, see Changes in default option values and compatibility and Cloud resource management.

File discovery modes

Auto Loader supports two modes for detecting when there are new files: directory listing and file notification.

  • Directory listing: Identifies new files by listing the input directory. Directory listing mode allows you to quickly start Auto Loader streams without any permission configuration and is suitable for scenarios where only a few files need to be streamed in on a regular basis. Directory listing mode is the default for Auto Loader in Databricks Runtime 7.2 and above. In Databricks Runtime 7.3 LTS and above, Auto Loader supports Azure Data Lake Storage Gen 1 only in directory listing mode.
  • File notification: Uses Azure Event Grid and Queue Storage services that subscribe to file events from the input directory. Auto Loader automatically sets up the Azure Event Grid and Queue Storage services. File notification mode is more performant and scalable for large input directories. To use this mode, you must configure permissions for the Azure Event Grid and Queue Storage services and specify .option("cloudFiles.useNotifications","true"). File notifications are supported for ADLS Gen2 and Azure Blob Storage.

ADLS Gen2 provides different event notifications for files appearing in your Gen2 container.

  • Auto Loader listens for the FlushWithClose event for processing a file.
    • Auto Loader streams created with Databricks Runtime 8.3 and after support the RenameFile action for discovering files. RenameFile actions will require an API request to the storage system to get the size of the renamed file.
    • Auto Loader streams created with Databricks Runtime 9.0 and after support the RenameDirectory action for discovering files. RenameDirectory actions will require API requests to the storage system to list the contents of the renamed directory.

You can change modes when you restart the stream. For example, you may want to switch to file notification mode when the directory listing is getting too slow due to the increase in input directory size. For both modes, Auto Loader internally keeps tracks of what files have been processed in your streaming checkpoint location to provide exactly-once semantics, so you do not need to manage any state information yourself.

Use cloudFiles source

To use the Auto Loader, create a cloudFiles source in the same way as other streaming sources. The code below will start an Auto Loader stream writing to Delta Lake in directory listing mode:

df = spark.readStream.format("cloudFiles") \
  .option(<cloudFiles-option>, <option-value>) \
  .schema(<schema>) \

df.writeStream.format("delta") \
  .option("checkpointLocation", <checkpoint-path>) \
  .trigger(<trigger>) \
val df = spark.readStream.format("cloudFiles")
  .option(<cloudFiles-option>, <option-value>)

  .option("checkpointLocation", <checkpoint-path>)


  • <cloudFiles-option> is a configuration option in Configuration.
  • <schema> is the file schema. Auto Loader also supports schema inference and evolution with some file formats. See Schema inference and evolution for more details
  • <input-path> is the path in storage that is monitored for new files. Child directories of <input-path> are also monitored. <input-path> can contain file glob patterns. The glob pattern will have * appended to it; if this includes files you don’t want to ingest you can include an additional filter through the pathGlobFilter option. If you are providing a queue for file notifications and don’t need to backfill any data, you don’t need to provide an input path.
  • <checkpoint-path> is the stream checkpoint location.
  • <trigger> An optional trigger for the stream. The default is to execute the next micro-batch as quickly as possible. If you have data arriving at a regular interval, for example once a day, you can use Trigger.Once and schedule the execution of your streams in a Databricks job. For Databricks Runtime 10.1 and above, Auto Loader now supports a new type of trigger: Trigger.AvailableNow for both directory listing and file notification modes. Trigger.AvailableNow provides the same guarantees as Trigger.Once, which processes all available data and then stops the query. But Trigger.AvailableNow can perform rate limiting and split the work across multiple batches, therefore is recommended instead of Trigger.Once. For always-on streams, Databricks recommends that you set a processing time trigger.
  • <output-path> is the output stream path.

Benefits over Apache Spark FileStreamSource

In Apache Spark, you can read files incrementally using spark.readStream.format(fileFormat).load(directory). Auto Loader provides the following benefits over the file source:

  • Scalability: Auto Loader can discover billions of files efficiently. Backfills can be performed asynchronously to avoid wasting any compute resources.
  • Performance: The cost of discovering files with Auto Loader scales with the number of files that are being ingested instead of the number of directories that the files may land in. See Optimized directory listing.
  • Schema inference and evolution support: Auto Loader can detect schema drifts, notify you when schema changes happen, and rescue data that would have been otherwise ignored or lost. See Schema inference and evolution.
  • Cost: Auto Loader uses native cloud APIs to get lists of files that exist in storage. In addition, Auto Loader’s file notification mode can help reduce your cloud costs further by avoiding directory listing altogether. Auto Loader can automatically set up file notification services on storage to make file discovery much cheaper.

Optimized directory listing


Available in Databricks Runtime 9.0 and above.

Auto Loader can discover files on cloud storage systems using directory listing more efficiently than other alternatives. For example, if you had files being uploaded every 5 minutes as /some/path/YYYY/MM/DD/HH/fileName, to find all the files in these directories, the Apache Spark file source would list all subdirectories in parallel, causing 1 (base directory) + 365 (per day) * 24 (per hour) = 8761 LIST API directory calls to storage. By receiving a flattened response from storage, Auto Loader reduces the number of API calls to the number of files in storage divided by the number of results returned by each API call, greatly reducing your cloud costs.

Incremental Listing


This feature is in Public Preview.


Available in Databricks Runtime 9.1 LTS and above.

For lexicographically generated files, Auto Loader now can leverage the lexical file ordering and existing optimized APIs to improve the efficiency of directory listing by listing from previous ingested files rather than listing the entire directory.

By default, Auto Loader will automatically detect whether a given directory is applicable for the incremental listing by checking and comparing file paths of previous completed full directory listings. To ensure eventual completeness in this auto mode, Auto Loader will automatically trigger the full directory listing after completing 7 consecutive incremental listings. If you want to be more frequent or less frequent, you can set cloudFiles.backfillInterval to trigger asynchronous backfills at a given interval.

If you have confidence in the order of files generated in the directory, you can explicitly turn on or off the incremental listing mode by setting cloudFiles.useIncrementalListing to true or false (default auto), e.g., files that are ordered by date=... partitions can be considered lexically ordered if data is processed once a day, file paths containing timestamps can be considered lexically ordered. You can always use cloudFiles.backfillInterval to ensure that all data is ingested when you turn on the incremental listing.

Schema inference and evolution


Available in Databricks Runtime 8.2 and above.

Auto Loader supports schema inference and evolution with CSV, JSON, binary (binaryFile), and text file formats. See Schema inference and evolution in Auto Loader for details.

Run Auto Loader in production

Databricks recommends that you follow the streaming best practices for running Auto Loader in production.


Configuration options specific to the cloudFiles source are prefixed with cloudFiles so that they are in a separate namespace from other Structured Streaming source options.


Some default option values changed in Databricks Runtime 7.2. If you are using Auto Loader on Databricks Runtime 7.1 or below, see Changes in default option values and compatibility.

File format options

With Auto Loader you can ingest JSON, CSV, PARQUET, AVRO, TEXT, BINARYFILE, and ORC files. See Format options for the options for these file formats.

Common Auto Loader options

You can configure the following options for directory listing or file notification mode.



Type: Boolean

Whether to allow input directory file changes to overwrite existing data. Available in Databricks Runtime 7.6 and above.

Default value: false


Type: String

The data file format in the source path. Allowed values include:

Default value: None (required option)


Type: Boolean

Whether to include existing files in the stream processing input path or to only process new files arriving after initial setup. This option is evaluated only when you start a stream for the first time. Changing this option after restarting the stream has no effect.

Default value: true


Type: Boolean

Whether to infer exact column types when leveraging schema inference. By default, columns are inferred as strings when inferring JSON datasets. See schema inference for more details.

Default value: false


Type: Byte String

The maximum number of new bytes to be processed in every trigger. You can specify a byte string such as 10g to limit each microbatch to 10 GB of data. This is a soft maximum. If you have files that are 3 GB each, Databricks processes 12 GB in a microbatch. When used together with cloudFiles.maxFilesPerTrigger, Databricks consumes up to the lower limit of cloudFiles.maxFilesPerTrigger or cloudFiles.maxBytesPerTrigger, whichever is reached first. This option has no effect when used with Trigger.Once().

Default value: None


Type: Interval String

How long a file event is tracked for deduplication purposes. Databricks does not recommend tuning this parameter unless you are ingesting data at the order of millions of files an hour. See the section on How to choose maxFileAge for more details.

Default value: None


Type: Map(String, String)

A series of key-value tag pairs to help associate and identify related resources, for example:

cloudFiles.option("cloudFiles.resourceTag.myFirstKey", "myFirstValue")           .option("cloudFiles.resourceTag.mySecondKey", "mySecondValue")

For more information, see Amazon SQS cost allocation tags and Configuring tags for an Amazon SNS topic. (1)

Default value: None


Type: String

The mode for evolving the schema as new columns are discovered in the data. By default, columns are inferred as strings when inferring JSON datasets. See schema evolution for more details.

Default value: "addNewColumns" when a schema is not provided. "none" otherwise.


Type: String

Schema information that you provide to Auto Loader during schema inference. See schema hints for more details.

Default value: None


Type: String

The location to store the inferred schema and subsequent changes. See schema inference for more details.

Default value: None (required when inferring the schema)


Type: Boolean

Whether to validate Auto Loader options and return an error for unknown or inconsistent options.

Default value: true



This feature is in Public Preview.

Type: Interval String

Auto Loader can trigger asynchronous backfills at a given interval, e.g. 1 day to backfill once a day, or 1 week to backfill once a week. File event notification systems do not guarantee 100% delivery of all files that have been uploaded therefore you can use backfills to guarantee that all files eventually get processed, available in Databricks Runtime 8.4 (Unsupported) and above. If using the incremental listing, you can also use regular backfills to guarantee the eventual completeness, available in Databricks Runtime 9.1 LTS and above.

Default value: None

(1) Auto Loader adds the following key-value tag pairs by default on a best-effort basis:

  • vendor: Databricks
  • path: The location from where the data is loaded.
  • checkpointLocation: The location of the stream’s checkpoint.
  • streamId: A globally unique identifier for the stream.

These key names are reserved and you cannot overwrite their values.

Directory Listing options

The following options are relevant to directory listing mode.




This feature is in Public Preview.

Type: String

Whether to use the incremental listing rather than the full listing in directory listing mode. By default, Auto Loader will make the best effort to automatically detect if a given directory is applicable for the incremental listing. You can explicitly use the incremental listing or use the full directory listing by setting it as true or false respectively.

Available in Databricks Runtime 9.1 LTS and above.

Default value: auto

Available values: auto, true, false

How to choose maxFileAge


Available in Databricks Runtime 8.4 and above.

Auto Loader keeps track of discovered files in the checkpoint location using RocksDB to provide exactly-once ingestion guarantees. For high volume datasets, you can use the maxFileAge option to expire events from the checkpoint location. The minimum value that you can set for maxFileAge is "14 days". Deletes in RocksDB appear as tombstone entries, therefore you should expect the storage usage to increase as events expire before it starts to level off.


maxFileAge is provided as a cost control mechanism for high volume datasets, ingesting in the order of millions of files every hour. Tuning maxFileAge incorrectly can lead to data quality issues. Therefore, Databricks doesn’t recommend tuning this parameter unless absolutely required.

Trying to tune the maxFileAge option can lead to unprocessed files being ignored by Auto Loader or already processed files expiring and then being re-processed causing duplicate data. Here are some things to consider when choosing a maxFileAge:

  • If your stream restarts after a long time, file notification events that are pulled from the queue that are older than maxFileAge are ignored. Similarly, if you use directory listing, files that may have appeared during the down time that are older than maxFileAge are ignored.
  • If you use directory listing mode and use maxFileAge, for example set to "1 month", you stop your stream and restart the stream with maxFileAge set to "2 months", all files that are older than 1 month, but more recent than 2 months are reprocessed.

The best approach to tuning maxFileAge would be to start from a generous expiration, for example, "1 year" and working downwards to something like "9 months". If you set this option the first time you start the stream, you will not ingest data older than maxFileAge, therefore, if you want to ingest old data you should not set this option as you start your stream.

File notification options

The following options are relevant to file notification mode.



Type: Integer

Number of threads to use when fetching messages from the queueing service.

Default value: 1


Type: A JSON string

Only required if you specify a queueName that receives file notifications from multiple ADLS Gen2 containers and you would like to leverage mount points that are configured for accessing data in these containers. Use this option to rewrite the prefix of the container@storage-account/key path with the mount point. Only prefixes can be rewritten. For example, for the configuration {"<container>@<storage-account>/path": "dbfs:/mnt/data-warehouse"}, the path abfss://<container>@<storage-accnt>.dfs.core.windows.net/path/17/08/flA.json is rewritten to dbfs:/mnt/data-warehouse/17/08/fleA.json.

Default value: None


Type: String

The name of the Azure queue. If provided, the cloud files source directly consumes events from this queue instead of setting up its own Azure Event Grid and Queue Storage services. In that case, your cloudFiles.connectionString requires only read permissions on the queue.

Default value: None


Type: Boolean

Whether to use file notification mode to determine when there are new files. If false, use directory listing mode. See File discovery modes.

Default value: false

You must provide values for all of the following options if you specify cloudFiles.useNotifications = true and you want Auto Loader to set up the notification services for you:



Type: String

The client ID or application ID of the service principal. (1)

Default value: None


Type: String

The client secret of the service principal.

Default value: None


Type: String

The connection string for the storage account, based on either account access key or shared access signature (SAS). (1)

Default value: None


Type: String

The Azure Resource Group under which the storage account is created.

Default value: None


Type: String

The Azure Subscription ID under which the resource group is created.

Default value: None


Type: String

The Azure Tenant ID under which the service principal is created.

Default value: None

(1) See Permissions.


Notifications are held in the Azure message queue for 7 days. If you stop the stream and restart after more than 7 days, you lose the notifications in the message queue. While the notifications are stopped, Databricks falls back to directory listing mode and processes files from the point where the stream stopped; there is no data loss. However, this might take some time and performance will be slow until Databricks catches up to the current state of the stream.

Changes in default option values and compatibility

The default values of the following Auto Loader options changed in Databricks Runtime 7.2 to the values listed in Configuration.

  • cloudFiles.useNotifications
  • cloudFiles.includeExistingFiles
  • cloudFiles.validateOptions

Auto Loader streams started on Databricks Runtime 7.1 and below have the following default option values:

  • cloudFiles.useNotifications is true
  • cloudFiles.includeExistingFiles is false
  • cloudFiles.validateOptions is false

To ensure compatibility with existing applications, these default option values do not change when you run your existing Auto Loader streams on Databricks Runtime 7.2 or above; the streams will have the same behavior after the upgrade.


You must have read permissions for the input directory. See Azure Blob Storage and Azure Data Lake Storage Gen2.

To use file notification mode, you must provide authentication credentials for setting up and accessing the event notification services. In Databricks Runtime 8.1 and above, you only need a service principal for authentication. For Databricks Runtime 8.0 and below, you must provide both a service principal and a connection string.

  • Service principal

    Create an Azure Active Directory app and service principal in the form of client ID and client secret.

    Assign this app the following roles to the storage account in which the input path resides:

    • Contributor: This role is for setting up resources in your storage account, such as queues and event subscriptions.
    • Storage Queue Data Contributor: This role is for performing queue operations such as retrieving and deleting messages from the queues. This role is required in Databricks Runtime 8.1 and above only when you provide a service principal without a connection string.

    Assign this app the following role to the related resource group:

    For more information, see Assign Azure roles using the Azure portal.

  • Connection string

    Auto Loader requires a connection stringto authenticate for Azure Queue Storage operations, such as creating a queue and reading and deleting messages from the queue. The queue is created in the same storage account where the input directory path is located. You can find your connection string in your account key or shared access signature (SAS).

    If you are using Databricks Runtime 8.1 or above, you do not need a connection string.

    If you are using Databricks Runtime 8.0 or below, you must provide a connection string to authenticate for Azure Queue Storage operations, such as creating a queue and retrieving and deleting messages from the queue. The queue is created in the same storage account in which the input path resides. You can find your connection string in your account key or shared access signature (SAS). When configuring an SAS token, you must provide the following permissions:

Auto loader permissions


If you do not have the necessary permissions to create resources, you can ask an administrator to perform setup using the Cloud resource management Scala API. An administrator can provide you with the queue name, which you can specify directly as .option("cloudFiles.queueName", <queue-name>) to the cloudFiles source.



java.lang.RuntimeException: Failed to create event grid subscription.

If you see this error message when you run Auto Loader for the first time, the Event Grid is not registered as a Resource Provider in your Azure subscription. To register this on Azure portal:

  1. Go to your subscription.
  2. Click Resource Providers under the Settings section.
  3. Register the provider Microsoft.EventGrid.


403 Forbidden ... does not have authorization to perform action 'Microsoft.EventGrid/eventSubscriptions/[read|write]' over scope ...

If you see this error message when you run Auto Loader for the first time, ensure you have given the Contributor role to your service principal for Event Grid as well as your storage account.


Auto Loader reports metrics at every batch. You can view how many files exist in the backlog and how large the backlog is in the numFilesOutstanding and numBytesOutstanding metrics under the Raw Data tab in the streaming query progress dashboard:

  "sources" : [
      "description" : "CloudFilesSource[/path/to/source]",
      "metrics" : {
        "numFilesOutstanding" : "238",
        "numBytesOutstanding" : "163939124006"

Cloud resource management

You can use a Scala API to manage the Azure Event Grid and Queue Storage services created by Auto Loader. You must configure the resource setup permissions described in Permissions before using this API.

import com.databricks.sql.CloudFilesAzureResourceManager
val manager = CloudFilesAzureResourceManager
  .option("cloudFiles.connectionString", <connection-string>)
  .option("cloudFiles.resourceGroup", <resource-group>)
  .option("cloudFiles.subscriptionId", <subscription-id>)
  .option("cloudFiles.tenantId", <tenant-id>)
  .option("cloudFiles.clientId", <service-principal-client-id>)
  .option("cloudFiles.clientSecret", <service-principal-client-secret>)
  .option("path", <path-to-specific-container-and-folder>) // required only for setUpNotificationServices

// Set up an AQS queue and an event grid subscription associated with the path used in the manager. Available in Databricks Runtime 7.4 and above.

// List notification services created by Auto Loader

// Tear down the notification services created for a specific stream ID.
// Stream ID is a GUID string that you can find in the list result above.


Available in Databricks Runtime 7.4 and above.

Use setUpNotificationServices(<resource-suffix>) to create a Queue and an Event Grid Subscription with the name databricks-<resource-suffix>. If there is an existing Queue or Event Grid Subscription with the same name, Databricks reuses the resource that already exists instead of creating a new one. This function returns a Queue that you can pass to the cloudFiles source using .option("cloudFiles.queueName", <queue-name>). This enables the cloudFiles source user to have fewer permissions than the user who creates the resources. See Permissions.

Provide the "path" option to newManager only if calling setUpNotificationServices; it is not needed for listNotificationServices or tearDownNotificationServices. This is the same path that you use when running a streaming query.

Frequently asked questions (FAQ)

Do I need to create Azure event notification services beforehand?

No. If you choose file notification mode, Auto Loader creates an Azure Data Lake Storage Gen2 > Azure Event Grid Subscription > Azure Queue Storage file event notification pipeline automatically when you start the stream.

How do I clean up the event notification resources, such as Event Grid Subscriptions and Queues, created by Auto Loader?

You can use the cloud resource manager to list and tear down resources. You can also delete these resources manually, either in the Web Portal or using Azure APIs. All resources created by Auto Loader have the prefix: databricks-.

Does Auto Loader process the file again when the file gets appended or overwritten?

Files are processed exactly once unless you enable cloudFiles.allowOverwrites. If a file is appended to or overwritten, Databricks does not guarantee which version of the file is processed. For well-defined behavior, Databricks recommends that you use Auto Loader to ingest only immutable files. If this does not meet your requirements, contact your Databricks representative.

Can I run multiple streaming queries from the same input directory?

Yes. Each cloud files stream, as identified by a unique checkpoint directory, has its own Queue, and the same ADLS Gen2 events can be sent to multiple Queues.

If my data files do not arrive continuously, but in regular intervals, for example, once a day, should I still use this source and are there any benefits?

Yes and yes. In this case, you can set up a Trigger-Once Structured Streaming job and schedule to run after the anticipated file arrival time. The first run sets up the event notification services, which will be always on, even when the streaming cluster is down. When you restart the stream, the cloudFiles source fetches and processes all files events backed up in the Queue. The benefit of using Auto Loader for this case is that you don’t need to determine which files are new and to be processed each time, which can be very expensive.

What happens if I change the checkpoint location when restarting the stream?

A checkpoint location maintains important identifying information of a stream. Changing the checkpoint location effectively means that you have abandoned the previous stream and started a new stream. The new stream will create new progress information and if you are using file notification mode, new Azure Event Grid and Queue Storage services. You must manually clean up the checkpoint location and Azure Event Grid and Queue Storage services for any abandoned streams.