2: Data Ingestion & Acquisition

    Designing and implementing data ingestion pipelines for diverse formats and sources

    Ingestion is the boundary where external data crosses into the Lakehouse.

    The Bronze layer captures source records in their original shape so downstream Silver and Gold layers can replay the transformation chain whenever business logic changes.

    At Professional depth, the exam tests three intertwined decisions on every ingestion question:

    • which connector reads the source,
    • which Spark reader matches the on-disk format,
    • which schema-handling mode survives the inevitable supplier change.

    The full ingestion surface on Databricks spans nine formats (Delta Lake, Parquet, ORC, AVRO, JSON, CSV, XML, Text, Binary) and two source families (cloud object storage and message buses), and a candidate must place every combination on the right path.

    The decision space looks larger than it is because most production ingestion converges on Auto Loader for object storage and on the Kafka structured-streaming source for message buses. The exam tests the edge cases:

    • when a format does not support schema inference,
    • when a message-bus payload is itself a wrapped Avro record,
    • when XML demands a row-tag option that JSON does not,
    • when binary file ingestion is the only path for medical imaging or document workloads.

    The sections below walk through each axis of that decision space.

    🎯 Scenario: A retail data engineer must ingest order events from three sources into the bronze.orders_raw table: nightly CSV drops from a legacy ERP into ADLS, real-time JSON events from a Kafka topic, and weekly Parquet snapshots delivered by a partner over S3. The team wants one Bronze table that captures the original payload from each source plus enough provenance to route downstream Silver transforms by source. The right design uses Auto Loader for the CSV and Parquet paths with cloudFiles.format set per source, a Kafka streaming source for the live topic, and a source_system column populated at ingestion. Each source writes to a distinct staging table to keep schemas clean, and a MERGE-free INSERT INTO bronze.orders_raw performs a union into the canonical Bronze table after lightweight projection.

    Auto Loader as the default for cloud object storage

    Auto Loader (cloudFiles) is the streaming source built for incremental ingestion of files arriving in S3, ADLS Gen2, or GCS. Two properties matter for the Professional exam: how Auto Loader tracks which files have been processed, and how it discovers new files.

    File tracking lives in RocksDB state under the streaming checkpoint, keyed by the source path. Once a file has been recorded, Auto Loader will not re-process it even if a downstream consumer crashes, which keeps Bronze ingestion idempotent across restarts. The state survives cluster restarts and survives runtime upgrades but does not survive a checkpoint deletion; deleting the checkpoint forces a re-ingestion of every file in the source path, which is occasionally the right answer for backfills and almost always wrong otherwise.

    How it works

    File discovery operates in one of two modes.

    • Directory-listing mode (the default) issues a periodic LIST against the source path and compares the result against the RocksDB state to find new files.
    • It is simple and requires no additional cloud configuration.
    • The cost is a per-trigger LIST request that scales with the file count, which becomes expensive when the source path holds millions of objects.
    • File-notification mode (cloudFiles.useNotifications = true) provisions a cloud-native event subscription (SQS in AWS, Event Grid plus Queue Storage in Azure, Pub/Sub in GCP) and consumes file-arrival events from the queue.
    • Throughput stays constant regardless of how many objects accumulate in the source path.
    • The trade-off is setup: file-notification mode requires the cluster identity to hold permission to create event subscriptions, or the queue must be pre-provisioned and named in the Auto Loader options.
    from pyspark.sql.functions import current_timestamp, input_file_name, lit
    
    bronze_df = (
     spark.readStream
     .format("cloudFiles")
     .option("cloudFiles.format", "json")
     .option("cloudFiles.schemaLocation", "/Volumes/main/bronze/_schemas/orders_json")
     .option("cloudFiles.inferColumnTypes", "true")
     .option("cloudFiles.schemaEvolutionMode", "addNewColumns")
     .option("cloudFiles.useNotifications", "true")
     .load("/Volumes/main/landing/orders_json/")
     .withColumn("_ingest_ts", current_timestamp())
     .withColumn("_source_file", input_file_name())
     .withColumn("_source_system", lit("erp_orders"))
    )
    
    (bronze_df.writeStream
     .format("delta")
     .option("checkpointLocation", "/Volumes/main/bronze/_checkpoints/orders_json")
     .option("mergeSchema", "true")
     .trigger(availableNow=True)
     .toTable("main.bronze.orders_raw"))
    

    The cloudFiles.schemaLocation option holds the schema inferred from the source files plus a rescue-data record.

    When the schema changes the stream restarts and Auto Loader writes the new schema into the location, so this directory is part of the contract between job runs.

    Misconfiguring it (sharing a schema location across unrelated streams, for example) corrupts schema evolution.

    The schema location is independent from the checkpoint and must be supplied separately; an exam answer that conflates the two is wrong.

    💡 Exam Trap: A question that asks how to scale Auto Loader for a source with tens of millions of files almost always points at file-notification mode. Directory-listing mode is the default but its LIST cost is linear in object count, so an answer that "increases the trigger interval" or "raises driver memory" is a distractor. The right answer is cloudFiles.useNotifications = true and the cloud-specific event subscription that backs it.

    💡 Exam Trap: Deleting the schema location to reset inference also resets schema evolution history, but the stream's RocksDB file tracking lives at the checkpoint, not the schema location. A question that asks "how do I re-ingest every file with a fresh schema" requires deleting both the checkpoint and the schema location. A question that asks "how do I keep the data history but accept a schema change" requires only restarting the stream after picking a new evolution mode.

    ⚠️ Anti-Pattern: Pointing two independent Auto Loader streams at the same cloudFiles.schemaLocation. The schema location is single-writer; concurrent streams overwrite each other's inferred schema and silently produce broken evolution. Each stream gets its own schema location, period.

    Schema inference and the four evolution modes

    Auto Loader infers schema by sampling the first batch of files (default sample size capped at 1000 files or 50 GB, whichever comes first) and writes the result to the schema location. All columns are inferred as strings unless cloudFiles.inferColumnTypes is set, in which case Auto Loader applies the format-specific type inference rules (which differ between JSON, CSV, XML, Parquet, and so on). String inference is the safe default for Bronze because it preserves the raw payload, but it costs downstream casting work in Silver; for partner feeds where the schema is contractually stable, type inference is fine.

    Steps

    Schema evolution mode controls what happens the next time the stream encounters a file whose schema differs from the recorded one. The four modes are addNewColumns, failOnNewColumns, rescue, and none.

    • Mode addNewColumns is the default and adds any unknown columns to the schema, restarts the stream, and continues; the stream restart is mandatory because the Delta table schema needs the new columns before writes can succeed.
    • Mode failOnNewColumns halts the stream with a SchemaEvolutionError so a human can review; pick this mode for regulated pipelines where adding a column is a governance event.
    • Mode rescue puts every unparseable column into a _rescued_data JSON-string column and does not modify the schema; pick this when columns vary per source file but the canonical schema is fixed.
    • Mode none matches files against the recorded schema and drops any value that does not fit, which is rarely the right answer because data loss is silent.
    (spark.readStream
     .format("cloudFiles")
     .option("cloudFiles.format", "csv")
     .option("cloudFiles.schemaLocation", "/Volumes/main/bronze/_schemas/legacy_csv")
     .option("cloudFiles.inferColumnTypes", "true")
     .option("cloudFiles.schemaEvolutionMode", "rescue")
     .option("header", "true")
     .option("rescuedDataColumn", "_rescued_data")
     .load("/Volumes/main/landing/legacy_csv/")
     .writeStream
     .format("delta")
     .option("checkpointLocation", "/Volumes/main/bronze/_checkpoints/legacy_csv")
     .trigger(availableNow=True)
     .toTable("main.bronze.legacy_csv_raw"))
    

    📊 Limit: Auto Loader's default schema-inference sample is 1000 files or 50 GB. Override with cloudFiles.schemaHints (to fix specific column types) or cloudFiles.schemaInferenceParallelism (to widen the sample) when a partner sends one type per file in the first 1000 files and a different type in file 1001.

    Message-bus ingestion: Kafka, Kinesis, Event Hubs, Pub/Sub

    Message buses present a fundamentally different ingestion surface than object storage.

    The source emits a binary value payload (and optional key, headers, topic, partition, offset) per record, and Spark Structured Streaming consumes the offset positions through the connector's native protocol.

    The Bronze table writes the binary payload verbatim, and decoding into structured columns happens in Silver.

    This pattern preserves provenance and survives schema-registry changes that would otherwise force a stream restart.

    from pyspark.sql.functions import col, current_timestamp
    
    raw_kafka = (
     spark.readStream
     .format("kafka")
     .option("kafka.bootstrap.servers", "broker1:9093,broker2:9093")
     .option("subscribe", "orders.events.v1")
     .option("startingOffsets", "earliest")
     .option("kafka.security.protocol", "SASL_SSL")
     .option("kafka.sasl.mechanism", "OAUTHBEARER")
     .option("kafka.sasl.jaas.config", "org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required;")
     .option("maxOffsetsPerTrigger", 500000)
     .load()
     .select(
     col("topic"),
     col("partition"),
     col("offset"),
     col("timestamp").alias("kafka_ts"),
     col("key").cast("string").alias("event_key"),
     col("value").alias("event_payload"),
     current_timestamp().alias("_ingest_ts"),
     )
    )
    
    (raw_kafka.writeStream
     .format("delta")
     .option("checkpointLocation", "/Volumes/main/bronze/_checkpoints/orders_kafka")
     .outputMode("append")
     .trigger(processingTime="30 seconds")
     .toTable("main.bronze.orders_kafka_raw"))
    

    The Kafka source on Databricks reads binary value and key columns, plus metadata columns the connector populates: topic, partition, offset, timestamp, timestampType, and headers.

    Persisting all of these into the Bronze table makes downstream deduplication and replay trivial because (topic, partition, offset) uniquely identifies the record.

    Avoid decoding the payload at the Kafka boundary; instead, write the binary value to Bronze and apply from_avro / from_json / from_protobuf in the Silver transformation. This decoupling means a schema-registry upgrade does not require re-reading from Kafka.

    Kinesis follows the same pattern via the kinesis source: a data binary column and metadata for the shard, sequence number, and approximate arrival timestamp.

    Event Hubs is consumed through the Kafka API (Event Hubs exposes a Kafka-compatible endpoint) or through the legacy eventhubs connector.

    Pub/Sub uses the pubsub source, which exposes messageId, attributes, publishTimestampInMillis, and payload columns.

    In every case the right Bronze pattern keeps the payload binary and writes the connector-provided offsets so the pipeline can resume safely after a checkpoint loss requires a Kinesis trim-horizon restart.

    💡 Exam Trap: A question that asks how to handle a Kafka source whose schema registry rotated mid-stream is testing whether the candidate keeps the payload binary in Bronze. The correct answer is "decode in Silver with from_avro and a schema-registry lookup". An option that says "restart the Kafka stream with startingOffsets = earliest" is wrong because Bronze should already hold the original bytes.

    ⚠️ Anti-Pattern: Casting value to string at the Kafka source for binary Avro or Protobuf payloads. The cast corrupts multi-byte UTF-8 sequences inside the binary frame, so the eventual from_avro call returns null. Keep the value column typed as binary in Bronze.

    Format-by-format reader behaviour

    Key points

    Delta Lake. Reads via format("delta") are the canonical source when ingesting from another Lakehouse table or from a Delta share. Delta sources support both batch reads (spark.read.format("delta").table(...)) and streaming reads (spark.readStream.format("delta").table(...)). The streaming reader treats appends as the input by default; updates and deletes raise an error unless ignoreChanges, ignoreDeletes, or skipChangeCommits is set. For an append-only Bronze sourced from another Delta table, no extra options are needed.

    Parquet. Self-describing columnar format with strong schema inference. The DataFrame reader and Auto Loader both read Parquet; column pruning and predicate pushdown are automatic. Schema evolution is conservative: adding a column is fine, but renaming a column or changing its type forces a manual schema patch. For ingestion of partner-supplied Parquet snapshots, Auto Loader with cloudFiles.format = "parquet" and cloudFiles.schemaEvolutionMode = "addNewColumns" is the standard configuration.

    ORC. Columnar format common to Hadoop pipelines. Spark reads ORC via format("orc"). Auto Loader supports ORC via cloudFiles.format = "orc". The exam rarely tests ORC depth, but ORC and Parquet behave equivalently for ingestion purposes; the discriminator on an exam question is usually source provenance (Hive jobs emit ORC, Spark jobs emit Parquet).

    AVRO. Row-oriented format with embedded schema, common in Kafka pipelines. Spark reads Avro via format("avro") for file-on-disk Avro and via from_avro(value, schema) for in-message Avro decoded after the Kafka source. The exam tests the distinction: file-Avro is read by the file reader; payload-Avro is decoded by from_avro against either an inline schema or a schema-registry-fetched schema.

    JSON. Two sub-formats matter. Line-delimited JSON (one document per line) is the default and parses through format("json") directly. Multi-line JSON requires option("multiline", "true") and is much slower because the parser cannot split files. Auto Loader inherits both modes via cloudFiles.format = "json". Schema inference promotes ambiguous fields to strings unless cloudFiles.inferColumnTypes = true, in which case numeric inference follows the JSON value type. The corrupt-record column (_corrupt_record) captures unparseable lines when mode = "PERMISSIVE" is the parse mode.

    CSV. Row-oriented text format. Requires header, delimiter, quote, escape, and multiLine options to parse reliably. Schema inference reads the first non-header row by default; for large files Spark's CSV inference can be slow, so production pipelines specify the schema explicitly or accept Auto Loader's RocksDB-cached inference. The badRecordsPath option directs malformed rows to a quarantine path.

    from pyspark.sql.types import StructType, StructField, StringType, IntegerType, TimestampType
    
    orders_schema = StructType([
     StructField("order_id", StringType(), False),
     StructField("customer_id", StringType(), True),
     StructField("order_amount_cents", IntegerType(), True),
     StructField("placed_at", TimestampType(), True),
    ])
    
    csv_stream = (spark.readStream
     .format("cloudFiles")
     .option("cloudFiles.format", "csv")
     .option("header", "true")
     .option("delimiter", ";")
     .option("escape", "\\")
     .option("badRecordsPath", "/Volumes/main/bronze/_bad/orders_csv")
     .schema(orders_schema)
     .load("/Volumes/main/landing/orders_csv/"))
    

    XML. Spark's XML reader, available as a built-in format on supported runtime versions, requires rowTag to identify the repeating element. Without rowTag the reader treats the whole document as one row. For large XML files (the format is verbose), partition the source path by date so Auto Loader can scale ingestion horizontally; XML files do not split well within a single file.

    xml_stream = (spark.readStream
     .format("cloudFiles")
     .option("cloudFiles.format", "xml")
     .option("rowTag", "Order")
     .option("cloudFiles.schemaLocation", "/Volumes/main/bronze/_schemas/orders_xml")
     .option("cloudFiles.inferColumnTypes", "true")
     .load("/Volumes/main/landing/orders_xml/"))
    

    Text. Treats each line as a row in a single value column.

    Used for log lines, CSV-with-no-header treated as opaque, or any line-oriented source the team intends to parse in Silver.

    format("text") is the reader; Auto Loader uses cloudFiles.format = "text".

    Binary. The binary file reader (format("binaryFile")) reads each file's bytes into a content binary column, plus path, modificationTime, and length.

    The use cases are medical imaging, PDF documents, audio files, and any unstructured payload that Silver code parses with a Python UDF or external library.

    Auto Loader supports binary via cloudFiles.format = "binaryFile", but the file size matters: large binary files inflate driver memory during ingestion because they materialise in memory as DataFrames.

    📊 Limit: The binary file reader produces rows where the content column holds the full file. Spark's default maxFileSize is 50 GB per row but the cluster will out-of-memory long before that. For binary ingestion the practical ceiling is per-file memory plus serialization overhead; for files above a few hundred MB, ingest the path and let downstream code stream the file body instead of materialising it.

    💡 Exam Trap: XML without rowTag reads the entire document as a single row. A question that describes XML ingestion producing one row per file is testing whether the candidate spots the missing rowTag.

    Format coverage decision flow

    Decision Tree: Choosing the Right Reader for Each Source

    Source provenance columns

    Every ingestion path needs provenance columns so Bronze rows can be traced to their origin. The standard set is:

    • _ingest_ts (when Spark wrote the row)
    • _source_file (file path for file-based sources, set via input_file_name())
    • _source_system (a literal naming the upstream system)
    • The connector-specific offset columns (topic/partition/offset for Kafka, shardId/sequenceNumber for Kinesis)

    Provenance columns are not optional at Professional depth; downstream auditing, retention policy enforcement, and incident response all depend on them.

    The Silver layer then projects away whatever provenance is not needed in the canonical schema.

    💡 Exam Trap: A question that asks how to deduplicate a Kafka Bronze table on replay is testing whether topic, partition, and offset columns were preserved. The correct answer is a window function or dropDuplicates(["topic", "partition", "offset"]) rather than a hash of value.

    Compute selection for ingestion

    Ingestion workloads are I/O-bound, not CPU-bound.

    The right compute is a job cluster sized to maximise parallelism on the source:

    • more workers when the source has many files (Auto Loader splits file discovery across workers)
    • Photon enabled because Photon's vectorised file readers cut Parquet and Delta read cost

    For high-volume Kafka streams, configure the cluster autoscaler with a small min-worker count to avoid scale-down churn during steady-state ingestion, and bound max workers based on the topic's partition count (more workers than partitions wastes money because Kafka parallelism caps at partition count).

    For Auto Loader the parallelism cap is cloudFiles.maxFilesPerTrigger and cloudFiles.maxBytesPerTrigger; raising these batches more files per trigger but uses more memory.

    ⚠️ Anti-Pattern: Running ingestion on an all-purpose cluster shared with notebook developers. All-purpose clusters bill at the interactive DBU rate (roughly two to three times the job DBU rate) and their lifecycle is interactive (started by humans, stopped by autosuspend). Job clusters are the cost-correct choice for scheduled ingestion.

    📊 Limit: Auto Loader's cloudFiles.maxFilesPerTrigger defaults to 1000 files per microbatch. Combined with cloudFiles.maxBytesPerTrigger (no default), either limit caps the trigger size. Raising these lets a single trigger sweep more backlog but increases driver memory pressure during file metadata accounting.

    Decision Anchor. Choose Auto Loader when the source is files arriving in cloud object storage. Choose a message-bus source (Kafka, Kinesis, Event Hubs, Pub/Sub) when records arrive through a streaming broker.

    Use file-notification mode when the source path holds more than roughly one million objects or when LIST cost becomes the dominant ingestion cost; otherwise keep directory-listing for its simplicity. ---

    Continue with the interactive course

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