Hello! Welcome back to our journey into practical data architecture.
In our last lesson, we contrasted the ETL and ELT architectural patterns. We concluded that ELT, which loads raw data first and transforms it later, is the dominant pattern for modern cloud data platforms. Now, it's time to put that theory into practice.
Today, we'll build the first, foundational stage of our ELT pipeline. This involves implementing the "Extract" and "Load" steps: ingesting raw data from its source into our Databricks lakehouse. Our goal is to implement a pipeline to ingest raw data into a bronze Delta table.
We'll be working with the concept of the Medallion Architecture, a data modeling pattern you'll see frequently. It organizes data into three layers:
- Bronze: Raw, unfiltered data ingested from source systems. This is our focus today.
- Silver: Validated, cleansed, and enriched data.
- Gold: Aggregated, business-level tables for analytics and reporting.
As a software architect, you know that for any given problem, there are often multiple tools with different trade-offs. Data ingestion is no exception. We'll explore the two primary Databricks tools for this job: COPY INTO and Auto Loader.
1. The Challenge: Ingesting Raw Files at Scale
Imagine a scenario where new data files (like CSVs or JSONs) arrive every hour in your cloud storage. A robust ingestion pipeline must:
- Process data incrementally: It should only process new files, not waste time and money reloading files it has already seen.
- Be idempotent: Re-running the pipeline on the same set of files should not result in duplicate data in the target table.
- Handle schema evolution: Source systems sometimes change. The pipeline should gracefully handle new columns without breaking.
- Scale efficiently: It needs to handle anything from a few files to millions of files per day.
Manually managing these challenges is complex and error-prone. This is why specialized tools are essential.

2. Method 1: COPY INTO for Simple Batch Ingestion
The COPY INTO command is a simple, idempotent SQL command for loading data from a file location into a Delta table. It's an excellent starting point for batch ingestion jobs that run on a schedule.
The following article provides a good narrative walkthrough of using COPY INTO.
Building Bronze Layer: Using COPY INTO in Databricks
This article, 'Building Bronze Layer: Using COPY INTO in Databricks' from the Enqurious Academy blog, tells the story of a data engineer solving the exact problem we're tackling today. It effectively demonstrates the power of COPY INTO.
Please read the first few sections, starting from 'The Challenge' and ending at 'How COPY INTO Works: The Magic Behind the Scenes'. Focus on understanding the problems COPY INTO solves and the basic syntax of the command.
As you saw in the article, COPY INTO addresses the core challenges of incremental loading and schema evolution with a straightforward SQL command.
Here's the basic syntax:
COPY INTO bronze_table_name
FROM 'path/to/source/files'
FILEFORMAT = 'your_format' -- e.g., CSV, JSON, PARQUET
FORMAT_OPTIONS (
'header' = 'true',
'inferSchema' = 'true'
)
COPY_OPTIONS (
'mergeSchema' = 'true'
);
How it works:
- Idempotency:
COPY INTOtracks the names of files it has already processed. If you run the command again, it will skip any files it has already loaded, preventing duplicates. - Schema Evolution: The
COPY_OPTIONS ('mergeSchema'='true')setting tells Databricks to automatically add any new columns found in the source files to the target Delta table's schema.
COPY INTO is a great tool, but its file-tracking mechanism (directory listing) can become less efficient when you need to ingest millions of files. For more demanding, large-scale scenarios, Databricks provides a more powerful solution.
3. Method 2: Auto Loader for Scalable, Automated Ingestion
Auto Loader is the recommended, most robust method for incremental data ingestion in Databricks. It's built on top of Spark Structured Streaming but is optimized for processing files from cloud storage efficiently and at a massive scale.
To understand the problems Auto Loader was designed to solve, let's watch a brief conceptual introduction.
Accelerating Data Ingestion with Databricks Autoloader
This official video from Databricks, 'Accelerating Data Ingestion with Databricks Autoloader', explains why traditional file streaming can be hard and introduces Auto Loader as the solution that combines the best of several approaches.
Watch the first 8 minutes of the video. The speaker does an excellent job of outlining the challenges of incremental loading that we discussed earlier and positions Auto Loader as the solution.
Now that you have the "why," let's look at the "how." Auto Loader is used as a streaming source, cloudFiles, within a Spark readStream call.
The following Databricks documentation provides a clean, standard implementation for ingesting JSON files into a bronze table.
Tutorial: Build an ETL pipeline using change data capture
This is from the official Databricks documentation for building an ETL pipeline. It shows the canonical way to set up an Auto Loader stream in Python.
Review the Python code block in the section 'Step 3: Incrementally ingest data with Auto Loader'. We will break this code down next.
Let's dissect the core components of that Python code:
# Define the path to your raw files in cloud storage
path = "/Volumes/<catalog>/<schema>/raw_data/customers"
# Use readStream with the "cloudFiles" format for Auto Loader
(spark.readStream
.format("cloudFiles")
# Specify the format of the files themselves (e.g., json, csv)
.option("cloudFiles.format", "json")
# This option lets Auto Loader infer data types, not just schema structure
.option("cloudFiles.inferColumnTypes", "true")
# A critical option: where to store the evolving schema information
.option("cloudFiles.schemaLocation", "dbfs:/path/to/schema_location")
.load(path)
# Now, write the stream to a Delta table
.writeStream
# This tells Auto Loader to process all available new files and then stop
.trigger(availableNow=True)
# Where to store the state of the stream (which files have been processed)
.option("checkpointLocation", "dbfs:/path/to/checkpoint_location")
# Specify the name of the target bronze Delta table
.toTable("customers_cdc_bronze")
)
Key Concepts:
cloudFilesformat: This is the special source format that invokes Auto Loader.- Checkpoint Location: This is the most important concept. Auto Loader uses this location to store its state, reliably tracking which files have been processed. This provides exactly-once processing guarantees and allows the stream to be stopped and restarted safely.
- Schema Location: Auto Loader can automatically infer the schema of your data. It stores and evolves this schema in the specified location, making it robust against schema drift.
- Trigger (
availableNow=True): While Auto Loader is a streaming technology, this trigger allows you to run it in a batch-like mode. It will process all new files that have arrived since the last run and then shut down. This is perfect for building scheduled ELT jobs without needing a cluster to run 24/7.
Test your understanding!
You are designing an ingestion pipeline for a new data source. The source system will drop tens of thousands of small JSON files into a cloud storage folder every 15 minutes. The schema of these files is expected to change occasionally without notice.
Which tool, COPY INTO or Auto Loader, would be more appropriate, and why?
Show answer
Auto Loader is the more appropriate choice.
Here's why:
- Scalability: Auto Loader is designed to handle very large numbers of files efficiently.
COPY INTOmight struggle with the performance of listing tens of thousands of files every 15 minutes. - Schema Handling: Auto Loader's automatic schema inference and evolution, managed via the
schemaLocation, is more robust for sources with unpredictable schema changes. - Efficiency: For high-frequency jobs, Auto Loader's more advanced file detection mechanisms (especially the file notification mode, which we'll touch on later) are more efficient than the simple directory listing used by
COPY INTO.
For a hands-on demonstration of building and running this code in a Databricks notebook, the following video provides a complete walkthrough.
24 Auto Loader in Databricks | AutoLoader Schema Evolution Modes | File Detection Mode in AutoLoader
This video from 'Ease With Data' provides a practical, step-by-step guide to using Auto Loader in a Databricks notebook.
Watch the sections from 5:09 to 12:21. This covers writing the readStream code, explaining key options, and then writing the writeStream code to a Delta table. Observe how the checkpoint and schema locations are used and how the availableNow trigger works in practice.
4. Conclusion: Choosing the Right Tool
You now have two powerful tools for building the first layer of your data lakehouse. The choice between them is an architectural decision based on your specific requirements.
| Feature | COPY INTO |
Auto Loader |
|---|---|---|
| Primary Use Case | Simple, idempotent batch loading. | Scalable, automated incremental loading. |
| Language | SQL | Python, Scala, SQL |
| Scalability | Good for thousands of files. | Excellent for millions of files. |
| Setup Complexity | Very low. A single SQL command. | Moderate. Requires configuring stream options. |
| Schema Handling | Good (mergeSchema option). |
Excellent (robust inference and evolution). |
| Idempotency | File name based. | Checkpoint based; more robust. |
Key Takeaways:
- The bronze layer is the landing zone for raw data in the Medallion Architecture.
COPY INTOis a simple, SQL-based command for easy, idempotent batch ingestion.- Auto Loader is the more powerful and scalable solution, designed for robust, automated, and high-volume file processing.
- For most modern, production-grade ELT pipelines in Databricks, Auto Loader is the preferred choice.
In our next lesson, we will move to the next stage of the Medallion Architecture. We'll take the raw data we've just landed in our bronze table and begin implementing the "Transform" step to clean, standardize, and load it into a silver Delta table.