Batch & Stream Processing
- Decide when a workload should be batch, streaming, or both, based on latency, completeness and cost
- Explain event time vs processing time, tumbling/sliding/session windows, and how watermarks trade latency for completeness
- Explain how stream processors achieve exactly-once state and what it takes to extend that to external sinks
- Design reconciliation, real-time fraud features and flash-sale dashboards, and compare Lambda and Kappa architectures
TL;DR
- Batch processes a bounded dataset (yesterday's transactions) — high throughput, simple correctness, latency of hours. Streaming processes unbounded data continuously — latency of seconds, but you must reason about time, order and state.
- Use event time (when it happened) for anything financial or analytical; processing time (when you saw it) is only for operational metrics.
- Windows: tumbling (fixed, non-overlapping), sliding/hopping (overlapping), session (gap-based). Watermarks declare "events older than W are (probably) all here", which is when windows fire; late events need an explicit policy.
- Exactly-once in streaming means state and output reflect each event once, achieved by checkpointing state together with source offsets, plus transactional or idempotent sinks. Side effects (SMS, payments) still need idempotency.
- Lambda = batch layer + speed layer (two codebases); Kappa = one streaming pipeline, reprocess by replaying the log. Unified engines make Kappa-style designs the common default.
- Banks still run critical batch (end-of-day, interest, statements, reconciliation of daily settlement files) while adding streaming for fraud, notifications and real-time limits.
Why it matters
- Reconciliation: card schemes, acquirers and clearing houses deliver settlement files on a schedule; the bank matches them against its ledger every day and investigates breaks. This is a classic batch job with strict correctness and audit requirements (see Reconciliation & Settlement).
- Fraud: an authorization must be scored in tens of milliseconds using features such as "transactions on this card in the last hour" or "distinct merchants in 10 minutes". Those are sliding-window aggregates maintained by a stream processor (see Real-time Fraud Detection Pipeline).
- E-commerce analytics: during 11.11, leadership watches GMV per minute and stock burn-down live; finance needs exact daily totals the next morning. Same events, two latency/accuracy requirements.
- Interviews: "ad click aggregation", "real-time leaderboard", "fraud detection" and "design a reconciliation system" are all batch/stream questions underneath.
Core concepts
Bounded vs unbounded data
| Batch | Stream | |
|---|---|---|
| Input | Bounded (a day's files, a table snapshot) | Unbounded (Kafka topic, CDC stream) |
| Latency | Minutes to hours | Milliseconds to seconds |
| Completeness | All data present before computing | Data keeps arriving, possibly late or out of order |
| State | Recomputed per run | Long-lived, must be checkpointed |
| Failure recovery | Rerun the job (idempotently) | Restore checkpoint and replay from offsets |
| Typical tools | Spark, MapReduce/Hadoop, SQL on a warehouse, dbt, Airflow | Flink, Kafka Streams, Spark Structured Streaming, Beam runners |
Batch: MapReduce and Spark
- MapReduce (Google, 2004; Hadoop) made large-scale batch fault-tolerant on commodity machines: map tasks transform records into key/value pairs, the framework shuffles all values for a key to one reducer, reducers aggregate. Every stage writes to disk, which is robust but slow.
- Spark generalises this into a DAG of transformations over partitioned datasets (DataFrames/SQL), keeps intermediate data in memory where possible, and recovers lost partitions by recomputing from lineage. Shuffles (joins, group-bys) are the expensive part; partitioning and skew handling dominate tuning.
- Batch hygiene for money:
- Idempotent runs: a job for business date D overwrites the output partition for D, so reruns are safe; never "append again".
- Business date and cut-off: banks define a business day with cut-off times and holiday calendars; "yesterday" in UTC is rarely the right partition.
- Orchestration: dependencies, retries, SLAs and backfills in a scheduler (Airflow or similar).
- Data quality checks: row counts, control totals (sum of amounts must match the file trailer), schema checks — fail loudly before downstream consumers use bad output.
Stream processing engines
| Kafka Streams | Apache Flink | Spark Structured Streaming | |
|---|---|---|---|
| Deployment | Library inside your service (JVM) | Separate cluster (JobManager + TaskManagers) | Spark cluster |
| Model | Record-at-a-time | Record-at-a-time | Micro-batches (continuous mode limited) |
| State | Local stores (RocksDB) backed by changelog topics | Keyed state (heap or RocksDB), distributed snapshots | State store with checkpoints |
| Event time and watermarks | Supported (grace periods) | First-class, rich | Supported |
| Exactly-once | Kafka transactions (exactly_once_v2) | Checkpoints + transactional / idempotent sinks | Checkpoints + idempotent sinks |
| Scale unit | Input partitions | Operator parallelism, key groups | Partitions / tasks |
| Fit | Kafka-in, Kafka-out microservices | Complex event-time pipelines, large state, CEP | Teams already on Spark, unified batch + streaming |
Go is less common for the heavy engines (they are JVM-first), but Go services often produce the events, consume the results, and implement simpler stateful consumers.
Event time vs processing time
- Event time: when the payment was authorized on the terminal or the order was placed in the app.
- Ingestion time: when the event reached the broker.
- Processing time: when your operator handled it.
They diverge because of mobile clients going offline, network retries, partner files delivered hours later, consumer lag and replays. A card transaction at 23:59:58 that reaches you at 00:00:03 belongs to the earlier day's totals for settlement — computing by processing time would put it in the wrong day, and a replay would compute different numbers from the same events. Event-time processing makes results reproducible.
Windows
event time -> 10:00 10:01 10:02 10:03
tumbling 1m [---------)[---------)[---------)
hopping 2m/1m [--------------------)
[--------------------)
[--------------------)
session 30s x x x x xx x x
gap [------) [------) [)
- Tumbling: fixed size, non-overlapping. "GMV per minute", "settlement totals per business date".
- Sliding / hopping: fixed size, overlapping, advancing by a slide interval. "Transactions per card in the last 60 minutes, updated every minute". (True per-event sliding windows can be implemented with per-key event buffers or bucketed counters.)
- Session: grows while events keep arriving within a gap; closes after inactivity. "Shopping session length", "login session anomalies".
- Global / count windows: custom triggers, for example "every 100 events".
Watermarks and late data
A watermark with value W asserts that no more events with event time ≤ W are expected. A window [start, end) fires when the watermark passes end.
- Bounded out-of-orderness: watermark = max event time seen − allowed delay (for example 10 s). Larger delay → more complete results, higher latency.
- Allowed lateness / grace period: keep window state a little longer and emit updated results for late events.
- Late events beyond that: route to a side output for correction, never silently drop money events.
- Idle partitions hold the overall watermark back (it is the minimum across inputs); configure idleness detection.
- Choose per use case: a fraud feature can fire early and update; a settlement total must wait for completeness (often a batch on the full day's file anyway).
Exactly-once in streaming
- Flink injects checkpoint barriers into the stream; each operator snapshots its state when the barrier passes (an asynchronous variant of the Chandy–Lamport snapshot). A checkpoint records source offsets + operator state consistently. On failure, the job restores the last checkpoint and replays from those offsets — state reflects every event exactly once.
- Output is the hard part. Either a transactional sink that pre-commits on the barrier and commits when the checkpoint completes (two-phase commit; Kafka transactions are the common case, and downstream consumers must read with
read_committed), or an idempotent sink that upserts by a deterministic key (merchant_id + window_start) so replays overwrite with the same value. - Kafka Streams achieves the same for Kafka-to-Kafka topologies with transactions that atomically write outputs, state changelogs and consumer offsets.
- External side effects (send SMS, call a payment API) are not covered; make them idempotent with event ids (see Idempotency & Exactly-Once).
- Cost: checkpoint overhead and, for transactional sinks, output latency of about one checkpoint interval.
Lambda vs Kappa
- Lambda (Nathan Marz): the batch layer periodically recomputes accurate views from the immutable master dataset; the speed layer covers the gap with low-latency, possibly approximate results; the serving layer merges them. Robust, but two implementations of the same logic that must agree.
- Kappa (Jay Kreps, 2014): one streaming implementation; to fix a bug or change logic, start a new version of the job reading the log from the beginning, let it catch up, then switch readers. Requires long log retention (or tiered storage) and an engine that handles event time correctly.
- In practice: unified engines (Flink, Spark, Beam) run the same code in batch and streaming modes, and table formats such as Apache Iceberg, Delta Lake and Apache Hudi let streaming jobs write tables that batch jobs read. Many banks still keep authoritative batch for regulated outputs and add streaming for real-time needs — a pragmatic Lambda.
Use cases through the bank and e-commerce lens
Reconciliation (batch first).
Run per business date, idempotently, with full audit of inputs and outputs. For instant payments, banks increasingly add intraday or continuous (streaming) matching so breaks surface within minutes.
Fraud features (streaming). Per card, account, device and merchant: count and sum in the last 5 min / 1 h / 24 h, distinct merchants or countries in 10 min, time since last transaction. A stream job maintains them keyed by entity and writes to a low-latency online feature store (often Redis or a key-value store) that the scoring service reads within its tens-of-milliseconds budget. The same feature definitions must be computed in batch over history for model training, or you get training/serving skew.
Sale-day analytics (both). Tumbling one-minute windows over OrderPlaced for live GMV and orders per minute (fire early, approximate is fine); next-morning batch over the order database or warehouse for the exact numbers finance reports. For the ad-click flavour of this problem, see SDI Vol. 2 Ch. 6.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Batch (Spark / SQL warehouse) | Simple correctness, cheap per record, easy backfills | High latency | Reconciliation, statements, regulatory reports, model training |
| Stream (Flink / Kafka Streams) | Low latency, continuous results | Time semantics, state management, operational complexity | Fraud features, alerts, live dashboards, CDC transforms |
| Micro-batch (Spark Structured Streaming) | Familiar Spark APIs, decent latency | Latency floor of the batch interval | Teams on Spark needing seconds-level latency |
| Processing-time windows | Simple, no watermarks | Non-reproducible, wrong under lag/replay | Operational metrics only |
| Event-time windows + watermarks | Correct, reproducible | Latency vs completeness tuning | Anything financial or analytical |
| Transactional sink | Exactly-once output | Output delayed by checkpoint interval | Kafka-to-Kafka pipelines, ledgers of aggregates |
| Idempotent upsert sink | Simple, low latency | Needs deterministic keys | Aggregates into DB/KV stores |
| Lambda | Accurate batch + fast speed layer | Two codebases | Regulated outputs plus real-time views |
| Kappa | One codebase, replay to fix | Long retention, engine maturity | Event-sourced or log-centric platforms |
In practice
- Parallelism follows partitions. A Kafka topic with 24 partitions caps a Kafka Streams app at 24 active tasks; key the topic by the aggregation key (card id, merchant id) to avoid repartitioning.
- State size: fraud features for 20 M cards × several windows is GBs of state; use RocksDB-backed state, TTLs on idle keys, and incremental checkpoints.
- Checkpoint interval: seconds to a minute; shorter means faster recovery and lower sink latency, more overhead.
- Backpressure propagates upstream in Flink; watch it alongside consumer lag (see Message Queues & Event Streaming).
- Reprocessing plan: before go-live, decide how you will replay a day of events after a bug — new job version, separate output, compare, switch.
- A tiny event-time tumbling window with a watermark in Go shows the mechanics (real engines add checkpointing and parallelism):
package window
import "time"
type Event struct {
Key string // e.g. merchant id
Amount int64 // minor units
At time.Time // event time
}
type Result struct {
Key string
WindowStart time.Time
Count int64
Sum int64
}
// Tumbling aggregates by event time and emits a window once the watermark
// (max event time seen minus maxDelay) has passed the window's end.
type Tumbling struct {
size time.Duration
maxDelay time.Duration
maxSeen time.Time
open map[time.Time]map[string]*Result
Late func(Event) // side output for events behind the watermark
}
func NewTumbling(size, maxDelay time.Duration) *Tumbling {
return &Tumbling{size: size, maxDelay: maxDelay, open: make(map[time.Time]map[string]*Result)}
}
func (t *Tumbling) watermark() time.Time { return t.maxSeen.Add(-t.maxDelay) }
// Add ingests one event and returns any windows that are now complete.
func (t *Tumbling) Add(e Event) []Result {
start := e.At.Truncate(t.size)
if !start.Add(t.size).After(t.watermark()) { // window already closed
if t.Late != nil {
t.Late(e)
}
return nil
}
byKey, ok := t.open[start]
if !ok {
byKey = make(map[string]*Result)
t.open[start] = byKey
}
r, ok := byKey[e.Key]
if !ok {
r = &Result{Key: e.Key, WindowStart: start}
byKey[e.Key] = r
}
r.Count++
r.Sum += e.Amount
if e.At.After(t.maxSeen) {
t.maxSeen = e.At
}
return t.fire()
}
func (t *Tumbling) fire() []Result {
wm := t.watermark()
var out []Result
for start, byKey := range t.open {
if !start.Add(t.size).After(wm) { // end <= watermark: complete
for _, r := range byKey {
out = append(out, *r)
}
delete(t.open, start)
}
}
return out
}
Write each emitted Result with an upsert keyed by (key, window_start) so a replay produces the same rows rather than double counts.
Common pitfalls
- Processing-time aggregation for money. Symptom: daily totals change when you rerun the job or after consumer lag; transactions near midnight land in the wrong day.
- Watermark too aggressive. Symptom: a growing side output of "late" events and totals that never match the batch numbers.
- Watermark stalled by an idle partition. Symptom: windows stop firing for one region or merchant group although events flow elsewhere.
- Unbounded state. Symptom: checkpoint size and recovery time grow every week; add TTLs and bound session windows.
- At-least-once sink with additive writes. Symptom: double-counted GMV after every restart. Use idempotent upserts or transactional sinks.
- Non-idempotent batch reruns. Symptom: interest accrued twice for a date after an operator reruns a failed job.
- Side effects inside a reprocessing pipeline. Symptom: replaying a day of events re-sends thousands of customer notifications.
- Training/serving skew. Symptom: a fraud model that scored well offline underperforms in production because online features are computed differently.
- Wrong business date / timezone. Symptom: reconciliation breaks every day around the cut-off time.
Interview angle
- Where it appears: ad click aggregation, metrics/monitoring systems, fraud detection, real-time dashboards, leaderboards, and "how do you reconcile with the card scheme?".
- Strong answer covers: batch vs stream justified by latency and completeness requirements; event time with watermarks and a late-data policy; window types; state and checkpointing; exactly-once boundaries and sink idempotency; reprocessing strategy; Lambda vs Kappa trade-off; how results are served.
- Follow-ups: "An event arrives 10 minutes late — what happens?", "How do you avoid double counting after a crash?", "How do you fix a bug in yesterday's aggregates?", "Why not compute fraud features with SQL queries on the OLTP database?", "How do batch and real-time numbers reconcile?"
- Red flags: using processing time for business metrics, claiming exactly-once end to end without idempotent sinks, no plan for late data, running analytics queries on the production ledger.
Self-check
1. Why should a merchant's daily settlement total be computed in event time, and what goes wrong with processing time?
Settlement belongs to the business date when the transaction happened, and results must be reproducible for audit. With processing time, a transaction delayed past midnight by lag or a retry lands in the next day, and rerunning or replaying produces different numbers from the same events. Event time with an explicit cut-off and late-data handling gives stable, explainable totals.
2. Explain watermarks and the trade-off in choosing the allowed delay.
A watermark asserts that events with event time up to W have (probably) all arrived; windows ending before W can fire. A watermark of "max seen − delay" with a large delay waits longer, so results are more complete but later; a small delay fires sooner but more events arrive late and need updates or side outputs. Choose per use case: early-and-update for fraud features, completeness for financial totals.
3. Pick a window type for each: GMV per minute, transactions per card in the last hour, a user's browsing session.
GMV per minute: tumbling one-minute windows. Transactions per card in the last hour: a sliding/hopping window (for example 60 minutes advancing every minute) or per-key bucketed counters for per-event freshness. Browsing session: session windows with an inactivity gap (for example 30 minutes).
4. How does Flink achieve exactly-once state, and what else is needed for exactly-once output to PostgreSQL?
Checkpoint barriers flow with the data; each operator snapshots state when the barrier passes, and the checkpoint records source offsets with the state. On failure, the job restores state and replays from the recorded offsets, so state reflects each event once. For PostgreSQL output, either use a two-phase-commit sink tied to checkpoints or, more commonly, idempotent upserts keyed by a deterministic id such as (merchant_id, window_start) so replays overwrite rather than add.
5. Scenario: a bug inflated yesterday's real-time GMV numbers. Describe a Kappa-style fix.
Fix the code and deploy a new version of the job with a new output table, reading the topic from an offset (or timestamp) before the affected period. Let it catch up, compare its output with the batch/warehouse numbers, then switch dashboard readers to the new output and retire the old job. This requires the topic's retention to cover the replay period and the pipeline to be free of external side effects.
6. Why do banks still rely on batch for reconciliation even with streaming available?
Counterparty inputs (scheme settlement files, statements) arrive in batches on fixed schedules, the business date has defined cut-offs, results must be complete, reproducible and auditable, and batch jobs are simpler to validate with control totals and reruns. Streaming complements it with intraday matching for instant payments, but the end-of-day batch remains the authoritative close.
Exercise
- Generate a synthetic stream of 1 M card transactions over a simulated day with realistic out-of-order delays (most under 2 s, 1% up to 2 minutes, a few hours late). Write them to Kafka keyed by
card_id. - Using the Go
Tumblingwindow (or Kafka Streams/Flink if you prefer), compute per-merchant one-minute totals with watermark delays of 0 s, 10 s and 2 min; count late events for each. - Write a batch job (SQL over a PostgreSQL table, or Spark) computing exact per-merchant daily totals by event time. Compare with the streaming results and explain each difference.
- Kill and restart your streaming consumer mid-run and confirm (using upserts keyed by window) that totals do not double count.
Done looks like: a table of watermark delay vs late events vs difference from batch totals, plus evidence that restarts do not change results.
Further reading
- Tyler Akidau, Slava Chernyak, Reuven Lax, Streaming Systems (O'Reilly) — event time, watermarks, windows, exactly-once.
- Akidau et al., "The Dataflow Model" (VLDB 2015).
- Dean & Ghemawat, "MapReduce: Simplified Data Processing on Large Clusters" (OSDI 2004).
- Zaharia et al., "Resilient Distributed Datasets" (NSDI 2012) — the Spark paper.
- Carbone et al., "Lightweight Asynchronous Snapshots for Distributed Dataflows" (2015) — Flink's checkpointing.
- Jay Kreps, "Questioning the Lambda Architecture" (O'Reilly Radar, 2014); Nathan Marz & James Warren, Big Data (Manning).
- Designing Data-Intensive Applications (Kleppmann), Ch. 10 "Batch Processing" and Ch. 11 "Stream Processing".
- System Design Interview, Vol. 2 (Xu & Lam), Ch. 6 "Ad Click Event Aggregation".
- Apache Flink and Kafka Streams official documentation.
Related
- Message Queues & Event Streaming — the logs these pipelines read and write.
- Reconciliation & Settlement — the domain behind the batch use case.
- Real-time Fraud Detection Pipeline — streaming features in a full design.
- Fraud & Risk Systems — how features feed decisions.
- Time, Clocks & Ordering — why event time is hard.
- Idempotency & Exactly-Once — sinks and side effects.
- Event-Driven Architecture, CQRS & Event Sourcing — replayable logs as the system backbone.
- Big Data Platforms & the Lakehouse — the storage layer and table formats these pipelines write into.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).