Skip to the page
Tecyfy

Databricks interview question · hard

You have a streaming job that writes to a Delta table. You want to ensure that small files are compacted regularly to optimize query performance. How can you achieve this within the streaming process, without requiring separate batch jobs?

The short answerTurn on optimized writes and auto compaction for the table.

The full answer

Turn on optimized writes and auto compaction for the table. Optimized writes make each micro-batch write fewer, larger files, and auto compaction merges remaining small files right after a write succeeds, on the same cluster, so no separate compaction job is needed. On Unity Catalog managed tables, predictive optimization can also run OPTIMIZE for you.

Why streaming creates small files. Every micro-batch writes at least one file per task, so a stream triggered every few seconds produces thousands of small files. Queries then spend more time opening files than reading data.

1. Set the table properties

ALTER TABLE events SET TBLPROPERTIES (
  'delta.autoOptimize.optimizeWrite' = 'true',
  'delta.autoOptimize.autoCompact' = 'true'
);
  • Optimized writes shuffle data before writing so each partition gets fewer, larger files. The cost is a small shuffle in each write.
  • Auto compaction runs after a write succeeds, synchronously on the cluster that did the write, and combines small files that have not been compacted before. It adds a little time to the micro-batch rather than a separate job.

On Databricks both are already on by default for MERGE, UPDATE and DELETE, so streams that upsert with foreachBatch and MERGE already benefit. Plain appends from a stream need the properties set.

You can also turn them on for a whole session with spark.databricks.delta.optimizeWrite.enabled and spark.databricks.delta.autoCompact.enabled.

2. Use predictive optimization

For Unity Catalog managed tables, predictive optimization runs OPTIMIZE (and VACUUM) automatically in the background on serverless compute, deciding when a table needs it. It is independent of auto compaction; the two can be used together.

3. Write less often

A longer trigger interval, such as .trigger(processingTime="1 minute"), writes fewer, bigger files. Choose the longest interval your freshness needs allow.

4. Lay the data out well

Use liquid clustering (CLUSTER BY) rather than partitions on high-cardinality columns. Over-partitioned tables are a common cause of small files, because each micro-batch writes a file into every partition it touches.

With these in place, a streaming table stays fast to query without a separate nightly compaction job, though for very large tables an occasional OPTIMIZE (or predictive optimization) is still worthwhile.

Last updated 16 October 2026

Asked next