Blog

Stream vs Batch Processing: Why the Same Events Give Two Different Answers

Stream vs batch processing results disagree for predictable reasons: event time, late data, duplicates, joins. How to find which number is wrong, and why.

  • stream vs batch processing
  • stream processing
  • batch processing
  • event time
  • root cause analysis

The real-time dashboard says 48,210 orders yesterday. The nightly report says 48,950. Someone opens an incident and asks which one is right.

The uncomfortable answer is that both may be correct for the question each one was built to answer, and that a difference on its own is not an incident. A streaming job and a batch job that read the same events are different machines with different ideas of time, completeness and failure. They should be expected to disagree a little. The incident is when nobody can explain the difference, because then nobody can say whether it is the usual few late events or a consumer that has been silently dropping data since Tuesday.

Stream vs batch processing is usually discussed as an architecture choice. This article treats it as an investigation problem. Martin Kleppmann’s Designing Data-Intensive Applications has chapters on both models and a closing section on how they combine, and between them they explain nearly every way the two answers drift apart: event time against processing time, late events, delivery guarantees, joins that depend on when they ran, and reprocessing. Each of those is a hypothesis you can test with evidence.

Table of Contents

Two models of the same data

Kleppmann describes batch processing through the lens of Unix tools and MapReduce: a job reads a bounded, fixed input, produces an output, and does not modify its input. That last property is the important one for incidents. If a batch job has a bug, you can fix the code and run it again over the same input, and get the right answer. The book calls this tolerance of human mistakes, and it is the main reason batch output is often treated as the reference.

Stream processing works on unbounded input. Events arrive continuously, the job processes them as they come, and its results are always provisional because more events may still arrive. It keeps state, remembers its position in each input, and must decide when it has seen “enough” of a time period to emit a result.

BatchStream
InputBounded and fixed when the job startsUnbounded; arrives continuously
Notion of timeUsually the event timestamps in the dataEvent time, processing time, or a mix
CompletenessWhatever had arrived when the job ranWhatever had arrived when a window closed
After a crashRerun the job from the same inputResume from a checkpoint or offset; may reprocess or skip
Fixing a bugRerun over the same input with new codeReplay from the log, if it is still retained
Typical incidentRan over incomplete input; ran twice; ran with the wrong parametersDropped late events; duplicates after restart; lag on one partition

Neither model is “the correct one”. A batch job run at 02:00 has its own completeness cut-off; it simply sits later than the stream’s. Data arriving at 03:00 for yesterday is missing from both until somebody reruns something.

Six reasons two answers differ

Almost every stream-versus-batch discrepancy comes from one or more of six mechanisms. They make different predictions, which is what makes them testable.

MechanismWhich side is usually lowerWhat it predicts at record level
Different time attribute (event time vs ingestion or processing time)EitherThe same events are assigned to different days or hours
Late events dropped by a closed windowStreamMissing-in-stream events all arrived well after their event time
Duplicates from at-least-once deliveryBatch, if it deduplicatesThe same event ID appears more than once in stream output
Different window or day boundaries (time zone, inclusive or exclusive end)EitherDifferences concentrated at the edges of windows
Join against changing reference dataNeither; attributes differSame events, different values for a joined field such as region or price
Different code or filtersEitherDifferences correlate with an attribute that one side filters

The last row deserves a word. In many organisations the stream job and the batch job were written by different teams, at different times, in different languages. They are separate implementations of what was meant to be one definition. A filter added to one and not the other is a perfectly ordinary cause of a permanent discrepancy, and it is found by reading both, not by tuning watermarks.

Event time, processing time and whose clock

Tyler Akidau’s essay Streaming 101 popularised the distinction most streaming systems now use: event time is when something happened; processing time is when the system observed it. In an ideal world they would be equal. In practice the gap between them varies with network delays, buffering, consumer lag, mobile devices that were offline, and upstream outages. The gap is not constant, and it is not small during exactly the periods you are likely to be investigating.

A batch job over yesterday’s data almost always groups by event time, because the timestamp is in the record. A stream job may group by event time, by processing time, or by the time the message reached the broker, depending on how it was written. If the two jobs use different attributes, they assign the same events to different hours and different days, and their totals will disagree near every boundary.

Kleppmann adds a question that is easy to skip: whose clock produced the event time? If events come from user devices, the device clock may be wrong, deliberately or not. His suggestion is to record three timestamps: when the event occurred by the device clock, when it was sent by the device clock, and when the server received it by the server’s clock. The difference between the last two estimates the device’s clock offset, which you can then apply to the first. Without that, an event stamped two days in the future by a misconfigured phone will land in a window that does not exist yet.

The backlog that looks like a spike

One of Kleppmann’s examples is worth knowing by heart. A stream consumer is stopped for a while, perhaps for a deploy, and then restarts and works through its backlog. If the job measures rates by processing time, the stop looks like a drop to zero followed by a sudden spike, neither of which happened in the real world. If it measures by event time, the rates are correct but arrive late.

In an incident, this shows up as an alarming chart that does not match any business event. Check the consumer’s restart history and its lag before investigating the “spike”. If the shape lines up with a pause and a catch-up, the incident is in the chart’s definition, not in the business.

Late events and windows that close too early

A stream job that groups by event time has to decide when a window is complete. It cannot know for certain, because a late event can always arrive. Most frameworks use a watermark, a running estimate of how far event time has progressed, and close a window when the watermark passes its end. Events that arrive after that are stragglers.

Kleppmann describes the two reasonable options for stragglers: drop them, ideally while counting how many were dropped so the loss is visible; or publish a correction for the window that has already been emitted. Many pipelines do the first without the counting, which turns late data into silent data loss. A batch job that runs later picks those events up, so the batch answer is higher, and the difference grows on days when more events arrive late: mobile traffic after a connectivity problem, a partner that resends a backlog, an upstream outage that delays delivery.

The diagnostic is to measure lateness directly. For the day in question, how many events arrived after the stream window for their event time had closed?

-- How late did yesterday's events arrive, by event-time hour?
-- Read-only. Assumes the raw landing table keeps both event_time and ingested_at.
SELECT date_trunc('hour', event_time)                                   AS event_hour,
       COUNT(*)                                                         AS events,
       COUNT(*) FILTER (WHERE ingested_at > event_time + interval '10 minutes')
                                                                        AS arrived_after_10_min,
       COUNT(*) FILTER (WHERE ingested_at > event_time + interval '1 hour')
                                                                        AS arrived_after_1_hour
FROM   raw.order_events
WHERE  event_time >= '2026-11-02' AND event_time < '2026-11-03'
GROUP  BY 1
ORDER  BY 1;

If the stream job’s allowed lateness is ten minutes, the third column is roughly what it should have dropped. If that number matches the gap between the two answers, you have a strong hypothesis. If it is far smaller, the gap has another cause.

Delivery guarantees: duplicates, gaps and “exactly once”

Message systems describe their guarantees in three levels, and the Kafka documentation’s section on message delivery semantics is a clear statement of them: at most once (messages may be lost but are never redelivered), at least once (never lost, but may be redelivered), and exactly once (each message is processed once). The same document points out that this breaks into two problems, the guarantee for publishing a message and the guarantee for consuming it.

Most production pipelines are effectively at least once. That is a sensible default, because duplicates can be removed and lost messages cannot be recovered. It does mean that a stream job writing to a sink that is not idempotent will produce duplicates whenever it reprocesses messages, which happens after crashes, restarts, rebalances and deploys.

Kleppmann’s discussion of exactly-once is useful here. What frameworks offer is better described as effectively once: the result is as if each message were processed once, achieved through checkpointing with atomic commits, or through idempotent writes keyed by a stable ID. The guarantee usually ends at the boundary of the framework. A side effect outside it, such as an HTTP call, an email, or an insert into a database that is not part of the transaction, can still happen twice.

Where the offset is committed

The decision that determines whether failures produce duplicates or gaps is when the consumer records its position relative to when it writes its output.

Order of operationsIf the consumer crashes in betweenResult
Commit offset, then process and writeMessages after the committed offset were never writtenGaps: at most once
Process and write, then commit offsetMessages written but offset not committed are reprocessedDuplicates: at least once
Write and commit offset atomically, or write idempotently by event IDReprocessing does not change the resultEffectively once

In an investigation, find this order in the consumer code at the deployed version. Then line up the duplicate or missing events with the consumer’s restart and rebalance history. Duplicates clustered right after a restart are the at-least-once signature. Gaps clustered right after a restart point to offsets committed before the work was done.

Joins that depend on when they ran

Some discrepancies are not about counts at all. The two answers have the same events but disagree about an attribute: revenue by region, orders by product category, transactions by exchange rate. These usually come from joins against reference data that changes over time.

Kleppmann’s example is tax: an invoice should use the tax rate that applied on the date of the sale, not today’s rate. In stream processing, an enrichment join typically uses whatever the reference table holds at the moment the event is processed. A batch rerun a week later joins with the reference table as it is a week later. If a customer moved region in between, or a product changed category, or a rate was corrected, the two answers attribute the same event differently. The book points out that this makes such joins nondeterministic unless the reference data is versioned and the join picks the version that was valid at the event’s time.

The diagnostic is a record-level comparison on the joined attribute. If the differing records all involve reference rows that changed between the two runs, you have found the mechanism. The fix is a design decision, not a bug fix: decide which version of the reference data the business means, and make both jobs use that version explicitly.

Reprocessing, backfills and the third answer

The batch model’s great strength is reprocessing: fix the code, rerun over immutable input, get the right answer. Streams can do the same only while the input log is still retained. If retention is seven days and the bug started ten days ago, part of the history can only be rebuilt from somewhere else.

Kleppmann’s closing chapter discusses the lambda architecture, which runs a batch layer and a stream layer side by side and merges their results, and its main problem: the same logic has to be maintained in two systems, which is precisely how the “different code or filters” row in the table above comes about. Many teams have since moved towards a single streaming implementation that can replay history, but most real organisations still have both kinds of job, often written years apart.

Backfills add a third answer. A backfill run today for last month uses today’s code, today’s reference data and today’s view of late events. It will match neither the original stream output nor the original batch output exactly. Record which run produced which numbers, with the code version, before comparing anything. Many “discrepancies” turn out to be a comparison between a backfilled table and one that was not backfilled.

Investigating a stream and batch discrepancy

The method is hypothesis-driven debugging, and the most important step comes before any hypothesis: make the two numbers comparable.

  1. Define both numbers precisely. Which time attribute, which window boundaries and time zone, which filters, which code version, and when each was computed.
  2. Recompute one side with the other’s definition. If the batch job groups by event time in UTC and the dashboard groups by ingestion time in local time, compute the batch answer the dashboard’s way. Many discrepancies disappear here, and the finding is a definition, not a defect.
  3. Reconcile at the record level for one bounded window. Classify every difference.
  4. Map each class of difference to its mechanisms using the table above.
  5. Confirm each mechanism with independent evidence: lateness distributions, consumer restart history, code at the deployed version, reference data change history.

Reconcile records, not totals

Totals hide everything that matters. A 1.5% gap can be 1.5% of missing events, or 3% missing and 1.5% duplicated. The only way to know is to compare individual events by a stable ID.

-- Record-level reconciliation for one day: which events are in one output and not the other?
-- Read-only. Assumes both sides keep event_id; if the stream sink stores only aggregates,
-- record-level reconciliation is impossible, and that is the first finding.
WITH batch AS (
    SELECT event_id, event_time, ingested_at
    FROM   warehouse.orders_daily
    WHERE  event_time >= '2026-11-02' AND event_time < '2026-11-03'
),
stream AS (
    SELECT event_id, COUNT(*) AS copies, MIN(processed_at) AS first_processed
    FROM   realtime.order_events_sink
    WHERE  event_time >= '2026-11-02' AND event_time < '2026-11-03'
    GROUP  BY event_id
)
SELECT CASE
         WHEN s.event_id IS NULL THEN 'missing_in_stream'
         WHEN b.event_id IS NULL THEN 'missing_in_batch'
         WHEN s.copies > 1       THEN 'duplicated_in_stream'
         ELSE 'matched'
       END                                                        AS outcome,
       COUNT(*)                                                   AS events,
       ROUND(AVG(EXTRACT(EPOCH FROM (b.ingested_at - b.event_time))) / 60)
                                                                  AS avg_lateness_minutes
FROM   batch b
FULL   OUTER JOIN stream s ON s.event_id = b.event_id
GROUP  BY 1
ORDER  BY 1;

The output tells you which mechanisms are in play. Missing-in-stream events with high average lateness point to dropped stragglers. Duplicated-in-stream events point to reprocessing without idempotence; group them by first_processed to see whether they cluster around a restart. Missing-in-batch events point to the batch job’s own cut-off or a filter it applies. Matched events with different attributes point to joins.

A worked example: two errors that cancelled out

This is an illustrative example; the numbers are invented to show the method.

Symptom. The real-time orders dashboard for Monday shows about 1.5% fewer orders than the nightly batch report. On a normal day the gap is under 0.2%. Finance wants to know which number to report.

Hypotheses.

  • H1: late mobile events were dropped by the stream job’s window (late data).
  • H2: the stream job double-counted some events after a restart (duplicates).
  • H3: the dashboard and the report use different day boundaries (definition).

First test. H3 is the cheapest to check: the code for both jobs groups by event time in UTC, and the window boundaries match. H3 is rejected. The record-level reconciliation then shows three classes of difference: about 1.9% of the batch’s events are missing from the stream, about 0.4% of the stream’s events are duplicates, and the rest match.

Two mechanisms, two lines of evidence each. The missing-in-stream events have an average lateness of 47 minutes, against a configured allowed lateness of 10 minutes, and they cluster between 08:00 and 10:00, when the mobile app’s event upload service logged a backlog after a dependency outage. That supports H1, from the data and from the upload service’s logs. The duplicates all have a first processing time between 14:05 and 14:09, which matches a consumer deploy and restart at 14:05 in the deploy log. The consumer code at that version writes to the sink before committing its offset, and the sink has no unique key on event_id. That supports H2, from the data and from the code.

Finding. “Monday’s stream result was low by 1.9% because events delayed by an upload backlog arrived after the ten-minute window had closed and were dropped without being counted, and high by 0.4% because a consumer restart reprocessed four minutes of events into a sink that is not idempotent. The net gap of 1.5% understated both problems.” The batch number is the one to report for Monday. The action items are a counter for dropped late events, an idempotent sink keyed by event ID, and an alert when the gap exceeds its usual range.

The lesson generalises: a net difference is the sum of opposite errors. Without the record-level comparison the team would have found one mechanism, fixed it, and watched the gap get worse.

Building pipelines whose answers can be reconciled

Discrepancies are cheap to investigate when the evidence exists and very expensive when it does not. A few design habits make the difference:

  • Give every event a stable ID at its source, and keep it through every stage and in every sink.
  • Store both event time and ingestion time on every record, so lateness is a query, not a guess.
  • Count what you drop. Late events, malformed events and filtered events should be counted per window, so a gap can be explained by numbers the pipeline itself reported.
  • Make sinks idempotent by event ID, so reprocessing does not change results.
  • Define every metric with its time attribute and boundary, and use the same definition in both jobs, ideally the same code.
  • Version reference data used in joins, and decide which version each join should use.
  • Keep raw input long enough to replay the period you would need to rebuild after a bug.

These matter whichever tools run the jobs. An orchestrator decides when the batch job runs and whether it succeeded; it does not decide whether its answer agrees with the stream. The comparisons with Airflow and Dagster cover where orchestration ends, and the Monte Carlo comparison covers where data observability’s detection ends and investigation begins.

Frequently asked questions

What is the difference between stream and batch processing?

Batch processing runs a job over a bounded input that is fixed when the job starts, produces an output, and can be rerun over the same input to get the same result. Stream processing handles an unbounded input continuously, keeps state, and emits results that may be revised as late data arrives. Batch jobs are simpler to reason about and reprocess; stream jobs give answers sooner. Many systems use both for the same data.

Why do my real-time numbers and batch numbers not match?

The usual causes are a different time attribute (event time against processing or ingestion time), late events dropped by the stream job’s windows, duplicates from at-least-once delivery after a restart, different window boundaries or time zones, joins against reference data that changed between the two runs, and different filters in two separate implementations. A record-level reconciliation by event ID shows which of these are present, which a comparison of totals cannot.

What is the difference between event time and processing time?

Event time is when something happened, usually recorded in the event itself. Processing time is when the processing system handled it. The gap between them varies with network delays, buffering, consumer lag and offline devices. Grouping by processing time gives fast but distorted results during backlogs; grouping by event time gives correct results but requires deciding how long to wait for late events.

Does exactly-once processing mean there are no duplicates?

Within the boundary of the framework that provides it, the effect should be as if each message were processed once. Outside that boundary, duplicates are still possible: a side effect such as an HTTP call or a write to a separate database can happen again when a message is reprocessed. The reliable defence is an idempotent sink keyed by a stable event ID, so that writing the same event twice has the same result as writing it once.

Should the batch result always be treated as the source of truth?

Not automatically. A batch job reprocesses from a fixed input, which makes it easier to correct, but it has its own cut-off and can miss events that arrive after it ran. It can also share bugs or filters with the stream job, or have its own. Treat whichever result follows the agreed definition, over the most complete input, as the reference for a given question, and record which run, code version and cut-off produced it.

Two answers are fine; unexplained answers are not

A stream job and a batch job will disagree, because they make different trade-offs about time and completeness. That is the design working. What turns a difference into an incident is not knowing why: not being able to say how much is late data, how much is duplication, and how much is a definition nobody wrote down. The fix is rarely to make the two jobs identical. It is to make every difference attributable, so the next investigation takes minutes and ends with a sentence finance can repeat.

Datasets that should agree but do not is a broader problem than stream and batch, and derived data out of sync follows it to caches, indexes and warehouse tables. For the general shape of silent shortfalls, see your pipeline succeeded and the rows are missing, and for jobs that may not have run as intended, scheduled job troubleshooting. Decim approaches incidents like this one from code, logs and tickets, through GitHub, Google Cloud Logging and Jira; when the deciding evidence sits in your warehouse, it writes a read-only check for your team to run rather than querying the warehouse itself.


Decim investigates incidents in your own system and returns a diagnosis where every claim links to the log line, code or check behind it, with the rejected explanations kept so your team learns why its pipelines disagree. It reads code from GitHub, logs from Google Cloud Logging and tickets from Jira, never runs SQL and never merges a fix. Learn more at decim.dev or see pricing.

Decim investigates pipeline incidents

It reads your code, logs and tickets, works through the pipeline step by step, and confirms the cause with evidence you can check: every claim links to the log line, commit or check behind it. Then it proposes the fix and writes the report.

Request a demo

← All articles