Parquet gives you a fast, open columnar format. It does not give you correctness when two jobs write to the same path, when a reader arrives halfway through a write, or when someone needs to see what a table looked like yesterday. Delta Lake adds a transaction log on top of those files, and that single addition is what makes a data lake behave more like a database.
This lesson covers the parts you will use daily in Azure Databricks:
- How the transaction log delivers atomicity and time travel.
- Auto Loader for incremental file discovery without custom listing logic.
- Schema evolution rules and when each one is safe.
- Maintenance commands that keep read performance from collapsing.
Prerequisites
- !PySpark DataFrame basics
- !ADLS Gen2 paths and service principals
- !A Databricks workspace on Azure
What plain Parquet cannot do
A directory of Parquet files has no notion of a commit. If a streaming job appends files while a batch job rewrites the same partition, readers can see a mixture of both, and there is no way to tell which files belong together. Crash halfway through a large overwrite and the directory is simply inconsistent, with no log to reconstruct the previous state.
Small files compound the problem. Every micro-batch that lands a few hundred kilobytes creates another file, and soon a query over one day's data opens thousands of files, each with its own footer and row groups. Read latency climbs even though the underlying dataset has not changed in meaning.
Delta addresses both. Writes become commits recorded in a log, so a reader always sees a consistent snapshot. Compaction commands merge small files into larger ones. The result is that the same storage path can be read concurrently with writers, versioned, and restored without keeping a separate backup copy.
The transaction log, concretely
Every Delta table carries a hidden _delta_log directory containing numbered JSON files, one per commit. Each entry lists the files added and removed by that operation along with metadata such as partition values and sizes. The current table state is simply the accumulation of entries up to the latest version.
warehouse/sales/_delta_log/
00000000000000000000.json initial create
00000000000000000001.json append of 12 parquet files
00000000000000000002.json remove 3 files, add 1 compaction output
00000000000000000003.json schema change adds column discount
Two guarantees follow directly. Readers take a snapshot of the log version and ignore anything newer, so concurrent writers cannot corrupt a query. Writers must win an optimistic concurrency check on the same version, so a conflicting update fails rather than silently interleaving. This is why a Delta table can be written to by a streaming job while analysts query it without locks.
Incremental ingestion with Auto Loader
Auto Loader discovers new files as they arrive using cloud notifications where available, and falls back to directory listing where they are not. It keeps its own state in a checkpoint location, so a restart does not rescan the entire landing zone.
stream = (
spark.readStream.format("cloudFiles")
.option("cloudFiles.format", "parquet")
.option(
"cloudFiles.schemaLocation",
"abfss://[email protected]/sales",
)
.option("cloudFiles.inferColumnTypes", "true")
.option("cloudFiles.schemaEvolutionMode", "addNewColumns")
.load("abfss://[email protected]/sales/")
)
(
stream.writeStream.format("delta")
.outputMode("append")
.option("checkpointLocation",
"abfss://[email protected]/sales_sink")
.option("mergeSchema", "true")
.trigger(availableNow=True)
.toTable("sales.bronze_sales")
)
availableNow=True runs everything currently available and then stops, which is the right shape for a scheduled batch that should behave like streaming without leaving a cluster idle. Because discovery state lives in the checkpoint, files are processed exactly once even if the job restarts.
Choosing a schema evolution rule
Schema change is inevitable, and Delta lets you decide what happens rather than inheriting whatever a writer does by accident.
| Situation | Setting | Outcome |
|---|---|---|
| New nullable column appears | addNewColumns | Column added, existing rows read as null |
| Column removed upstream | default fail | Query fails loudly, forcing a review |
| Type widened, string to double | mergeSchema on write | Readers see the new type after commit |
| Type narrowed or renamed silently | none | Write rejected unless schema overwritten deliberately |
| Untrusted source adds columns | evolution off | Files quarantined for inspection |
Additive changes are safe because downstream queries that do not reference the new column are unaffected. Type changes are not, since they can silently alter how numbers are parsed. Keep mergeSchema off for untrusted sources and turn it on explicitly for curated ones where a change has been reviewed.
Time travel for debugging and audits
Because every commit is retained, any previous version can be queried directly. That turns a bad transformation from a restore-from-backup event into a two-line read.
from delta.tables import DeltaTable
yesterday = (
spark.read.format("delta")
.option("timestampAsOf", "2026-01-04 23:59:59")
.table("sales.fact_sales")
)
diff = yesterday.exceptAll(spark.table("sales.fact_sales"))
print(f"{diff.count()} rows present yesterday but missing today")
table = DeltaTable.forName(spark, "sales.fact_sales")
table.restoreToVersion(42)
Restore is a new commit that reverts the table, not an overwrite of history, so it is itself auditable. The same mechanism supports regulatory snapshots and point-in-time reporting without a separate snapshot pipeline.
Keeping tables fast: OPTIMIZE, ZORDER, VACUUM
Without maintenance, a streaming table accumulates hundreds of small files per hour. OPTIMIZE compacts them into sizes that the scan engine handles efficiently, and it is safe to run while readers are active because it produces a normal commit.
spark.sql("OPTIMIZE delta.`sales.fact_sales`")
spark.sql("OPTIMIZE delta.`sales.fact_sales` ZORDER BY (customer_key, sale_date)")
spark.sql("VACUUM delta.`sales.fact_sales` RETAIN 168 HOURS")
Z-ORDER co-locates values of the chosen columns across files so that data skipping can eliminate files during a filtered query. Pick columns that appear together in filters, usually a join key plus a date. Applying it to every column defeats the purpose, because no single ordering can satisfy all of them.
VACUUM removes files no longer referenced by the log, which is what allows old versions to be forgotten. Keep the default seven-day retention unless you have a specific reason to shorten it, and never run VACUUM on a table while a long-running job might still be reading an older snapshot, because that job will start failing on missing files.
Cost and performance trade-offs
| Command | Cost driver | Run when | Risk if skipped |
|---|---|---|---|
OPTIMIZE | Cluster compute per compaction | File count per partition grows | Slower reads, higher scan cost |
ZORDER | Extra passes over data | Queries filter on stable columns | Full scans where skipping was possible |
VACUUM | I/O plus storage reclaimed | Storage budget pressure | Files retained longer than needed |
| Statistics collection | Small, per write | Automatic | Poor file skipping |
Schedule OPTIMIZE on a daily cadence per active table and drive Z-ORDER from query patterns rather than habit. Combine these with Auto Loader's checkpoint hygiene, and a Delta table will keep reading at close to its original speed months after ingestion began.
Common Mistakes
Letting every micro-batch write its own tiny file
Fix: Run OPTIMIZE on a schedule and tune trigger intervals so batches land in the tens of megabytes.
Enabling mergeSchema globally for untrusted sources
Fix: Apply schema evolution only to curated paths and quarantine files that introduce unexpected columns.
Running VACUUM with a very short retention period
Fix: Keep at least seven days so concurrent readers of older snapshots are not broken mid-query.
Z-ORDERing every column because it sounds optimal
Fix: Choose only columns that frequently appear together in filters, otherwise the rewrite buys nothing.
Best Practices
- Keep checkpoint and data paths separate so neither interferes with the other
- Use availableNow triggers for scheduled jobs that should behave like streaming
- Record the Delta version in load metadata for audit and replay
- Combine Z-ORDER with partition pruning, it works on top of pruning rather than replacing it
- Alert on file count per partition as an early warning that compaction is overdue
Questions interviewers ask about Delta Lake
đ¯Interview Tip
Be ready to explain why a Delta write can fail with a concurrent modification error. The optimistic concurrency check compares log versions; if two writers commit against the same base version, one is rejected and must retry, which is exactly the behaviour that prevents silent lost updates.
Interview Questions
Q1: How does time travel work in Delta Lake?
Every write creates a new version recorded in _delta_log. Readers address a version or timestamp to snapshot the table at that point, which enables point-in-time queries, audits, and restore operations without separate backup copies.
Q2: How does Auto Loader differ from listing files on a schedule?
Auto Loader uses cloud file notifications where supported and maintains discovery state in a checkpoint, so each file is processed once with no full directory rescan. Manual listing requires custom idempotency logic and re-lists the entire path on every run.
Q3: What does VACUUM do and when is it dangerous?
It deletes files no longer referenced by the transaction log, which reclaims storage but removes the ability to read those old versions. Running it with too short a retention period breaks any reader still using a snapshot older than the window.
Q4: How do you handle a breaking schema change?
Handle it as a deliberate migration: apply the new schema in a controlled write with overwriteSchema, update downstream contracts, and redeploy consumers together. Never rely on automatic merging for a type change or a rename, because readers will misinterpret the data.
Key Takeaways
- The transaction log, not the Parquet files, provides consistency and versioning
- Auto Loader state in a checkpoint is what makes ingestion restart-safe
- Additive schema changes are safe, type changes require a reviewed migration
- Time travel replaces backup-and-restore for most incident recovery
- OPTIMIZE fixes file sprawl, Z-ORDER fixes filter efficiency, VACUUM reclaims space
- Run maintenance on a schedule and watch file counts as the trigger