Batch, Streaming, and Real-Time Serving Trade-offs Questions
Reasoning about when to use batch, micro-batch, or continuous streaming and how to serve low-latency analytics: latency, cost, complexity, and correctness trade-offs; lambda vs kappa architectures; and reprocessing semantics. Covers real-time aggregation, freshness vs consistency trade-offs, and reconciling streaming results with batch ground truth, including geospatial and high-throughput real-time workloads under eventual consistency. The data-systems judgment topic for choosing and reconciling batch versus real-time approaches, distinct from the hands-on streaming transport itself.
Design a near-real-time dashboarding pipeline for product metrics that must keep event-ingestion latency under 5 seconds while sustaining 20,000 events/sec. Size the ingestion and processing layers, choose a storage layer for serving (fast OLAP vs. real-time store), and describe the caching strategy that gets read latency under a second for dashboard queries.
Sample Answer
Direct answer
At 20,000 events/sec with a sub-5-second ingestion latency target, the ingestion layer needs only a small number of partitions to handle the raw throughput comfortably, and the harder engineering problem is actually the read side: getting thousands of dashboard queries per second down to sub-second latency, which a caching layer in front of the serving store solves cheaply if the read pattern is repetitive (as dashboard traffic usually is).
Structured elaboration
Sizing the ingestion layer: with an average event size and a per-partition throughput ceiling (both stated assumptions here, since real limits depend on your specific broker and hardware), compute the number of partitions from both the message-rate cap and the raw-bytes-per-second cap, and provision for the larger of the two plus headroom for skew and growth.
Processing layer: a stream processor consuming those partitions, doing whatever light transformation/aggregation the metrics require, with parallelism matched to the partition count so no single consumer instance becomes a bottleneck. At this volume (about 19 MB/s), this is a modest cluster, not a large one; the sub-5-second latency bar is comfortably achievable without exotic tuning.
Storage layer for serving: choose a real-time-oriented store (a fast OLAP engine like ClickHouse/Druid, or a low-latency key-value/columnar store) over a traditional data warehouse for the serving path, since warehouses are optimized for large scans, not thousands of small, low-latency point/aggregate queries per second.
Caching strategy for sub-second reads: dashboard read traffic is highly repetitive (many viewers polling the same small set of metric keys), which makes it an excellent caching target. Put a cache (in-memory, short TTL matched to your freshness bar) in front of the serving store, so only a small fraction of reads (cache misses) actually hit the store, and even those hit a store designed for low-latency point reads.
Worked example
Partition sizing (assumptions: 1 KB average event size; a single partition sustains 10,000 msgs/sec or 10 MB/sec, whichever binds first):
EVENTS_PER_SEC, AVG_EVENT_BYTES = 20_000, 1_000
PER_PARTITION_MSG_CAP, PER_PARTITION_MB_CAP = 10_000, 10
throughput_mb_s = EVENTS_PER_SEC * AVG_EVENT_BYTES / (1024*1024) # 19.07 MB/s
partitions_by_msg_rate = -(-EVENTS_PER_SEC // PER_PARTITION_MSG_CAP) # ceil -> 2
partitions_by_mb_rate = -(-throughput_mb_s // PER_PARTITION_MB_CAP) # ceil -> 2
print(f"throughput_mb_s={throughput_mb_s:.2f}")
print(f"partitions_by_msg_rate={partitions_by_msg_rate}")
print(f"partitions_by_mb_rate={partitions_by_mb_rate}")
Executed output: raw throughput is 19.07 MB/s; both the message-rate and byte-rate caps independently require 2 partitions; provisioning 3 (50% headroom) comfortably absorbs skew and near-term growth without needing to repartition soon.
Cache sizing (assumptions: 500 distinct dashboard metric keys, 50 viewers per key, polling every 5 seconds, 98% cache hit rate, 150ms store read latency vs. 3ms cache read latency):
read_qps = 500 * 50 / 5 # 5,000 reads/sec, all viewers
store_qps = read_qps * (1 - 0.98) # 100 reads/sec actually hit the store
blended_latency_ms = 0.98*3 + 0.02*150 # 5.94 ms
print(f"read_qps={read_qps:.0f}")
print(f"store_qps={store_qps:.0f}")
print(f"blended_latency_ms={blended_latency_ms:.2f}")
Executed output: 5,000 total read QPS collapses to only 100 QPS actually reaching the serving store once the cache absorbs 98% of reads, and the blended expected latency across all reads is 5.94 ms, comfortably under a one-second target even though a single uncached store read (150ms) is far from instant on its own.
Trade-offs and pitfalls
The mistake to avoid is over-provisioning the ingestion layer out of an instinct that "20,000 events/sec sounds like a lot," when the arithmetic shows it's a genuinely modest throughput for a modern streaming platform; the real engineering effort here is on the read side, where naively hitting the serving store for every dashboard poll (5,000 QPS with no cache) would either require a much more expensive store or blow the sub-second latency target under load. The other pitfall is setting the cache TTL longer than the stated freshness requirement to squeeze out a higher hit rate; the cache's TTL has to be bounded by the same 5-second latency promise the whole system is built to keep, not chosen purely to optimize the cache-hit number.
Compare the Lambda and Kappa architectures for combining batch and streaming processing: what components does each have, what operational complexity does maintaining two codepaths (Lambda) versus a single replayable streaming codepath (Kappa) actually cost you, and when would you choose one over the other?
Sample Answer
Direct answer
Lambda architecture runs two separate codepaths, a batch layer for accuracy and a speed layer for freshness, and merges their outputs at serving time. Kappa architecture collapses that into a single streaming codepath with full replay capability, using reprocessing instead of a second batch system to get accuracy. Lambda buys you a battle-tested batch layer as a correctness backstop at the cost of maintaining two implementations of your business logic; Kappa buys you one codebase at the cost of your streaming engine and storage having to support cheap, full-history replay.
Structured elaboration
Lambda's components: a batch layer (recomputes accurate views from the full historical log, usually on a schedule), a speed layer (a stream processor providing low-latency, possibly-approximate views of very recent data), and a serving layer that merges the two, typically overwriting the speed layer's view for a time window once the batch layer's more-accurate result for that window lands.
Kappa's components: a single durable, replayable event log (the source of truth) and one stream-processing codebase that both handles live traffic and, when you need to fix a bug or backfill, gets pointed at an earlier offset and replayed through the same code.
The real cost of Lambda is that your batch and speed layers are two independent implementations of the same business logic, in whatever language/framework each layer uses, and they can silently drift apart (a bug fixed in one and not the other, a metric defined slightly differently). That duplication is the actual argument against it, not raw complexity for its own sake.
The real cost of Kappa is that it pushes all correctness work onto the streaming engine: state management, exactly-once guarantees, and cheap full-history replay for potentially years of data, all inside one system, which is a harder engineering problem than "run a batch job over the same log."
Worked example
A team building fraud scoring that needs both a fast online signal and periodic full retraining on corrected historical labels is a natural Lambda fit: the speed layer scores in real time with best-effort features, the batch layer recomputes ground truth nightly once labels settle, and a small serving-layer reconciliation step swaps in the corrected value. A team building a single, well-defined metrics pipeline (say, per-minute active users) where the exact same logic should always apply, live or replayed, is a better Kappa fit: one Flink job computes it, and a bug fix just means replaying the log from the point of the bug, not fixing and re-deploying two systems.
Trade-offs and pitfalls
A common mistake is choosing Kappa because "one codebase" sounds obviously simpler, without checking whether the team's streaming engine and storage can actually afford cheap, full-history replay at their retention window and data volume; if replay is slow or expensive, Kappa quietly turns into "one codebase, but reprocessing takes three days," which defeats the purpose. The opposite mistake is defaulting to Lambda out of caution and then never actually keeping the two layers' logic in sync, which produces the exact dual-codepath drift Lambda is often criticized for.
Explain the real differences between batch processing and stream processing for a production data platform: latency, throughput, cost, operational complexity, and correctness. Give one concrete workload that clearly favors each approach, and describe a scenario where a hybrid of the two is the right call.
Sample Answer
Direct answer
Batch and streaming are two ways of answering the same question (what does the data say right now) at different points on the latency/cost/complexity curve. Batch reads a large accumulated chunk on a schedule; streaming processes each event as it arrives. Pick batch by default and reach for streaming only when a specific business decision genuinely needs data fresher than the next scheduled run can provide.
Structured elaboration
Latency. Batch is minutes to a day (whatever the schedule is); streaming is sub-second to a few seconds, bounded mainly by how long you wait for late data (the watermark).
Throughput. Batch amortizes overhead across a huge chunk, so it is usually the cheaper way to move the same total volume of data. Streaming pays a small per-event tax (serialization, network hops, state lookups) on every single record, so the same total throughput costs more compute.
Cost. A batch job runs, finishes, and releases its compute. A streaming job holds compute (and often memory-resident state) 24/7 whether or not there's a burst of traffic, so streaming infrastructure has a real always-on cost floor that batch does not.
Operational complexity. Batch failure recovery is simple: rerun the job. Streaming failure recovery has to reason about partial state, checkpoints, exactly-once vs at-least-once delivery, and consumer lag, which means more moving parts, more monitoring surface, and a team that has to understand event-time semantics, not just SQL.
Correctness. Batch naturally sees all the data for a period before computing anything, so late-arriving records are simply part of the input. Streaming has to make an explicit decision about how long to wait for late data (allowed lateness) before it emits a result, which means a streaming aggregate can legitimately differ from the eventual batch recompute of the same period.
| Axis | Batch | Streaming |
|---|---|---|
| Latency | minutes to a day | sub-second to seconds |
| Throughput cost per unit volume | lower (amortized) | higher (per-event overhead) |
| Infra cost floor | zero between runs | always-on |
| Ops complexity | low (rerun on failure) | higher (state, checkpoints, lag) |
| Correctness model | sees everything before computing | must decide how long to wait for late data |
Worked example
A nightly-refreshed revenue dashboard is a clean batch case: the business consumes it once a day, a few hours of latency is invisible to the user, and a failed run just reruns. A fraud-detection system that has to block a card swipe before it completes is a clean streaming case: by the time a batch job would even start, the transaction has already succeeded or failed. A hybrid shows up constantly in practice: a company might run streaming only for the handful of metrics that trigger pages or block a transaction, and leave everything else (the other 90% of reporting) on batch, because paying the always-on cost and operational overhead of streaming for a dashboard nobody checks more than once a day has no payoff.
Trade-offs and pitfalls
The most common mistake is treating this as a technology choice instead of a latency-requirement choice: teams reach for Kafka and Flink because streaming sounds more modern, then discover they've taken on 24/7 operational burden for data nobody looks at more than once a day. The second most common mistake is the opposite: assuming batch is always simpler, when a batch job that has grown large enough to blow its nightly window is itself an operational risk. The right first question is always "what decision does this data drive, and how fresh does it actually need to be to drive that decision correctly," not "which technology is state of the art."
Design a hybrid pipeline where nightly batch jobs compute historical values and a streaming job updates recent values on top of them. How do you reconcile the overlap between the two (streamed recent updates vs. batch historical values), prevent double-counting once the batch job catches up, and ensure the combined result is monotonic and reproducible?
Sample Answer
Direct answer
The key design decision is a clean, well-defined handoff boundary: the streaming path owns everything newer than a fixed cutoff (say, the last 24-48 hours), the batch path owns everything older, and every value in the combined output is tagged with which path produced it, so "double counting" becomes structurally impossible rather than something you have to detect after the fact.
Structured elaboration
The handoff boundary: pick a cutoff time window (based on how long your data typically takes to fully settle, including late arrivals and any correction processes) before which data is considered "batch-owned." The streaming path only ever writes to the window newer than that cutoff; the nightly batch job only ever (re)writes to the window at or older than the cutoff. Neither path writes into the other's territory, which is what actually prevents double-counting, rather than trying to deduplicate after merging two overlapping outputs.
Reconciling overlap: as the cutoff advances each day (yesterday's "streaming-owned" data becomes old enough to be "batch-owned" today), the batch job recomputes that newly-crossed-over window from the full, settled data and overwrites whatever the streaming path had written for it, rather than appending to it. This overwrite, not merge, is what keeps the combined table free of duplicates.
Monotonicity and reproducibility: because the batch job always fully recomputes (and overwrites) its owned windows from the immutable source log, rerunning it for the same historical window always produces the same result, which is what "reproducible" means here. Monotonicity (values only get more correct over time, never inconsistently jump around) follows from the batch job being the sole writer once a window crosses the cutoff; the streaming path never touches that window again.
Implementation detail that matters: this requires the storage layer to support an efficient overwrite-by-partition operation (most warehouse and lakehouse formats do, via a partition-level replace or a MERGE keyed on the time window), not an append-only log, otherwise "overwrite" becomes an expensive full-table rewrite.
Worked example
With a 24-hour cutoff: today's data (0-24 hours old) is served entirely from the streaming path's continuously-updated aggregate. Tomorrow, once today's data is fully settled, the nightly batch job recomputes today's aggregate from the raw log and overwrites the partition the streaming path had been writing, at which point that partition is permanently batch-owned and the streaming path stops writing to it. A user querying "yesterday's total" always gets the batch-recomputed, final value; a user querying "today's total" always gets the streaming path's continuously-updating value, and the two never both contribute to the same partition.
Trade-offs and pitfalls
The common mistake is designing this as an append-and-deduplicate system (both paths write, then a dedup step tries to reconcile duplicates by, say, keeping the most recent write per key), which is fragile: dedup logic itself can have bugs, and it obscures which value is authoritative at any given moment. The partition-ownership-by-time-window design avoids that whole class of bug by construction. The remaining risk is choosing a cutoff that's too short for how long your data actually takes to settle, in which case the batch job will be overwriting a partition that hasn't fully arrived yet, reintroducing exactly the streaming-vs-batch discrepancy this design is meant to eliminate; the cutoff should be set from measured late-arrival data, not a round number picked by convention.
A product team requests near-real-time personalization requiring sub-100ms reads and 1,000 writes/sec. Decide between a stateful streaming architecture and a micro-batch near-real-time approach: compare latency, cost, operational complexity, and developer velocity, and propose a recommended architecture with a migration plan from whatever exists today.
Sample Answer
Direct answer
At sub-100ms reads and 1,000 writes/sec for personalization, a micro-batch approach almost certainly cannot meet the latency bar (even a very tight micro-batch adds tens to hundreds of milliseconds of batching delay before a write is even visible), so this points toward a stateful streaming architecture, with the real design work being how to serve those sub-100ms reads cheaply, not whether streaming is required.
Structured elaboration
Why micro-batch struggles here: a micro-batch interval tight enough to keep end-to-end latency under 100ms (accounting for batch collection time plus processing time) starts to lose most of micro-batching's efficiency advantage, since you're now paying near-continuous compute anyway, without the operational simplicity batch normally offers. At that point you've built something that behaves like streaming but without streaming's tooling for state and exactly-once handling, which is often a worse trade than just using a real streaming engine.
Latency: streaming wins clearly; a stateful stream processor updating a low-latency key-value store as writes arrive can support sub-100ms reads if the read path is a simple point lookup, not a recomputation.
Cost: streaming's always-on compute and (likely) resident low-latency storage cost more than a batch approach would, but at only 1,000 writes/sec, this is a modest-scale system either way, so the absolute cost difference is unlikely to be the deciding factor here, the latency requirement is.
Operational complexity: real, and worth naming honestly: state management, checkpointing, and monitoring for a stream-processing system require different skills than a batch pipeline, and this is a genuine cost of the recommendation, not something to gloss over.
Developer velocity: initially slower to build (more moving parts to get right), but once the pattern is established, adding new personalization signals to an existing streaming pipeline is usually incremental, versus repeatedly re-tuning batch intervals as latency requirements tighten over time.
Worked example
Suppose the current system is a batch job that recomputes personalization signals hourly. The migration plan: (1) stand up a stream processor that consumes the same event source and computes the personalization state incrementally, writing to a low-latency store (Redis or DynamoDB-style key-value store) sized for the 1,000 writes/sec and sub-100ms read requirement; (2) run it in shadow, comparing its computed values against the batch job's hourly output for the same users, to validate correctness before it serves any real reads; (3) cut over reads to the new store behind a feature flag, monitoring read latency directly (not just throughput) to confirm the sub-100ms bar holds under real production load, not just in testing; (4) once validated, retire the hourly batch job, or repurpose it as a periodic correctness-reconciliation check rather than the primary compute path.
Trade-offs and pitfalls
The common mistake is trying to squeeze micro-batch tighter and tighter to chase a latency target it wasn't designed for, rather than recognizing the 100ms bar as a genuine architectural signal to move to streaming; there's a point (well before 100ms) where shrinking the batch interval stops buying meaningful latency improvement and just adds overhead. The other mistake is under-investing in the shadow-validation step in the migration plan, since a stateful streaming system that's subtly wrong (a race condition in how state updates, an edge case in cold-start behavior for a brand-new user with no prior state) is much harder to debug after it's serving live personalization decisions than to catch in a shadow comparison against the known-correct batch baseline.
Unlock Full Question Bank
Get access to all 9 Batch, Streaming, and Real-Time Serving Trade-offs interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.