Micro-batch processing

Also known as: micro-batching

On this page 7

Micro-batch processing is a technique for handling streaming data in which incoming events are collected into small batches over short, fixed intervals, typically from a few hundred milliseconds to a few minutes, and each batch is then processed as a bounded unit of work. It sits between classic batch processing and true record-at-a-time stream processing, giving near-real-time results while reusing the simpler execution and recovery model of batch systems.

The approach, also called micro-batching, became widely known through Spark Streaming and later Spark Structured Streaming, and the same idea appears in data warehouse ingestion, change data capture loaders and serverless consumers of Kafka or Amazon Kinesis. Its defining trade-off is that latency can never be lower than the batch interval, in exchange for high throughput and easy exactly-once guarantees.

How micro-batch processing works

A micro-batch engine runs a repeating cycle driven by a trigger. At each trigger the engine asks the source, such as a Kafka topic, which offsets are new since the last batch, records that offset range in a write-ahead log, reads exactly those records, runs the transformation as a small batch job and commits the results and the new offsets together. The next cycle then starts from the committed position.

Because every batch is defined by a deterministic offset range, a failed batch can simply be replayed. The engine rereads the same records, recomputes the same output and, provided the sink is idempotent or transactional, overwrites any partial result. This is the core reason micro-batching makes exactly-once semantics comparatively easy to achieve.

The steps of a single cycle are summarized in the following table.

StageWhat happensWhy it matters
TriggerTimer or completion of the previous batch starts a cycleSets the minimum achievable latency
Offset planningEngine fixes the start and end offsets per partitionMakes the batch reproducible
LoggingPlanned range is written to a checkpoint logAllows replay after a crash
ExecutionBatch job reads, transforms and aggregates the recordsReuses optimized batch operators
CommitOutput and offsets are committed, state is checkpointedPrevents duplicates and data loss
Stages of one micro-batch cycle

Stateful operations such as running counts, windowed aggregations and stream joins keep their state between batches in a state store, usually backed by local disk or RocksDB and checkpointed to durable storage. Each batch reads the previous state, updates it with new records and writes a new version.

Key parameters and how to tune them

Tuning a micro-batch pipeline is mostly about balancing batch interval, batch size and processing time. The pipeline is stable only while the average time to process a batch stays below the interval; once processing takes longer, batches queue up, end-to-end delay grows and the job eventually falls behind the source.

ParameterTypical rangeEffect of increasing it
Trigger interval0.5 s to 15 minHigher throughput, higher latency, fewer small files
Max records per batchThousands to millionsSmoother catch-up after outages, larger memory peaks
Shuffle partitionsTens to hundredsMore parallelism, more scheduling overhead
Watermark delaySeconds to hoursAccepts later data, keeps more state in memory
Checkpoint frequencyEvery batch or every few batchesFaster recovery, more storage writes
Main tuning parameters in micro-batch systems

A practical rule is to keep processing time at roughly 50 to 80 percent of the interval, which leaves headroom for traffic spikes, garbage collection pauses and occasional slow tasks. Rate limits on records per batch act as a form of backpressure, so a pipeline that restarts after a long outage does not try to swallow hours of backlog in one oversized batch.

Micro-batching compared with batch and continuous streaming

Micro-batching is best understood as a point on a latency spectrum rather than a separate paradigm. Classic batch jobs process large bounded datasets hours apart, while continuous engines such as Apache Flink and Kafka Streams process each record as it arrives. The table compares the three models.

PropertyBatch processingMicro-batch processingContinuous streaming
Typical latencyMinutes to hoursSub-second to minutesMilliseconds
Unit of workWhole dataset or partitionSmall bounded batchSingle record or small buffer
Fault toleranceRerun the jobReplay the offset rangeDistributed snapshots of state
Throughput per coreVery highHighHigh, with more tuning
Operational complexityLowModerateHigher
Example enginesApache Spark batch, MapReduceSpark Structured StreamingApache Flink, Kafka Streams
Batch, micro-batch and continuous stream processing

The boundary is not absolute. Continuous engines also buffer records internally for efficiency, and Spark offers an experimental continuous mode. The distinction that matters is whether scheduling and recovery happen per batch or per record and snapshot. Micro-batching also maps naturally onto the Lambda architecture, because the same batch code can serve both the speed layer and the historical layer.

When to choose micro-batch processing

Micro-batching fits workloads where seconds of delay are acceptable and correctness, throughput and simple operations matter more than the last few hundred milliseconds. The decision table below captures typical cases.

RequirementRecommended modelReason
Dashboards refreshed every 30 to 60 sMicro-batchLatency target exceeds the batch interval
Loading events into a data lake or warehouseMicro-batchFewer, larger files and transactional commits
Fraud scoring within 50 ms of a card swipeContinuous streamingInterval alone would exceed the budget
Nightly financial reconciliationBatchNo real-time need, simplest operation
Team already runs Spark batch jobsMicro-batchSame API, skills and cluster
Choosing a processing model by requirement

Limitations and common pitfalls

The main limitation is the latency floor: an event arriving just after a trigger waits for the full interval plus processing time. Several other problems appear repeatedly in production pipelines.

  • Small-file explosion occurs when short intervals write many tiny files to object storage; compaction jobs or longer intervals fix it.
  • Growing batch durations signal that processing no longer fits the interval; scale out, simplify the logic or raise the interval.
  • Unbounded state builds up when windowed aggregations lack a watermark, so late data handling must be configured explicitly.
  • Non-idempotent sinks break exactly-once guarantees during replay; use transactional writes or upserts keyed on a stable identifier.
  • Fixed scheduling overhead per batch, often tens to hundreds of milliseconds, makes very short intervals inefficient.

Event-time correctness is a separate concern. Micro-batches are cut by processing time, not by event time, so windows defined on event timestamps still need watermarks to decide when a window is complete and how long to wait for late data.

In everyday language

Imagine a mail carrier who could deliver each letter the moment it is posted, or collect letters for a whole day and deliver them once. Micro-batch processing is the middle path: the carrier picks up every few seconds and delivers each small bundle together.

The result is almost real time, with much less effort per item. If something goes wrong, the carrier knows exactly which small bundle to redo, so nothing gets lost or delivered twice.

Seen in the real world

An online retailer streams about 5,000 clickstream events per second from its website into a Kafka topic with 24 partitions. The analytics team needs a sales and traffic dashboard that is never more than a minute old and a clean copy of all events in its data lake.

The team runs a Spark Structured Streaming job with a 30-second trigger interval. Each batch reads roughly 150,000 events, removes duplicates by event identifier, computes per-product counts in 5-minute event-time windows with a 10-minute watermark and writes the results with transactional commits to lake tables. Average processing time is about 12 seconds, which leaves comfortable headroom for evening traffic peaks.

When a worker node failed during a holiday sale, the job restarted from its checkpoint and replayed only the interrupted batch. The dashboard fell behind by under two minutes and recovered automatically, with no lost or double-counted orders.