2: Data Ingestion and Loading

    Ingestion Patterns and Sources

    Every data pipeline opens with the same question: how does the data physically arrive on the lakehouse? The answer is rarely one shape.

    A finance team might drop a single monthly extract; a marketing platform may push thousands of small JSON files per minute; a transactional database may need rows replicated within seconds.

    The Databricks Data Intelligence Platform addresses this variety with three operating models, batch, incremental, and streaming, and a layered catalog of ingestion primitives that fit each model. Picking the right model up front determines the cost, latency, recoverability, and governance posture of everything downstream. The wrong model is not always slower; it is often more brittle.

    A nightly batch job that scans the entire raw bucket on every run works at small scale, then collapses once file counts cross a few hundred thousand. A streaming job that polls every five seconds for a daily CSV drop burns compute idly. Knowing why each primitive exists, and which tradeoffs it makes, is the foundation for everything else in this chapter.

    Batch ingestion

    How it works

    Batch ingestion processes a bounded dataset in a single run.

    The job starts, reads a defined input (a fixed list of files, a SQL extract, a snapshot table), writes the output, and stops.

    There is no concept of "new files since last time" inside the job itself; if you re-run it, it sees the same input and either rewrites the target or appends duplicates. Batch is the default for sources that are inherently bounded:

    • a quarterly financial close
    • a one-time backfill
    • a vendor file delivered weekly

    It is also the operating model for reading Parquet, ORC, or CSV files through the standard spark.read API without a streaming source.

    A typical batch pattern uses CREATE OR REPLACE TABLE ... AS SELECT for full refreshes, or INSERT OVERWRITE for partition-level rewrites.

    Batch reads have no state to retain between runs, which makes them simple but expensive at scale: every run rereads everything you point it at.

    The compute pattern is usually a Lakeflow Jobs task on job compute with auto-termination, where the cluster starts, processes the bounded dataset, and shuts down.

    -- Pure batch: overwrite the target on every run
    CREATE OR REPLACE TABLE prod_dlh.bronze.monthly_finance_close
    USING DELTA
    AS
    SELECT *
    FROM read_files(
     's3://acme-landing/finance/close/',
     format => 'parquet'
    );
    

    The strength of batch ingestion is determinism.

    The same input always produces the same output, and downstream consumers can reason about freshness using the job's last successful run timestamp.

    The weakness is that batch is blind to incrementality: it has no native notion of "what changed."

    If you need that, you either build it manually (high-water-mark tracking, file checksums) or pick a different primitive.

    Incremental ingestion

    Incremental ingestion is the middle ground. The job runs periodically (every hour, every fifteen minutes, on file arrival) but processes only what changed since the last successful run. The state that records "what changed" lives somewhere durable:

    • in the Delta target's transaction log (COPY INTO)
    • in a Structured Streaming checkpoint directory (Auto Loader)
    • in a connector-managed state store (Lakeflow Connect)

    When to use

    Incremental ingestion is the right default for file-based landing zones. Cloud storage is append-only in practice; partners drop files, applications export them, IoT gateways flush them. Each file is small relative to the cumulative dataset, and reading them all on every run wastes both compute and money. An incremental loader reads only the files that have not yet been seen, marks them as loaded, and exits. Recovery is automatic: if the job dies mid-load, the next run picks up the files that were not committed.

    💡 Exam Trap: Incremental loading is not the same as streaming. COPY INTO runs incrementally but is a one-shot SQL command, not a continuous stream. Auto Loader can run incrementally in two ways: as a triggered batch (one batch per invocation) or as a continuous stream. Confusing the two leads to wrong answers about scheduling and checkpointing.

    Streaming ingestion

    Streaming ingestion processes records as they arrive, with end-to-end latencies measured in seconds. On Databricks, streaming is built on Structured Streaming, the unified API that treats a continuously appended table or queue as the source.

    Sources include Kafka, Kinesis, Event Hubs, Pulsar, Delta tables (read as streams), and cloud storage paths (through Auto Loader). The sink can be a Delta table, another queue, or a foreach writer.

    Streaming jobs have continuous compute (a long-running cluster or pipeline) and durable checkpoints that record the last processed offset. They support exactly-once semantics into Delta sinks: if the job crashes and restarts, no record is doubled and none is lost, provided the source offsets are deterministic.

    Latency is tunable through the processingTime trigger or the availableNow trigger, which processes all currently-available data in micro-batches and then stops, ideal for incremental backfills that share streaming machinery.

    # Streaming ingestion from Auto Loader into a Unity Catalog Delta table
    from pyspark.sql.functions import current_timestamp
    
    (spark.readStream
     .format("cloudFiles")
     .option("cloudFiles.format", "json")
     .option("cloudFiles.schemaLocation", "/Volumes/prod_dlh/bronze/_schemas/orders")
     .load("s3://acme-landing/orders/")
     .withColumn("ingest_ts", current_timestamp())
     .writeStream
     .option("checkpointLocation", "/Volumes/prod_dlh/bronze/_checkpoints/orders")
     .trigger(processingTime="30 seconds")
     .toTable("prod_dlh.bronze.orders_raw")
    )
    

    Sources you can import from

    The platform recognizes four broad source classes for ingestion. First, local files uploaded through the workspace UI; this is the fastest path for ad hoc exploration and tutorials.

    Use the Catalog Explorer "Create" menu to upload a CSV or Excel file directly into a Unity Catalog table, or drag a file into a notebook to attach it as a workspace file. Local file uploads are not appropriate for production ingestion because they bypass durability and lineage tracking.

    Second, cloud object storage: S3 on AWS, ADLS Gen2 on Azure, GCS on Google Cloud. This is the most common production source.

    Files arrive via partner SFTP relays, application exports, IoT firehoses, or batch jobs from upstream systems. The lakehouse consumes them through COPY INTO (incremental SQL), Auto Loader (streaming), or read_files (batch).

    Unity Catalog external locations and storage credentials govern which principals can read or write each path.

    Third, Lakeflow Connect standard connectors: SaaS sources exposed through APIs that the platform invokes on a schedule, such as Google Analytics, ServiceNow, SharePoint, and similar. Standard connectors are typically read-only and produce bronze tables with consistent schemas across runs.

    Fourth, Lakeflow Connect managed connectors: enterprise systems with rich change-data-capture semantics, including Salesforce, Workday, SQL Server, ServiceNow (managed variant), and others. Managed connectors handle CDC, watermarking, and snapshot reconciliation for you, writing directly into Unity Catalog Delta tables.

    Importing local files

    The UI offers two equivalent entry points.

    • From a workspace, choose "New" then "Add data" then "Upload file to volume" to drop a file into a Unity Catalog volume.
    • From Catalog Explorer, navigate to the target schema and click "Create" then "Table" to upload directly into a managed table with schema inference.

    The CLI alternative uploads a file to a volume, after which read_files consumes it like any object-store path.

    # Upload a CSV to a Unity Catalog volume from a local machine
    databricks fs cp ./customer_seed.csv \
     dbfs:/Volumes/prod_dlh/bronze/_uploads/customer_seed.csv
    
    -- Then create or refresh a table from it
    CREATE OR REPLACE TABLE prod_dlh.bronze.customer_seed
    AS SELECT * FROM read_files(
     '/Volumes/prod_dlh/bronze/_uploads/customer_seed.csv',
     format => 'csv',
     header => true,
     inferSchema => true
    );
    

    Limits and quotas

    📊 Limit: Workspace file upload through the UI is capped per file at the workspace size limit (commonly several hundred megabytes for direct upload; verify in workspace settings before relying on it). For larger payloads, write to a volume through the CLI or REST API.

    📊 Limit: Auto Loader directory listing performance degrades sharply once a single directory accumulates more than roughly one million files. Use date-partitioned folder layouts or switch to file notification mode well before that ceiling.

    💡 Exam Trap: "Batch" on Databricks does not mean "non-streaming." Trigger.AvailableNow runs through the streaming engine but terminates when the source is drained, which makes it behave like an incremental batch job. Exam stems that pair "batch" with "checkpoint location" usually point to this trigger, not to spark.read.

    ⚠️ Anti-Pattern: Pointing spark.read.format("json").load(path) at a continuously-growing bucket as a "poor man's incremental loader" and filtering by file timestamp inside the query. The job rereads every file on every run, schema drift is never detected, and recovery after a partial failure requires manual deduplication. Use Auto Loader or COPY INTO instead.

    Choosing the operating model

    Key points

    The first decision is latency tolerance.

    • If the business can wait minutes to hours, lean toward incremental ingestion (Auto Loader with availableNow, or COPY INTO on a schedule).
    • If the business needs seconds, choose continuous streaming.
    • If the business only needs a complete refresh on a known cadence, pure batch is the simplest and most reproducible choice.

    The second decision is source shape.

    • Append-only file landings are a strong fit for COPY INTO and Auto Loader.
    • Change-data-capture from operational databases is a strong fit for Lakeflow Connect managed connectors.
    • API-based SaaS pulls are a fit for Lakeflow Connect standard connectors.
    • One-off vendor extracts that arrive irregularly may not need any orchestration beyond a file-arrival trigger.

    The third decision is governance.

    • Targets in Unity Catalog are the default for any pipeline that needs cross-workspace access controls, lineage, or auditing.
    • Targets in the deprecated hive_metastore are tolerated only for legacy reasons and should never appear in new pipelines.

    Decision Anchor:

    • Choose batch when the source is bounded and refreshed on a coarse cadence (daily or longer).
    • Choose incremental (COPY INTO or Auto Loader availableNow) when the source is append-only files in cloud storage and the latency target is minutes to hours.
    • Choose streaming (Auto Loader continuous, Kafka, Lakeflow Spark Declarative Pipelines in continuous mode) when latency must stay under a few minutes and the source produces events continuously.

    🎯 Scenario: A retail data team receives ~20,000 small JSON files per hour from store point-of-sale terminals, dropped into s3://acme-landing/pos/. The business wants order data visible in dashboards within fifteen minutes. A nightly batch job is too slow, and a five-second streaming job is more compute than needed. The right choice is Auto Loader with file-notification mode and a processingTime="2 minutes" trigger writing into prod_dlh.bronze.pos_orders_raw. This keeps end-to-end latency well under the fifteen-minute target while avoiding constant micro-batch overhead.

    Where ingestion lands

    Regardless of model, the destination is almost always a bronze table in Unity Catalog.

    Bronze tables hold raw or near-raw records with minimal transformation: the source columns, a few audit fields (ingestion timestamp, source filename), and the same physical schema as the upstream system.

    The medallion architecture introduced in Chapter 1 routes everything through bronze before refinement, which gives every pipeline a single auditable point of arrival and a stable replay surface if downstream logic changes. Bronze tables on Unity Catalog can be managed or external.

    • Managed bronze tables are simplest: Unity Catalog owns the storage path and the table identity.
    • External bronze tables are appropriate when the same physical files must be read by tools outside the lakehouse, or when the storage layout is dictated by a regulatory boundary.

    Either way, the ingestion primitive (COPY INTO, Auto Loader, Lakeflow Connect) is independent of the managed-versus-external choice.

    💡 Exam Trap: Ingestion never targets a view. Views are derived objects without their own storage. If a question shows an ingestion command writing to a view name, the answer is almost certainly wrong.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Databricks - Data Engineer Associate learning hub.