Skip to content

Stream Processing: Windows, Watermarks & State ​

“We as a field must stop trying to groom unbounded datasets into finite pools of information that eventually become complete, and instead live and breathe under the assumption that we will never know if or when we have seen all of our data …” — Tyler Akidau et al., The Dataflow Model, PVLDB 8(12), 2015

Summary: Stream processing runs a query that never finishes over data that never completes, so it must decide which clock to group by, when a group is done, and where its state lives. Focus: Event time versus processing time, windows, watermarks, triggers and lateness, state stores and changelogs, joins, exactly-once inside the processor, and what RabbitMQ and Redis can and cannot imitate. Learning goal: Predict, for any record, which window it lands in, whether it is on time, late or too late, what pane it causes, and what survives a crash; then build a correct windowed aggregation in Go and Laravel, and know when to hand the job to Kafka Streams or Flink.

This page owns the processor side of streaming: Kafka Streams and Flink concepts and their equivalents elsewhere. Delivery guarantees owns the three semantics and the Kafka idempotent producer; ordering and partitioning owns keys and partitions; event sourcing and CQRS owns projections as an architectural pattern; change data capture owns getting database changes into a stream; storage engines explains the LSM-tree inside RocksDB. Backpressure owns consumer lag and flow control.

Page map ​

If you are looking forGo to
Which timestamp to group byEvent, ingestion and processing time
Tumbling vs hopping vs sliding vs sessionWindows
When a window is "done" and why it stallsWatermarks
Early, on-time and late resultsTriggers and panes
grace, allowedLateness, side outputsLateness
RocksDB, changelog topics, KTableState
Stream-stream, stream-table, table-table joinsJoins
exactly_once_v2, checkpoint barriers, 2PC sinksExactly-once
Kafka Streams vs Flink vs ksqlDB vs Spark vs MaterializePer-engine behaviour
What RabbitMQ and Redis can do insteadBroker differences
A runnable window operator with testsGo and Lab

Everything in one minute ​

ConceptPlain wordsTiny exampleWhat goes wrong without it
Event timeWhen it happenedOrder placed 12:04:10 on a phoneA backlog moves orders into the wrong minute
Processing timeWhen the processor saw itWorker read it at 12:09:02Replays give a different answer every run
WindowA finite slice of an endless stream"orders per region per minute"Nothing ever finishes, state grows forever
Watermark"Event time has probably reached t"Max seen 12:05:00 minus 30 sYou never know when 12:04 is final
Trigger / paneWhen to emit a result for a windowOn-time pane at the watermark, then late panesOne answer too late, or no correction
Allowed lateness / graceHow long to keep a fired window open2 minutes after the window endLate data corrupts or is dropped silently
Side outputWhere too-late records goorders-too-late topicData loss that no dashboard shows
State store + changelogDurable, local window stateRocksDB plus a compacted topicA crash loses or double-counts open windows
Exactly-once in the processorOffsets, state and output commit togetherexactly_once_v2, Flink checkpointsDuplicates or holes after every restart
QuestionKafka StreamsFlinkRabbitMQRedis Streams
Window operatorwindowedBy(...)window(...) assignersNoneNone
Progress signalStream time (max timestamp seen per task)Watermarks, min over inputsNoneNone
Late-data boundGrace periodallowedLatenessHand-rolledHand-rolled
Durable stateRocksDB + changelog topicState backend + checkpointsUnacked messages, or an external storeKeys you design
ReplayYes, the topic is a logYes, from a checkpoint or savepointNo (queues); yes (RabbitMQ Streams)Yes, while entries are retained
Exactly-once scopeKafka in, Kafka outSources and 2PC sinksNoneNone
Window kindDefined byOne record belongs to
TumblingSizeExactly one window
HoppingSize + advanceSize ÷ advance windows
SlidingMaximum time differenceWindows defined by the records themselves
SessionInactivity gap, per keyOne session, which can merge with neighbours

Where it comes from ​

For years "streaming" meant a fast, approximate pipeline next to a nightly batch job that produced the correct numbers, the pairing Akidau's "Streaming 101" (O'Reilly, 5 August 2015) describes as the Lambda Architecture. His argument was that the split was a tooling gap: "I would argue that well-designed streaming systems actually provide a strict superset of batch functionality." The two missing tools were correctness (consistent, checkpointed state) and tools for reasoning about time.

The Dataflow paper (Akidau and ten Google colleagues, VLDB 2015) made the time part precise. Data is bounded or unbounded; "streaming" and "batch" describe engines, not data. A pipeline answers four questions: what is computed, where in event time, when in processing time results are materialised, and how refinements relate. Two sentences in the paper separate the axes:

“Windowing determines where in event time data are grouped together for processing.” “Triggering determines when in processing time the results of groupings are emitted as panes.”

"Streaming 102" (20 January 2016) defined watermarks and allowed lateness for practitioners. Apache Flink implemented event time and watermarks; Kafka Streams implemented windows with grace periods on top of Kafka's log; Apache Beam carries the Dataflow model as an API; ksqlDB, Spark Structured Streaming, Materialize and RisingWave expose the same ideas in SQL.

Why it exists ​

A batch job ends, so "all the data" is defined. A stream does not end, and records arrive out of order, so every aggregation over time needs an explicit policy for completeness. The fundamental trade-off is three-way: correctness, latency and cost.

Waiting longer (slow watermark, long lateness)Answering sooner (fast watermark, short lateness)
Fewer late records, more correct first answerMore late records, more corrections or drops
Higher latency for every windowLower latency for most windows
More state held (memory, RocksDB, changelog)Less state
Simpler downstream (fewer updates)Downstream must accept updated panes

The analogy used on this page: an election count. Ballots are grouped by the district and day they were cast (event time), not the day they reached the hall (processing time). The officer declares a provisional result when "enough" districts reported (watermark), publishes corrections as postal ballots arrive (late panes), and stops accepting ballots at a legal deadline (allowed lateness), after which the boxes are destroyed (state eviction). A ballot that arrives after the deadline is logged as late, not silently binned (side output).

Three misunderstandings, up front:

  1. "Streaming is approximate, batch is correct." With event time, watermarks, lateness and checkpointed state, a streaming engine reaches the batch answer and gives earlier provisional answers.
  2. "A watermark guarantees no more late data." A heuristic watermark is an estimate; late data is normal and needs a policy.
  3. "Exactly-once processing means my webhook fires once." It covers state and output inside the system; external side effects need idempotency.

What it is really about ​

A stream processor keeps three things per key and window: an aggregate, a progress estimate, and an emission state. Every record updates the first; the progress estimate (watermark or stream time) moves when inputs move; the emission state decides whether a pane goes out and when the state can be deleted.

event time (when it happened)processing time (when it is seen)ideal: seen the instant it happensheuristic watermarklate: seen after the watermarkalready passed its event timeskew = processing time - event timegrows during outages and backlogsReading the picturedots: recordsbetween line and curve: on timeleft of the curve: late datatoo fast watermark: more latedata, earlier answerstoo slow watermark: fewer latedata, answers waitallowed lateness bounds howlong state waits behind it

Each dot is a record: its x position is when it happened, its y position is when the processor saw it. Nothing is ever below the dashed diagonal, because nothing is seen before it happens. The thick curve is a heuristic watermark; dots to its left (above it) are late data. The rest of the page is about where the curve should be, what to do with dots to its left, and how to survive a crash in the middle.

An everyday picture ​

Back at the election hall: each district box is a window, the returning officer's "enough districts have reported" is the watermark, the provisional and corrected announcements are panes, the legal deadline is allowed lateness, shredding the boxes is eviction, and the late-ballot log is the side output. If one district never phones in at all, the officer cannot declare the national result; that is an idle partition holding the watermark back, and a rule such as "districts silent for an hour are presumed done" is Flink's withIdleness.

Concept catalogue ​

Bounded and unbounded data Good to know ​

In plain words: A bounded dataset has an end you can wait for; an unbounded one never does.

Common misunderstanding: "Batch engines process bounded data and streaming engines process unbounded data." The Dataflow paper keeps the words apart: a streaming engine can process a bounded file, and a batch engine can process an unbounded source in repeated chunks (micro-batches, as Spark Structured Streaming does by default).

Definition: Bounded data is finite and complete at processing time; unbounded data is infinite and never complete, so any result is relative to a completeness estimate.

text
1 Batch job:   read orders for 2026-11-25 -> all rows exist -> one final answer
2 Stream job:  read orders forever         -> rows keep coming, some from yesterday
3 Stream job:  answer for 12:04 is provisional until the watermark passes 12:05
4 Stream job:  answer may still change until 12:05 + allowed lateness

Real scenarios: a daily revenue report (bounded, batch is fine); a fraud score per card over the last 10 minutes (unbounded, needs windows); replaying a year of history through a streaming job to rebuild a table (bounded input on a streaming engine).

ProductBounded inputUnbounded input
FlinkBatch execution mode, same APIStreaming mode
Kafka StreamsA topic read from offset 0 is still treated as unboundedNative
Spark Structured StreamingDataFrame batchMicro-batch (default) streaming query
Apache BeamPCollection boundedPCollection unbounded, run on a runner

How to use it: decide whether your consumer of results can accept updates. If yes, stream; if a downstream system only takes final numbers, emit final panes only (Kafka Streams suppress, ksqlDB EMIT FINAL), or run batch.

Event time, ingestion time and processing time Must-know ​

In plain words: Event time is when something happened; ingestion time is when the broker stored it; processing time is when your code read it.

Common misunderstanding: "The Kafka record timestamp is the event time." By default it is whatever the producer set (CreateTime), which is event time only if the producer stamps it from the source. With LogAppendTime it is ingestion time.

Definition (Kafka Streams docs): event time is "the point in time when an event or data record occurred, i.e. was originally created 'at the source'"; ingestion time is when it "is stored in a topic partition by a Kafka broker"; processing time is when "the event or data record happens to be processed by the stream processing application".

text
1 12:04:10  phone creates OrderPlaced{occurred_at=12:04:10}      event time
2 12:04:10  phone has no signal; it buffers the order
3 12:08:55  phone reconnects, producer sends; broker appends    ingestion time 12:08:55
4 12:09:30  consumer group lags 35 s, processor reads it        processing time 12:09:30
5 grouping by processing time puts the order in minute 12:09, by event time in 12:04

Real scenarios: mobile apps that buffer offline; IoT devices with drifting clocks; a 10-minute consumer outage after which processing-time windows show one giant spike; a replay of last week that must produce last week's numbers; fraud rules where "three payments within 60 s" refers to when the payments happened.

Where the timestamp comes fromProduct and settingMeaning
Producer sets it (default)Kafka topic message.timestamp.type=CreateTimeEvent time if the producer stamps it from the source
Broker overwrites itKafka message.timestamp.type=LogAppendTimeIngestion time
Broker rejects future recordsKafka message.timestamp.after.max.ms (default 3600000, 1 hour) with CreateTimeBounds clock skew into the future
Broker rejects old recordsKafka message.timestamp.before.max.ms (default Long.MAX)No bound unless you set one
Processor extracts itKafka Streams TimestampExtractor / default.timestamp.extractorPayload field, record timestamp or wall clock
Processor extracts itFlink WatermarkStrategy.withTimestampAssignerEvent time from the payload or Kafka record
Auto-generated IDRedis XADD *Server clock at append: ingestion time
Consumer argumentRabbitMQ Streams x-stream-offset timestamp"message arrival time (not application-provided timestamps)"

How to use it: put occurred_at in the payload at the source, and extract it explicitly. Never group by time.Now() or now() in a consumer (the Go and Laravel "Before" snippets do exactly that). For processing-time use cases, such as monitoring the pipeline itself, processing time is correct and simpler.

Windows: tumbling, hopping, sliding and session Must-know ​

In plain words: A window cuts an endless stream into finite groups so that an aggregation can finish.

Common misunderstanding: "A sliding window is a sliding window." Kafka Streams notes: "Hopping windows are sometimes called “sliding windows” in other stream processing tools." Flink and the Dataflow paper use sliding for what Kafka Streams and ksqlDB call hopping; Kafka Streams' SlidingWindows are a different, record-driven kind.

Definition: a window assigner maps each record to zero or more windows. Kafka Streams tumbling and hopping windows "are aligned to the epoch, with the lower interval bound being inclusive and the upper bound being exclusive", for example [0;5000),[5000;10000). Kafka Streams sliding windows have both bounds inclusive. Session windows are per key and merge: "Any events processed that fall within the inactivity gap of any existing sessions are merged into the existing sessions."

Tumblingsize 5mHoppingsize 10m, hop 5mSlidingmax difference 5mSessiongap 3m per key[0,5)[5,10)[10,15)[15,20)[20,25)[25,30)each record lands in size / hop = 2 windowsKafka Streams SlidingWindows / JoinWindows: a window per record, size = max time differencea gap of inactivity closes a session; a late record can merge twoFlink and the Dataflow paper call the hopping row sliding windows; Kafka Streams keeps the academic names
text
Tumbling, size 1m, record at 12:00:59.999 -> [12:00, 12:01)
Tumbling, size 1m, record at 12:01:00.000 -> [12:01, 12:02)
Hopping, size 10m, advance 5m, record at 12:07 -> [12:00, 12:10) and [12:05, 12:15)
Session, gap 5m: 12:00 -> [12:00,12:05); 12:08 -> [12:08,12:13); late 12:04 -> merges both into [12:00,12:13)

Real scenarios: orders per minute (tumbling); a 10-minute moving average refreshed every minute (hopping); "two payments for the same card within 30 s" (sliding / join window); a user's browsing session that ends after 30 minutes of inactivity (session); a daily window in a local time zone (tumbling with an offset; ksqlDB and Kafka Streams windows are UTC epoch based, Flink accepts an offset).

ConceptKafka StreamsksqlDBFlink DataStreamSpark Structured StreamingDataflow / Beam
Fixed, non-overlappingTimeWindows.ofSizeWithNoGrace / ofSizeAndGraceWINDOW TUMBLING (SIZE ...)TumblingEventTimeWindowswindow(ts, "10 minutes")Fixed windows
Fixed, overlappingTimeWindows...advanceBy (hopping)WINDOW HOPPING (SIZE, ADVANCE BY)SlidingEventTimeWindowswindow(ts, "10 minutes", "5 minutes")Sliding windows
Record-drivenSlidingWindows.ofTimeDifferenceAndGrace, JoinWindowsJoin WITHINInterval joinNot built inNot built in
Per-key activitySessionWindows.ofInactivityGap...WINDOW SESSION (...)EventTimeSessionWindows.withGapsession_window(ts, "5 minutes")Sessions
Everything, custom triggerNot built inNot built inGlobalWindows + triggerNot built inGlobal window

How to use it: choose the window from the question ("per minute", "over the last 10 minutes", "per visit"), then choose the timestamp. The Go library on this page implements tumbling, hopping and session assigners with exactly these boundaries, and its tests pin the half-open edges.

Watermarks Must-know ​

In plain words: A watermark is the processor's running estimate of "how far event time has got", used to decide that a window is complete.

Common misunderstanding: "The watermark is the newest timestamp seen." It is usually the newest timestamp minus an allowance for disorder, and across several inputs it is the minimum, so one slow input holds everything back.

Definition: Streaming 102: "A watermark with a value of time X makes the statement: “all input data with event times less than X have been observed.”" Flink: "A Watermark(t) declares that event time has reached time t in that stream". A perfect watermark is possible only with full knowledge of the input; "Heuristic watermarks use whatever information is available about the inputs ... to provide an estimate". The Dataflow paper names both failure modes: watermarks are "sometimes too fast, meaning there may be late data that arrives behind the watermark", and "sometimes too slow", since one can be "held back for the entire pipeline by a single slow datum."

text
     partition 0 max   partition 1 max   watermark = min(max) - 30s
1    12:00:10          (none)            none: p1 has no data yet
2    12:00:10          12:00:15          11:59:40
3    12:01:40          12:01:35          12:01:05 -> [12:00,12:01) fires
4    12:04:10          12:01:35 (silent) 12:01:05 -> p1 holds everything back
5    p1 silent >= idleness (1m)          12:03:50 -> idle p1 ignored, windows close
6    p1 sends 12:00:50                   12:03:50 -> watermark never moves back; record too late

That table is the real output of go run ./after in the lab.

Real scenarios: a Kafka topic with 12 partitions, one of which only receives traffic from a small country at night (idle partition); a backfill job that reads one partition much faster than another (watermark alignment); a mobile fleet whose clocks drift by minutes (the out-of-orderness bound must cover it, or the producer must reject skew).

BehaviourFlinkKafka StreamsSpark Structured StreamingRisingWave
Watermark sourceWatermarkStrategy.forBoundedOutOfOrderness(d) (periodic) or a punctuated generatorNo watermark object: per-task "stream time" = max timestamp seenwithWatermark("ts", "10 minutes"): max event time minus delayWATERMARK FOR col AS col - INTERVAL ... on a source
Several inputsOperator event time is "the minimum of its input streams’ event times"Task processes partitions by timestamp; max.task.idle.ms waits for empty onesGlobal watermark = min by default; spark.sql.streaming.multipleWatermarkPolicy=maxPer source
Idle inputwithIdleness(Duration) marks a split idleStream time does not advance without recordsSlow stream holds the minPer source
Fast inputwithWatermarkAlignment(group, maxDrift, interval) pauses fast splitsNot applicableNot applicableNot applicable
Kafka-awarePer-partition watermarks inside the Kafka sourcePer partition (task) by designPer queryPer source

How to use it: set the out-of-orderness bound from measured skew (p99 of processing time minus event time), register partitions on assignment so an empty one holds the watermark, and enable idleness detection where partitions can go quiet. In the Go library, Register, Forget and Config.Idleness do exactly those three things.

Triggers, panes and accumulation modes Important ​

In plain words: A trigger decides when to publish a result for a window; each publication is a pane; the accumulation mode decides whether a later pane repeats the total or only the change.

Common misunderstanding: "A window emits once." In Kafka Streams, "windowed computations update their results continuously" unless you add suppress(Suppressed.untilWindowCloses(...)); in Flink, the default EventTimeTrigger "fires once the watermark passes the end of a window" and fires again for each late element within allowed lateness.

Definition: Dataflow refinement modes: Discarding, where "window contents are discarded, and later results bear no relation to previous results"; Accumulating, where "window contents are left intact in persistent state, and later results become a refinement of previous results"; Accumulating & Retracting, which also emits "a retraction for the previous value" before the new value. Early panes (processing-time triggers before the watermark), the on-time pane (at the watermark) and late panes (after) can all be combined.

watermarkOpenrecords accumulateOn-time panewatermark reaches endLate panesend to end + latenessEvictedstate deletedendend + latenessaccumulating: full countdiscarding: only the deltarecord for this window= too late -> side outputKafka Streams: graceFlink: allowedLateness
text
Window us [12:00,12:01), accumulating, lateness 2m
1 watermark 12:01:05 -> on-time pane#0 orders=1 cents=900
2 late record 12:00:40 arrives -> late pane#1 orders=2 cents=1700   (sink overwrites)
Same window, discarding
1 on-time pane#0 orders=1 cents=900
2 late pane#1 orders=1 cents=800                                    (sink adds)
Session merge, accumulating & retracting
1 panes for [12:00,12:05) and [12:08,12:13)
2 bridging record -> pane [12:00,12:13) orders=3, retracts both earlier sessions

Real scenarios: a dashboard that shows a provisional count every 10 s and a final count later (early + on-time + late panes); a billing sink that must see exactly one final number (suppress / EMIT FINAL); a sum written to a key-value store (accumulating, upsert); a counter in a downstream system that can only add (discarding); sessions written to a table (retractions needed, because a merge changes the window key).

ProductDefault emissionFinal-only optionAccumulation
Kafka StreamsEvery update, rate-limited by the record cache (statestore.cache.max.bytes, commit.interval.ms)suppress(Suppressed.untilWindowCloses(...)) (KIP-328)Accumulating (a KTable per window)
ksqlDBEMIT CHANGESEMIT FINALAccumulating
FlinkEventTimeTrigger: on watermark, and again per late elementCustom trigger / no latenessDepends on the window function; PurgingTrigger discards
Spark Structured StreamingOutput mode updateOutput mode append (final rows only)Accumulating per mode
Beam / DataflowWatermark triggerWatermark trigger, no late firingsaccumulatingFiredPanes / discardingFiredPanes
Go library (this page)On-time pane at watermark, late panes per AdvanceSet AllowedLateness to 0Accumulating or Discarding, Pane.Retracts for sessions

How to use it: pick the mode from the sink. An upsert-by-window-key sink wants accumulating panes; an append-only counter wants discarding; anything that indexes by window bounds needs retractions for sessions. Make the sink idempotent either way, because a restart can repeat the last pane.

Allowed lateness, grace period and side outputs Must-know ​

In plain words: Allowed lateness is how long a window that already fired keeps accepting late records; after that its state is deleted and new records for it are refused.

Common misunderstanding: "Late data is lost data." Late data inside the allowed lateness is counted and causes a late pane. Only data later than that is dropped, and a good pipeline sends it to a side output instead of losing it silently.

Definition: Streaming 102 describes it as "placing a bound on how late any given record may be (relative to the watermark) for the system to bother processing it; any data that arrive after this horizon are simply dropped." Flink: elements "that arrive after the watermark has passed the end of the window but before it passes the end of the window plus the allowed lateness, are still added to the window", and "By default, the allowed lateness is set to 0." Kafka Streams: "a record is discarded if its timestamp dictates it belongs to a window, but the current stream time is greater than the end of the window plus the grace period."

text
window [12:00,12:01), allowed lateness 2m, watermark moves:
1 wm 12:00:50  record 12:00:20 -> on time
2 wm 12:01:05  -> on-time pane
3 wm 12:02:30  record 12:00:40 -> late, accepted, late pane
4 wm 12:03:00  -> end + lateness reached: state evicted
5 wm 12:03:10  record 12:00:50 -> too late -> side output topic orders-too-late

Real scenarios: mobile orders that arrive hours late after a flight (route them to a side output and reconcile nightly); a regulator report where every late record must be counted (long lateness, or batch reconciliation of the side output); a real-time alert that is useless after 5 minutes (short lateness, drop to side output).

ProductKnobDefaultToo-late handling
Flink.allowedLateness(Duration)0Dropped, or .sideOutputLateData(OutputTag) then getSideOutput
Kafka StreamsofSizeAndGrace(size, grace), ofSizeWithNoGraceChosen per window; the ...WithNoGrace factories set no graceDiscarded: "will not be processed in that window"
ksqlDBGRACE PERIOD in the WINDOW clause"a default of 24 hours when no grace period is specified"Not included in the result
Spark Structured StreamingwithWatermark delayNoneRows older than the watermark may be dropped
Go library (this page)Config.AllowedLateness0Result.Outcome == TooLate, caller side-outputs

How to use it: use one eviction rule for both state deletion and refusal (end + lateness <= watermark), so an evicted window can never be resurrected with a partial count. The Go operator's expired function is that single rule; the test TestAllowedLatenessAccumulatingRefinesThenEvicts checks that a refused record leaves only a tombstone behind.

State stores, changelogs and the stream-table duality Must-know ​

In plain words: Window counts, join buffers and tables live in a local key-value store on the processor's disk, and every change is also written to a Kafka topic so that another machine can rebuild the store.

Common misunderstanding: "State is in memory, so a restart starts from zero" or "state is in Kafka, so reads go over the network." In Kafka Streams the default persistent store is local RocksDB ("Stores its data on local disk") and the remote copy is a changelog used only for recovery.

Definition: Kafka Streams "maintains a replicated changelog Kafka topic in which it tracks any state updates", one partition per store instance, with "Log compaction ... enabled on the changelog topics". The stream-table duality: "A stream can be considered a changelog of a table, where each data record in the stream captures a state change of the table." KStream is a record stream, KTable is the table view of a changelog stream (latest value per key, partitioned), GlobalKTable is a full copy of a table on every instance. Flink keeps keyed state in a state backend (HashMapStateBackend on the heap by default, or EmbeddedRocksDBStateBackend, the one that "offers incremental checkpoints") and snapshots it in checkpoints; state is sharded by Key Groups, of which there are "exactly as many ... as the defined maximum parallelism".

text
1 task 0_3 counts orders for partition 3 in RocksDB (window key -> count)
2 every update is also produced to app-store-changelog partition 3
3 the instance dies; partition 3 is reassigned to another instance
4 new task 0_3 replays changelog partition 3 into a fresh RocksDB
5 a standby replica (num.standby.replicas=1) would already be warm: no long replay

Real scenarios: enriching orders with the latest customer row (KTable from a compacted customers topic); a currency rate table small enough to copy everywhere (GlobalKTable); a counting job whose changelog takes 20 minutes to restore, solved with standby replicas; RocksDB disk filling up because windows are never evicted (no grace, no retention).

ConcernKafka StreamsFlinkHand-rolled (Go on this page)
Local storeRocksDB (persistent, default) or in-memoryHeap or embedded RocksDBGo maps
DurabilityCompacted changelog topic per storeCheckpoints to durable storageCompacted changelog written in the same transaction
Fast failovernum.standby.replicas, warm-up replicasLocal recovery, incremental checkpointsNot implemented: full replay
Upgrade with stateSame application.id, compatible topologySavepointsChangelog format is yours to version
Sharding unitTask per input partitionKey GroupOperator per input partition

How to use it: keep state bounded (eviction, retention), name stores so internal topics are stable across topology changes, and size the changelog restore: restore time is roughly changelog bytes ÷ restore throughput, so standby replicas matter for large stores. Storage engines explains RocksDB's compaction and write amplification.

Joins and co-partitioning Important ​

In plain words: A stream join pairs records that share a key; because both sides are endless, a stream-stream join only pairs records whose timestamps are close.

Common misunderstanding: "Any two topics with the same key can be joined." Kafka Streams requires co-partitioning for equi-joins: "The input topics of the join (left side and right side) must have the same number of partitions", and all producers must use the same partitioning strategy.

Definition: "KStream-KStream joins are always windowed joins, because otherwise the size of the internal state store used to perform the join ... would grow indefinitely." KStream-KTable joins "are always non-windowed joins" and perform a lookup of the table's current value per stream record. KTable-KTable equi-joins are non-windowed and produce a new KTable. Co-partitioning is "not required when performing KTable-KTable Foreign-Key joins and Global KTable joins." When an operation changes the key (selectKey, map, groupBy), Kafka Streams writes through an internal repartition topic so records with the new key reach the task that owns that key's state.

text
Stream-stream join, JoinWindows 5m, key = payment_id
1 12:00:00 left  PaymentAuthorized(p1)
2 12:03:00 right PaymentCaptured(p1)    -> joined: |12:03 - 12:00| <= 5m
3 12:09:00 right PaymentCaptured(p2)    -> left PaymentAuthorized(p2) at 12:02: no match, outside window
Stream-table join, key = customer_id
1 KTable customers: c7 -> {tier: gold}
2 KStream orders: o1{customer c7}       -> o1 enriched with tier gold (value at processing)

Real scenarios: authorisation and capture events matched within 10 minutes (stream-stream); orders enriched with customer tier (stream-table); exchange rates copied to every instance (stream-GlobalKTable, no co-partitioning); an orders topic with 12 partitions joined to customers with 6 partitions (fails co-partitioning: repartition one side).

JoinKafka StreamsFlinkksqlDBNeeds a window?
Stream-streamjoin/leftJoin/outerJoin with JoinWindowsInterval join, window joinJOIN ... WITHINYes
Stream-tableKStream.join(KTable)Temporal / lookup joinStream-table joinNo
Table-tableKTable.join(KTable), foreign-key joinRegular join (state grows)Table-table joinNo
Stream-global tableKStream.join(GlobalKTable, keyMapper, joiner)Broadcast stateNot applicableNo

How to use it: create topics that will be joined with the same partition count and key; when you re-key, expect a repartition topic and its extra write and read; for small reference data use a global table and avoid the repartition.

Exactly-once inside the processor Must-know ​

In plain words: The processor commits "I read up to here", "my state is now this" and "I emitted that" as one unit, so a crash never shows half of it.

Common misunderstanding: "Exactly-once means each record is processed once." Records can be processed twice after a failure; what is guaranteed is that the committed effect inside the boundary appears once.

Definition: Kafka Streams with processing.guarantee=exactly_once_v2 (brokers 2.5 or newer) uses Kafka transactions to "ensure that commits on the input topic offsets, updates on the state stores, and writes to the output topics will be completed atomically". With exactly-once, commit.interval.ms defaults to 100 ms, consumers use isolation.level="read_committed" and producers enable.idempotence=true. Flink injects checkpoint barriers: "Barriers never overtake records, they flow strictly in line", and with a two-phase commit sink "The starting of a checkpoint represents the “pre-commit” phase of our two-phase commit protocol"; the sink commits only after the whole checkpoint completes.

Kafka Streams, exactly_once_v2input topicpartition 3task 0_3state storeRocksDBwindow countschangelog p3 (compacted)output topic p3__consumer_offsetsone transaction: all three become visible together,or none do (read_committed consumers)restore after a move: replay the changelog into a new RocksDBFlink, checkpoint barriers + 2PC sinkflowbarrier ncheckpoint n+1checkpoint n1 sources inject barrier n2 operators snapshot state3 sink pre-commits its transaction4 JobManager: checkpoint complete5 sink commits; restart rolls back to nNeither covers an HTTP call or emailsent from inside the processor
text
Kafka Streams / the Go kafka snippet, one transaction:
1 begin
2 consume orders p3 offsets 100..149, update window state
3 produce panes -> orders-per-region-minute p3
4 produce state changes -> orders-windower-changelog p3
5 send offsets 150 for the group, commit
6 crash before 5 -> abort; restart reads from 100, state rebuilt from changelog

Real scenarios: a revenue-per-minute topic that finance reads with read_committed; a Flink job writing to Kafka with exactly-once delivery; a Flink job writing to a database via a sink that does not take part in 2PC (at-least-once plus idempotent upserts); a processor that also calls a payment API (no exactly-once for that call).

ProductMechanismBoundaryCost
Kafka Streamsexactly_once_v2, transactions, KIP-447 producer per threadKafka input, state changelogs, Kafka outputCommit latency (100 ms default interval), 3+ brokers recommended
FlinkAligned (or unaligned) checkpoints, 2PC sinksReplayable sources, operator state, transactional sinksCheckpoint alignment latency, sink transaction timeouts
Spark Structured StreamingCheckpointed offsets and state; idempotent or transactional sinksFile sink exactly-once; Kafka sink documented as at-least-onceMicro-batch latency
Go kafka snippetfranz-go GroupTransactSession, changelog in the same transactionKafka in, Kafka outYou own restore and changelog format
RabbitMQ, RedisNoneNoneIdempotent sinks only

How to use it: inside Kafka, use the transactional pattern; at the edges, make the sink idempotent (upsert by window key) and side effects keyed by a business identity. See delivery guarantees for the producer-side mechanics.

Scaling, parallelism and backpressure Important ​

In plain words: A stream processor scales by splitting keys across tasks, and the number of input partitions caps the number of tasks.

Common misunderstanding: "Add instances to go faster." In Kafka Streams, "the maximum parallelism at which your application may run is bounded by the maximum number of stream tasks, which itself is determined by maximum number of partitions of the input topic(s)". Extra instances sit idle (or act as standbys).

Definition: a task owns a set of partitions and the state for their keys. Flink's maximum parallelism fixes the number of Key Groups, so it limits future rescaling. Backpressure is the slowing of upstream operators when a downstream one cannot keep up; in Flink it also delays barriers and therefore checkpoints, which unaligned checkpoints mitigate.

text
1 topic orders: 12 partitions -> at most 12 Kafka Streams tasks for this sub-topology
2 3 instances x 4 threads = 12 threads: one task each
3 a 4th instance joins: no task to run (or becomes a standby)
4 a groupBy(region) adds a repartition topic: its partition count limits the next sub-topology

Real scenarios: a hot key (one region with 80 % of traffic) that pins one task; a backfill that saturates the sink and builds lag; a Flink job whose checkpoints time out under backpressure.

LimitKafka StreamsFlinkHand-rolled
Parallelism capInput partitionsMax parallelism / Key GroupsPartitions, or one consumer (RabbitMQ SAC)
Hot keyOne taskOne subtaskOne process
Backpressure signalConsumer lagBackpressure metrics, checkpoint durationLag, prefetch exhaustion

How to use it: pick partition counts for the processor, not only the producer, and see competing consumers and backpressure.

Per-engine behaviour ​

EngineModelStateEvent-time progressLatenessExactly-onceTypical fit
Kafka StreamsJava library inside your serviceRocksDB + changelogStream time per taskGrace periodexactly_once_v2 (Kafka to Kafka)Kafka-centric microservices
ksqlDBSQL server on Kafka StreamsSame as Kafka StreamsSameGRACE PERIOD (24 h default)Inherits Kafka StreamsSQL over Kafka topics
Apache FlinkCluster, DataStream and SQL APIsHeap or RocksDB backend, checkpointsWatermarks, idleness, alignmentallowedLateness, side outputsCheckpoints + 2PC sinksLarge stateful jobs, many sources
Spark Structured StreamingMicro-batch DataFrame queriesState store + checkpointwithWatermark (global min by default)Watermark delaySink dependentTeams already on Spark
MaterializeIncrementally maintained SQL viewsInternalTemporal filters with mz_now()Rows leave views as time movesConsistent viewsLive SQL views over CDC and Kafka
RisingWaveStreaming SQL databaseInternalWATERMARK FOR col AS ...Watermark-based state cleanupConsistent viewsPostgres-compatible streaming SQL
Apache BeamAPI over runners (Flink, Dataflow, Spark)RunnerDataflow watermarksAllowed latenessRunner dependentPortable pipelines, Go SDK
Go / PHP by handYour codeYour storeYour watermarkYour ruleOnly what you buildSmall, single-purpose aggregations

Materialize describes itself as maintaining results incrementally: it "incrementally updates results as it ingests data rather than recalculating results from scratch". Its time windows are temporal filters such as WHERE mz_now() <= event_ts + INTERVAL '5min'. Spark's default global watermark is the minimum because "it ensures that no data is accidentally dropped as too late if one of the streams falls behind the others".

Mechanics and exact controls ​

Knobs you will actually set Must-know ​

ProductKnobDefault (docs read 2026-11-26)Effect
Kafka topicmessage.timestamp.typeCreateTimeLogAppendTime makes record time ingestion time
Kafka topicmessage.timestamp.after.max.ms3600000Rejects CreateTime records too far in the future
Kafka Streamsprocessing.guaranteeat_least_onceexactly_once_v2 enables transactions
Kafka Streamscommit.interval.ms30000, or 100 with exactly-onceCommit (and with EOS, visibility) frequency
Kafka Streamsnum.standby.replicas0Warm copies of state for fast failover
Kafka Streamsmax.task.idle.ms0Wait for empty partitions to avoid out-of-order joins and merges
Kafka Streamsstatestore.cache.max.bytes10485760Record cache; fewer intermediate updates downstream
Kafka Streamsdefault.timestamp.extractorFailOnInvalidTimestamp (the record's embedded timestamp)Plug event-time extraction from the payload
FlinkforBoundedOutOfOrderness(d)NoneWatermark = max timestamp minus d
FlinkwithIdleness(d)OffIdle splits stop holding the watermark
FlinkallowedLateness(d)0Keeps fired windows for late elements
FlinkenableCheckpointing(ms) / execution.checkpointing.intervalDisabledCheckpoint period; required for exactly-once
FlinkCheckpointingMode.EXACTLY_ONCEExactly-once when checkpointing is onAT_LEAST_ONCE skips alignment
SparkwithWatermark(col, delay)NoneState cleanup and late-row dropping
Sparkspark.sql.streaming.multipleWatermarkPolicyminmax follows the fastest stream
ksqlDBGRACE PERIOD24 hoursWindow close time
RabbitMQconsumer_timeout1800000 (30 min)Bounds how long a message can stay unacked
RabbitMQ Streamsx-stream-offsetNext offsetfirst, last, offset, timestamp, interval

Symptoms and what they mean Important ​

SymptomMeaningFix
Windows never close, no outputWatermark or stream time not advancing: an idle partition, or no new recordsIdleness detection; heartbeat events; Kafka Streams needs new records per task
Output bursts after an outageProcessing-time windows, or a watermark that jumps after backlogUse event time; expect late panes
Totals lower than a batch recount (Kafka Streams, ksqlDB)Records later than the grace period were discardedLonger grace, or reconcile from the raw topic
Restore takes many minutes after rebalanceChangelog replay into a new storenum.standby.replicas, smaller state, retention
RocksDB disk grows without boundNo eviction: unbounded keys or no grace/retentionGrace, retention, TTL, key design
Joins produce no matchesNot co-partitioned, or timestamps outside the join windowSame partition count and partitioner; check extractor
Flink checkpoints time outBackpressure delays barriersUnaligned checkpoints, reduce state, scale the slow operator
Duplicates downstream after restartAt-least-once sink outside the transactionIdempotent upsert, or a transactional sink
AMQP 406 PRECONDITION_FAILED on a channel holding unacked window messagesRabbitMQ consumer_timeout hitShorter windows plus lateness, or external state

Solving classic problems ​

Orders per minute that survive replays and late data ​

SolutionHowAdvantageCost / limitation
Kafka Streams windowed countgroupByKey().windowedBy(ofSizeAndGrace).count()Full model, EOS, standbysJVM service
ksqlDBSQL with WINDOW TUMBLING and GRACE PERIODNo codeAnother server to run
Flink SQL or DataStreamEvent-time windows, watermarksMany sources and sinksA cluster to operate
Hand-rolled Go operator + Kafka transactionThis page's kafka snippetGo only, readableYou own restore, changelog, upgrades
Redis Lua windowsThis page's redis snippet and Laravel classShares state across runtimesNo exactly-once; single watermark
Batch reconciliationNightly job over the raw topic and side outputSimple, exact for the pastNot real time

ksqlDB, from its documentation's grace-period example, adapted to the order stream:

sql
-- ksqlDB: one-minute event-time windows, two minutes of grace, final rows only.
CREATE TABLE orders_per_region_minute AS
  SELECT region, COUNT(*) AS orders, SUM(amount_cents) AS amount_cents
  FROM orders
  WINDOW TUMBLING (SIZE 1 MINUTE, GRACE PERIOD 2 MINUTES)
  GROUP BY region
  EMIT FINAL;

The sink side in PostgreSQL: an accumulating pane overwrites only an older pane, so replays and repeated panes are harmless.

sql
CREATE TABLE order_window_counts (
    region          text   NOT NULL,
    window_start_ms bigint NOT NULL,
    window_end_ms   bigint NOT NULL,
    orders          integer NOT NULL,
    amount_cents    bigint NOT NULL,
    pane_index      integer NOT NULL,
    PRIMARY KEY (region, window_start_ms)
);
INSERT INTO order_window_counts AS c
    (region, window_start_ms, window_end_ms, orders, amount_cents, pane_index)
VALUES ('eu', 1795694400000, 1795694460000, 2, 1650, 0)
ON CONFLICT (region, window_start_ms) DO UPDATE
    SET orders = EXCLUDED.orders, amount_cents = EXCLUDED.amount_cents, pane_index = EXCLUDED.pane_index
    WHERE c.pane_index < EXCLUDED.pane_index;

Too-late records without silent loss ​

Route them to a side output (Flink sideOutputLateData, a orders-too-late topic or stream), keep their original payload, and reconcile in batch: recompute the affected window from the raw log and overwrite the pane with a higher pane index. Measure the side-output rate; if it is high, the out-of-orderness bound or the lateness is too short.

One quiet partition blocks everything ​

Register every assigned partition (so it holds the watermark until it has data), enable idleness (Flink withIdleness; Config.Idleness in the Go operator), and for Kafka Streams, where stream time advances only with records, send periodic heartbeat records per partition if windows must close during quiet periods.

State that grows forever ​

Bound it: windows with a lateness horizon, session gaps, retention on window stores, TTL on non-windowed state, and keys that do not grow without limit (no raw session IDs as keys in a KTable that never deletes).

Choosing an approach ​

SituationChooseExtra techniqueReason
Kafka already, JVM services, Kafka-in and Kafka-outKafka Streamsexactly_once_v2, standbysLibrary, no cluster, full model
Same, but SQL usersksqlDBEMIT FINAL, explicit GRACE PERIODNo code; mind the 24 h default
Many sources and sinks, very large stateFlinkRocksDB backend, idleness, savepointsWatermarks and checkpoints at scale
Team on Spark, minute-level latency is fineSpark Structured StreamingwithWatermark, append modeReuse the platform
Live SQL views over CDCMaterialize or RisingWaveTemporal filters / watermarksIncremental views, Postgres wire
Go service, one simple aggregation on KafkaHand-rolled operator + transactionChangelog topic, idempotent sinkSmall and readable; know its limits
RabbitMQ queues onlyExternal state (Redis/DB) or move the stream to Kafka/RabbitMQ StreamsSingle active consumerQueues cannot replay
Redis Streams, small volumeLua windows or Redis TimeSeriesHash-tagged keys, dedup setFast; no exactly-once, no multi-input watermark
Analytics over history, not real timeBatch / columnar storeReconcile side outputsOLAP is cheaper than long windows

Go ​

Before ​

The consumer stamps each order with time.Now() and increments a map that is never trimmed. A ten-minute outage turns into one spike when the backlog drains, and replaying the topic gives a different answer each time.

go
// Command before counts "orders per minute" the way most first versions do:
// by the consumer's wall clock, in a map that only ever grows. It is bad
// design, not broken code: it compiles and runs, and its answers are wrong.
package main

import (
	"context"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/twmb/franz-go/pkg/kgo"
)

func main() {
	brokers := os.Getenv("KAFKA_BROKERS")
	if brokers == "" {
		fmt.Println("set KAFKA_BROKERS to run")
		return
	}
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(strings.Split(brokers, ",")...),
		kgo.ConsumerGroup("orders-per-minute-naive"),
		kgo.ConsumeTopics("orders"),
	)
	if err != nil {
		panic(err)
	}
	defer cl.Close()

	// Keyed by PROCESSING-time minute. Nothing is ever deleted, so memory
	// grows for as long as the process lives, and no minute is ever final.
	counts := map[string]int{}
	ctx := context.Background()
	for {
		fetches := cl.PollFetches(ctx)
		if fetches.IsClientClosed() {
			return
		}
		fetches.EachRecord(func(r *kgo.Record) {
			// time.Now() is when WE saw the order, not when it was placed.
			// After a 10-minute outage the backlog lands in the current
			// minute: one huge spike after ten empty minutes.
			minute := time.Now().UTC().Format("2006-01-02T15:04")
			counts[minute]++
		})
		// Replaying the topic gives different numbers on every run, because
		// the answer depends on when the job ran. Auto-commit also means a
		// crash loses the in-memory counts while the offsets moved on.
		now := time.Now().UTC().Format("2006-01-02T15:04")
		fmt.Printf("%s: %d orders (%d minutes held in memory)\n", now, counts[now], len(counts))
	}
}

After ​

The window operator is a small, standard-library package: tumbling, hopping and session assigners with half-open epoch-aligned windows; a watermark that is the minimum over registered inputs minus the out-of-orderness bound, monotonic, with idleness; one eviction rule for state and refusal; accumulating or discarding panes; retraction hints for merged sessions; and TakeChanges/Restore/Meta so a caller can write a changelog.

go
// Package window is a small, single-threaded event-time windowing operator:
// tumbling, hopping and session windows, a bounded-out-of-orderness
// watermark taken as the minimum over input partitions, idle-input
// detection, allowed lateness, accumulating or discarding panes, retraction
// hints for merged sessions, and state eviction. It follows the Dataflow
// model closely enough to teach Flink and Kafka Streams; it is not a
// replacement for either. Callers serialise access (no internal locking).
package window

import (
	"errors"
	"math"
	"sort"
	"time"
)

// Kind selects the window assigner.
type Kind int

const (
	Tumbling Kind = iota // fixed size, no overlap, epoch aligned
	Hopping              // fixed size, starts every Advance; overlapping
	Session              // per key, closed by a gap of inactivity
)

// Mode is the Dataflow refinement mode for repeated panes of one window.
type Mode int

const (
	Accumulating Mode = iota // every pane carries the full aggregate so far
	Discarding               // every pane carries only what arrived since the last pane
)

// Config describes one windowed aggregation. Durations are truncated to ms.
type Config struct {
	Kind            Kind
	Size            time.Duration // Tumbling and Hopping
	Advance         time.Duration // Hopping only (Tumbling uses Size)
	Gap             time.Duration // Session only
	OutOfOrderness  time.Duration // watermark = min(max event time per input) - OutOfOrderness
	AllowedLateness time.Duration // Flink allowedLateness, Kafka Streams grace period
	Idleness        time.Duration // processing time after which a silent input stops holding the watermark; 0 = never
	Mode            Mode
}

// Record is one input element. Value is summed; every record also counts 1.
type Record struct {
	Partition string // input partition, e.g. "orders/3"
	Key       string
	EventTime time.Time
	Value     int64
}

// Outcome tells the caller what happened to one record.
type Outcome int

const (
	OnTime  Outcome = iota // stored in windows that have not fired yet
	Late                   // stored, but at least one of its windows already fired: a late pane follows
	TooLate                // every window it belongs to has expired; nothing stored, side-output it
)

// Result reports where a record went. A hopping record can be partly dropped.
type Result struct {
	Outcome Outcome
	Windows int // windows the record was added to
	Dropped int // expired windows it would have belonged to
}

// Span is a window interval in Unix milliseconds, [Start, End).
type Span struct {
	Start int64 `json:"start"`
	End   int64 `json:"end"`
}

// Timing says whether a pane was produced by the watermark or by late data.
type Timing int

const (
	OnTimePane Timing = iota // the watermark passed the window end
	LatePane                 // late records refined an already fired window
)

func (t Timing) String() string {
	if t == LatePane {
		return "late"
	}
	return "on-time"
}

// Pane is one emission for one window (the Dataflow term).
type Pane struct {
	Key        string
	Start, End time.Time
	Count, Sum int64
	Timing     Timing
	Index      int    // 0 for the first pane of this window, then 1, 2, ...
	Retracts   []Span // previously emitted windows this pane replaces (merged sessions, Accumulating only)
}

// State is one stored window, exported so a caller can write it to a
// changelog and restore it after a crash or a partition move.
type State struct {
	Key     string `json:"key"`
	Span    Span   `json:"span"`
	Count   int64  `json:"count"`
	Sum     int64  `json:"sum"`
	Fired   bool   `json:"fired"`
	Dirty   bool   `json:"dirty"`
	Panes   int    `json:"panes"`
	Emitted *Span  `json:"emitted,omitempty"` // span of the last emitted pane
	Retract []Span `json:"retract,omitempty"` // emitted spans swallowed by a session merge
	Deleted bool   `json:"deleted,omitempty"` // changelog tombstone
}

// Meta is the operator's progress, also needed to restore it.
type Meta struct {
	Watermark    int64            `json:"watermark"`
	HasWatermark bool             `json:"has_watermark"`
	InputMax     map[string]int64 `json:"input_max"`
}

type input struct {
	max    int64
	seen   bool
	active time.Time // processing time of the last record (or registration)
}

type id struct {
	key  string
	span Span
}

// Operator holds windows, inputs and the watermark.
type Operator struct {
	cfg                                 Config
	size, advance, gap, delay, lateness int64
	inputs                              map[string]*input
	wm                                  int64
	hasWM                               bool
	windows                             map[string]map[Span]*State
	changed                             map[id]bool
}

// New validates cfg and returns an empty operator.
func New(cfg Config) (*Operator, error) {
	o := &Operator{
		cfg:      cfg,
		size:     cfg.Size.Milliseconds(),
		advance:  cfg.Advance.Milliseconds(),
		gap:      cfg.Gap.Milliseconds(),
		delay:    cfg.OutOfOrderness.Milliseconds(),
		lateness: cfg.AllowedLateness.Milliseconds(),
		inputs:   map[string]*input{},
		windows:  map[string]map[Span]*State{},
		changed:  map[id]bool{},
	}
	switch cfg.Kind {
	case Tumbling:
		o.advance = o.size
		if o.size <= 0 {
			return nil, errors.New("window: tumbling needs Size >= 1ms")
		}
	case Hopping:
		if o.size <= 0 || o.advance <= 0 || o.advance > o.size {
			return nil, errors.New("window: hopping needs 0 < Advance <= Size")
		}
	case Session:
		if o.gap <= 0 {
			return nil, errors.New("window: session needs Gap >= 1ms")
		}
	default:
		return nil, errors.New("window: unknown kind")
	}
	if o.delay < 0 || o.lateness < 0 || cfg.Idleness < 0 {
		return nil, errors.New("window: negative duration")
	}
	return o, nil
}

// Register adds an input before its first record (call it from a partition
// assignment callback) so the watermark cannot run ahead of it.
func (o *Operator) Register(partition string, now time.Time) {
	if _, ok := o.inputs[partition]; !ok {
		o.inputs[partition] = &input{active: now}
	}
}

// Forget removes an input, e.g. when a rebalance revokes the partition.
func (o *Operator) Forget(partition string) { delete(o.inputs, partition) }

// Watermark returns the current watermark: an assertion that no more
// records with an earlier event time are expected. ok is false until every
// non-idle input has produced at least one record.
func (o *Operator) Watermark() (wm time.Time, ok bool) {
	return time.UnixMilli(o.wm).UTC(), o.hasWM
}

func floorTo(ts, unit int64) int64 {
	m := ts % unit
	if m < 0 {
		m += unit
	}
	return ts - m
}

// assign returns the fixed windows (ascending) that contain ts.
func (o *Operator) assign(ts int64) []Span {
	var out []Span
	for s := floorTo(ts, o.advance); s > ts-o.size; s -= o.advance {
		out = append(out, Span{s, s + o.size})
	}
	sort.Slice(out, func(i, j int) bool { return out[i].Start < out[j].Start })
	return out
}

// expired is the single eviction rule: state for a window is kept until the
// watermark reaches End + AllowedLateness, and records for it are refused
// from then on, so an evicted window can never be resurrected half-empty.
func (o *Operator) expired(s Span) bool { return o.hasWM && s.End+o.lateness <= o.wm }

func (o *Operator) bucket(key string) map[Span]*State {
	b := o.windows[key]
	if b == nil {
		b = map[Span]*State{}
		o.windows[key] = b
	}
	return b
}

// Add assigns one record by event time. It never moves the watermark;
// Advance does, as Flink's periodic watermark emission does.
func (o *Operator) Add(r Record, now time.Time) Result {
	ts := r.EventTime.UnixMilli()
	in := o.inputs[r.Partition]
	if in == nil {
		in = &input{}
		o.inputs[r.Partition] = in
	}
	in.active = now
	if !in.seen || ts > in.max {
		in.max, in.seen = ts, true
	}
	if o.cfg.Kind == Session {
		return o.addSession(r, ts)
	}
	var res Result
	late := false
	for _, s := range o.assign(ts) {
		if o.expired(s) {
			res.Dropped++
			continue
		}
		b := o.bucket(r.Key)
		st := b[s]
		if st == nil {
			st = &State{Key: r.Key, Span: s}
			b[s] = st
		}
		st.Count++
		st.Sum += r.Value
		if st.Fired {
			st.Dirty, late = true, true
		}
		o.changed[id{r.Key, s}] = true
		res.Windows++
	}
	res.Outcome = outcome(res.Windows, late)
	return res
}

func outcome(windows int, late bool) Outcome {
	switch {
	case windows == 0:
		return TooLate
	case late:
		return Late
	default:
		return OnTime
	}
}

// addSession starts [ts, ts+Gap) and merges it with every overlapping
// session of the same key. Sessions that only touch (end == start) stay apart.
func (o *Operator) addSession(r Record, ts int64) Result {
	proto := Span{ts, ts + o.gap}
	b := o.bucket(r.Key)
	var overlaps []*State
	for s, st := range b {
		if s.Start < proto.End && proto.Start < s.End {
			overlaps = append(overlaps, st)
		}
	}
	if len(overlaps) == 0 && o.expired(proto) {
		return Result{Outcome: TooLate, Dropped: 1}
	}
	merged := &State{Key: r.Key, Span: proto}
	for _, st := range overlaps {
		merged.Span.Start = min(merged.Span.Start, st.Span.Start)
		merged.Span.End = max(merged.Span.End, st.Span.End)
		merged.Count += st.Count
		merged.Sum += st.Sum
		merged.Fired = merged.Fired || st.Fired
		merged.Panes = max(merged.Panes, st.Panes)
		merged.Retract = append(merged.Retract, st.Retract...)
		if st.Emitted != nil {
			merged.Retract = append(merged.Retract, *st.Emitted)
		}
		delete(b, st.Span)
		o.changed[id{r.Key, st.Span}] = true
	}
	merged.Count++
	merged.Sum += r.Value
	merged.Dirty = merged.Fired
	b[merged.Span] = merged
	o.changed[id{r.Key, merged.Span}] = true
	return Result{Outcome: outcome(1, merged.Fired), Windows: 1}
}

// Advance recomputes the watermark from the inputs, emits on-time panes for
// windows whose end it passed and late panes for refined windows, and evicts
// windows past End + AllowedLateness. Call it periodically.
func (o *Operator) Advance(now time.Time) []Pane {
	o.advanceWatermark(now)
	if !o.hasWM {
		return nil
	}
	var out []Pane
	for key, b := range o.windows {
		for s, st := range b {
			if (!st.Fired && s.End <= o.wm) || st.Dirty {
				out = append(out, o.emit(st))
				o.changed[id{key, s}] = true
			}
			if o.expired(s) {
				delete(b, s)
				o.changed[id{key, s}] = true
			}
		}
		if len(b) == 0 {
			delete(o.windows, key)
		}
	}
	sort.Slice(out, func(i, j int) bool {
		if !out[i].Start.Equal(out[j].Start) {
			return out[i].Start.Before(out[j].Start)
		}
		if out[i].Key != out[j].Key {
			return out[i].Key < out[j].Key
		}
		return out[i].End.Before(out[j].End)
	})
	return out
}

func (o *Operator) advanceWatermark(now time.Time) {
	candidate, active := int64(math.MaxInt64), 0
	for _, in := range o.inputs {
		if o.cfg.Idleness > 0 && now.Sub(in.active) >= o.cfg.Idleness {
			continue // idle: Flink withIdleness; it rejoins on its next record
		}
		if !in.seen {
			return // an active input without data holds the watermark back
		}
		active++
		candidate = min(candidate, in.max-o.delay)
	}
	if active == 0 {
		return // all inputs idle: nothing proves that event time moved on
	}
	if !o.hasWM || candidate > o.wm {
		o.wm, o.hasWM = candidate, true // monotonic: never moves backwards
	}
}

func (o *Operator) emit(st *State) Pane {
	p := Pane{
		Key:   st.Key,
		Start: time.UnixMilli(st.Span.Start).UTC(),
		End:   time.UnixMilli(st.Span.End).UTC(),
		Count: st.Count, Sum: st.Sum,
		Index: st.Panes,
	}
	if st.Fired {
		p.Timing = LatePane
	}
	if o.cfg.Mode == Accumulating {
		for _, r := range st.Retract {
			if r != st.Span {
				p.Retracts = append(p.Retracts, r)
			}
		}
		if st.Emitted != nil && *st.Emitted != st.Span {
			p.Retracts = append(p.Retracts, *st.Emitted)
		}
	} else {
		st.Count, st.Sum = 0, 0 // Discarding: the next pane starts from zero
	}
	span := st.Span
	st.Emitted, st.Retract = &span, nil
	st.Fired, st.Dirty = true, false
	st.Panes++
	return p
}

// OpenWindows reports how many windows are held in state.
func (o *Operator) OpenWindows() int {
	n := 0
	for _, b := range o.windows {
		n += len(b)
	}
	return n
}

// TakeChanges returns every window created, updated or deleted since the
// previous call (deleted ones as tombstones), for a changelog.
func (o *Operator) TakeChanges() []State {
	out := make([]State, 0, len(o.changed))
	for c := range o.changed {
		if st := o.windows[c.key][c.span]; st != nil {
			cp := *st
			cp.Retract = append([]Span(nil), st.Retract...)
			out = append(out, cp)
		} else {
			out = append(out, State{Key: c.key, Span: c.span, Deleted: true})
		}
	}
	clear(o.changed)
	sort.Slice(out, func(i, j int) bool {
		if out[i].Span != out[j].Span {
			return out[i].Span.Start < out[j].Span.Start ||
				(out[i].Span.Start == out[j].Span.Start && out[i].Span.End < out[j].Span.End)
		}
		return out[i].Key < out[j].Key
	})
	return out
}

// Restore applies one changelog entry without marking it as changed.
func (o *Operator) Restore(st State) {
	if st.Deleted {
		if b := o.windows[st.Key]; b != nil {
			delete(b, st.Span)
		}
		return
	}
	cp := st
	o.bucket(st.Key)[st.Span] = &cp
}

// Meta snapshots the watermark and the per-input maxima.
func (o *Operator) Meta() Meta {
	m := Meta{Watermark: o.wm, HasWatermark: o.hasWM, InputMax: map[string]int64{}}
	for p, in := range o.inputs {
		if in.seen {
			m.InputMax[p] = in.max
		}
	}
	return m
}

// RestoreMeta reinstates progress saved by Meta. The watermark only moves
// forward, so restoring an older snapshot cannot reopen expired windows.
func (o *Operator) RestoreMeta(m Meta, now time.Time) {
	for p, mx := range m.InputMax {
		in := o.inputs[p]
		if in == nil {
			in = &input{active: now}
			o.inputs[p] = in
		}
		if !in.seen || mx > in.max {
			in.max, in.seen = mx, true
		}
	}
	if m.HasWatermark && (!o.hasWM || m.Watermark > o.wm) {
		o.wm, o.hasWM = m.Watermark, true
	}
}

The tests pin each rule: boundaries, hopping membership, min-over-inputs and monotonicity, idleness, lateness and eviction with tombstones, discarding deltas, session merges with retractions, restore, and config validation.

go
package window

import (
	"testing"
	"time"
)

var t0 = time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)

func at(d time.Duration) time.Time { return t0.Add(d) }

func mustNew(t *testing.T, cfg Config) *Operator {
	t.Helper()
	o, err := New(cfg)
	if err != nil {
		t.Fatal(err)
	}
	return o
}

func add(o *Operator, part, key string, ev time.Duration) Result {
	return o.Add(Record{Partition: part, Key: key, EventTime: at(ev), Value: 1}, t0)
}

func TestTumblingBoundariesAreHalfOpenAndEpochAligned(t *testing.T) {
	o := mustNew(t, Config{Kind: Tumbling, Size: time.Minute})
	add(o, "p0", "k", 59*time.Second+999*time.Millisecond) // last ms of [12:00, 12:01)
	add(o, "p0", "k", time.Minute)                         // first ms of [12:01, 12:02)
	add(o, "p0", "k", 3*time.Minute)                       // moves the watermark to 12:03
	panes := o.Advance(t0)
	if len(panes) != 2 {
		t.Fatalf("want 2 panes, got %+v", panes)
	}
	if !panes[0].Start.Equal(at(0)) || !panes[0].End.Equal(at(time.Minute)) || panes[0].Count != 1 {
		t.Fatalf("first window wrong: %+v", panes[0])
	}
	if !panes[1].Start.Equal(at(time.Minute)) || panes[1].Count != 1 {
		t.Fatalf("second window wrong: %+v", panes[1])
	}
}

func TestHoppingRecordBelongsToSizeOverAdvanceWindows(t *testing.T) {
	o := mustNew(t, Config{Kind: Hopping, Size: 10 * time.Minute, Advance: 5 * time.Minute})
	res := add(o, "p0", "k", 7*time.Minute)
	if res.Windows != 2 || o.OpenWindows() != 2 {
		t.Fatalf("12:07 should be in [12:00,12:10) and [12:05,12:15): %+v", res)
	}
}

func TestWatermarkIsMinimumOverInputsAndMonotonic(t *testing.T) {
	o := mustNew(t, Config{Kind: Tumbling, Size: time.Minute, OutOfOrderness: 10 * time.Second})
	o.Register("p0", t0)
	o.Register("p1", t0)
	add(o, "p0", "k", 5*time.Minute)
	o.Advance(t0)
	if _, ok := o.Watermark(); ok {
		t.Fatal("p1 has no data yet; the watermark must wait for it")
	}
	add(o, "p1", "k", 2*time.Minute)
	o.Advance(t0)
	if wm, _ := o.Watermark(); !wm.Equal(at(2*time.Minute - 10*time.Second)) {
		t.Fatalf("want min(p0,p1)-10s = 12:01:50, got %v", wm)
	}
	o.Forget("p0")
	add(o, "p1", "k", time.Minute) // older record; max of p1 stays 12:02
	o.Advance(t0)
	if wm, _ := o.Watermark(); !wm.Equal(at(2*time.Minute - 10*time.Second)) {
		t.Fatalf("watermark moved backwards or forwards wrongly: %v", wm)
	}
}

func TestIdleInputStopsHoldingTheWatermark(t *testing.T) {
	o := mustNew(t, Config{Kind: Tumbling, Size: time.Minute, Idleness: time.Minute})
	o.Register("busy", t0)
	o.Register("quiet", t0)
	o.Add(Record{Partition: "busy", Key: "k", EventTime: at(30 * time.Second)}, t0)
	o.Add(Record{Partition: "busy", Key: "k", EventTime: at(2 * time.Minute)}, t0.Add(90*time.Second))
	if panes := o.Advance(t0.Add(30 * time.Second)); panes != nil {
		t.Fatalf("quiet input is not idle yet, nothing may fire: %+v", panes)
	}
	panes := o.Advance(t0.Add(90 * time.Second)) // quiet has been silent for 90s >= 1m
	if len(panes) != 1 || panes[0].Count != 1 {
		t.Fatalf("idle input should release [12:00,12:01): %+v", panes)
	}
}

func TestAllowedLatenessAccumulatingRefinesThenEvicts(t *testing.T) {
	o := mustNew(t, Config{Kind: Tumbling, Size: time.Minute, AllowedLateness: 2 * time.Minute})
	add(o, "p0", "k", 10*time.Second)
	add(o, "p0", "k", time.Minute+5*time.Second) // watermark -> 12:01:05
	if p := o.Advance(t0); len(p) != 1 || p[0].Timing != OnTimePane || p[0].Count != 1 {
		t.Fatalf("on-time pane expected: %+v", p)
	}
	if r := add(o, "p0", "k", 20*time.Second); r.Outcome != Late {
		t.Fatalf("12:00:20 is behind the watermark but inside lateness: %+v", r)
	}
	p := o.Advance(t0)
	if len(p) != 1 || p[0].Timing != LatePane || p[0].Count != 2 || p[0].Index != 1 {
		t.Fatalf("accumulating late pane must carry the full count: %+v", p)
	}
	add(o, "p0", "k", 3*time.Minute) // watermark 12:03 = end 12:01 + lateness 2m
	o.Advance(t0)
	if r := add(o, "p0", "k", 30*time.Second); r.Outcome != TooLate {
		t.Fatalf("after end+lateness the record must be refused: %+v", r)
	}
	for _, s := range o.TakeChanges() {
		if s.Span.Start == t0.UnixMilli() && !s.Deleted {
			t.Fatalf("expired window must be a tombstone in the changelog: %+v", s)
		}
	}
}

func TestDiscardingPanesCarryOnlyTheDelta(t *testing.T) {
	o := mustNew(t, Config{Kind: Tumbling, Size: time.Minute, AllowedLateness: time.Hour, Mode: Discarding})
	add(o, "p0", "k", 0)
	add(o, "p0", "k", 1*time.Second)
	add(o, "p0", "k", 2*time.Minute)
	o.Advance(t0)
	add(o, "p0", "k", 3*time.Second)
	p := o.Advance(t0)
	if len(p) != 1 || p[0].Count != 1 {
		t.Fatalf("discarding late pane must hold 1, got %+v", p)
	}
}

func TestSessionMergeEmitsRetractions(t *testing.T) {
	o := mustNew(t, Config{Kind: Session, Gap: 5 * time.Minute, AllowedLateness: time.Hour})
	add(o, "p0", "u1", 0)                // [12:00, 12:05)
	add(o, "p0", "u1", 8*time.Minute)    // [12:08, 12:13): 3 minutes apart from the first
	add(o, "p0", "u2", 30*time.Minute)   // other key moves the watermark to 12:30
	if p := o.Advance(t0); len(p) != 2 { // two u1 sessions fire; u2 is still open
		t.Fatalf("want two u1 sessions, got %+v", p)
	}
	if r := add(o, "p0", "u1", 4*time.Minute); r.Outcome != Late { // bridges both: [12:00, 12:13)
		t.Fatalf("bridging record is late: %+v", r)
	}
	p := o.Advance(t0)
	if len(p) != 1 || p[0].Count != 3 || len(p[0].Retracts) != 2 {
		t.Fatalf("merged session must carry 3 and retract both old sessions: %+v", p)
	}
	if !p[0].Start.Equal(at(0)) || !p[0].End.Equal(at(13*time.Minute)) {
		t.Fatalf("merged bounds wrong: %+v", p[0])
	}
}

func TestRestoreFromChangelogAndMeta(t *testing.T) {
	cfg := Config{Kind: Tumbling, Size: time.Minute, AllowedLateness: time.Minute}
	a := mustNew(t, cfg)
	add(a, "p0", "k", 10*time.Second)
	add(a, "p0", "k", 20*time.Second)
	a.Advance(t0)
	b := mustNew(t, cfg)
	for _, s := range a.TakeChanges() {
		b.Restore(s)
	}
	b.RestoreMeta(a.Meta(), t0)
	add(b, "p0", "k", 2*time.Minute)
	p := b.Advance(t0)
	if len(p) != 1 || p[0].Count != 2 {
		t.Fatalf("restored operator lost state: %+v", p)
	}
}

func TestConfigValidation(t *testing.T) {
	bad := []Config{
		{Kind: Tumbling},
		{Kind: Hopping, Size: time.Minute, Advance: 2 * time.Minute},
		{Kind: Session},
		{Kind: Tumbling, Size: time.Minute, AllowedLateness: -time.Second},
	}
	for _, c := range bad {
		if _, err := New(c); err == nil {
			t.Fatalf("config should be rejected: %+v", c)
		}
	}
}

A broker-free replay makes the semantics visible; its output is reproduced in the lab.

go
// Command after replays a fixed, out-of-order order stream through the
// window operator, with no broker, so every outcome is reproducible:
// one-minute tumbling windows per region, a watermark trailing the newest
// event by 30s, two minutes of allowed lateness, one-minute idleness, and
// accumulating panes that a sink can upsert by (region, window start).
package main

import (
	"fmt"
	"time"

	"academy/stream-processing/window"
)

type event struct {
	arrive   time.Duration // processing time, after the replay starts
	part     string        // input partition
	region   string        // grouping key
	occurred time.Duration // event time, after 12:00
	cents    int64
}

func main() {
	start := time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)
	op, err := window.New(window.Config{
		Kind:            window.Tumbling,
		Size:            time.Minute,
		OutOfOrderness:  30 * time.Second,
		AllowedLateness: 2 * time.Minute,
		Idleness:        time.Minute,
		Mode:            window.Accumulating,
	})
	if err != nil {
		panic(err)
	}
	op.Register("orders/0", start)
	op.Register("orders/1", start)

	m := time.Minute
	s := time.Second
	stream := []event{
		{1 * s, "orders/0", "eu", 10 * s, 1200},
		{2 * s, "orders/1", "us", 15 * s, 900},
		{3 * s, "orders/0", "eu", 50 * s, 450},
		{4 * s, "orders/0", "eu", 1*m + 40*s, 700},   // p0 max 12:01:40, p1 still 12:00:15
		{5 * s, "orders/1", "us", 1*m + 35*s, 300},   // watermark -> 12:01:05: [12:00,12:01) fires
		{6 * s, "orders/1", "us", 40 * s, 800},       // behind the watermark, inside lateness: late pane
		{7 * s, "orders/0", "eu", 4*m + 10*s, 500},   // p1 now holds the watermark
		{100 * s, "orders/0", "eu", 4*m + 20*s, 650}, // p1 silent for 95s: idle, watermark -> 12:03:50
		{101 * s, "orders/1", "us", 50 * s, 999},     // [12:00,12:01) evicted at 12:03: too late; p1 is active again
		{102 * s, "orders/1", "us", 3*m + 55*s, 100}, // ahead of the watermark: on time
		{103 * s, "orders/0", "eu", 6*m + 10*s, 50},  // p1 holds the watermark; it cannot move backwards
		{104 * s, "orders/1", "us", 7*m + 0*s, 75},   // watermark -> 12:05:40
	}

	for _, e := range stream {
		now := start.Add(e.arrive)
		res := op.Add(window.Record{
			Partition: e.part, Key: e.region,
			EventTime: start.Add(e.occurred), Value: e.cents,
		}, now)
		fmt.Printf("t+%-4v %s %s event=%s -> %s\n", e.arrive, e.part, e.region,
			start.Add(e.occurred).Format("15:04:05"), outcome(res))
		for _, p := range op.Advance(now) {
			fmt.Printf("        pane %s [%s,%s) orders=%d cents=%d %s#%d\n", p.Key,
				p.Start.Format("15:04"), p.End.Format("15:04"), p.Count, p.Sum, p.Timing, p.Index)
		}
		if wm, ok := op.Watermark(); ok {
			fmt.Printf("        watermark %s, open windows %d\n", wm.Format("15:04:05"), op.OpenWindows())
		}
	}
}

func outcome(r window.Result) string {
	switch r.Outcome {
	case window.Late:
		return "late (accepted)"
	case window.TooLate:
		return "too late -> side output"
	default:
		return "on time"
	}
}

The Go angle ​

Go has no Kafka Streams or Flink. Apache Beam has a Go SDK, but Beam pipelines run on a runner such as Flink or Dataflow. A Go service therefore either owns windowing and state, as above, or hands the computation to a JVM processor and consumes its output topic. The hard part is not the window logic but durable state: a changelog, restore on assignment, and commits that include both state and offsets. The kafka snippet below does exactly that with franz-go's GroupTransactSession and kadm; once you need joins, many stores, standbys or upgrades with state, you are rewriting Kafka Streams. The snippets compile without a broker and exit when their environment variable is unset.

Laravel ​

Before ​

A queued job bumps a cache counter for the minute in which the worker happened to run. Retries count twice, backlogs move orders into the wrong minute, and no minute is ever final.

php
<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Cache;

/**
 * BEFORE: one queued job per OrderPlaced event, counted by wall clock.
 * Bad design, not broken code.
 */
final class CountOrderPlaced implements ShouldQueue
{
    use Queueable;

    public function __construct(public string $orderId) {}

    public function handle(): void
    {
        // The bucket is the minute the WORKER ran (processing time), not the
        // minute the order was placed (event time). A queue backlog, a retry
        // with backoff or a paused Horizon supervisor moves orders into the
        // wrong minute.
        $minute = now()->utc()->format('Y-m-d H:i');

        // Never closes and never expires: no minute is ever final, and a
        // retried job counts twice because nothing remembers the order id.
        Cache::increment("orders:per-minute:{$minute}");
    }
}

After ​

The job carries the event time and a stable event id. EventTimeWindows runs two Lua scripts through Redis::eval: ingest (watermark update, grace check, per-window dedup set, aggregate, too-late side output) and close (on-time or late pane to a stream, eviction after grace). They are the same scripts the Go Redis consumer embeds, copied into resources/lua/ as window-ingest.lua and window-close.lua.

php
<?php

namespace App\Streams;

use Illuminate\Support\Facades\Redis;

/**
 * AFTER: one-minute event-time windows per region, kept in Redis, with a
 * watermark (max event time - 30s), a two-minute grace period and a
 * too-late side output. The two Lua scripts are byte-for-byte the ones the
 * Go consumer uses (copied to resources/lua/), so both runtimes can feed
 * the same windows.
 */
final class EventTimeWindows
{
    public const SIZE_MS = 60_000;

    public const DELAY_MS = 30_000;   // bounded out-of-orderness

    public const GRACE_MS = 120_000;  // allowed lateness (Kafka Streams: grace period)

    private const MAX = '{orders}:win:max';

    private const OPEN = '{orders}:win:open';

    private const STATE = '{orders}:win:state';

    private const PANES = '{orders}:panes';

    private const LATE = '{orders}:too-late';

    public const ACCEPTED = 1;

    public const DUPLICATE = 2;

    public const LATE_ACCEPTED = 3;

    public const TOO_LATE = 0;

    /** Returns one of the class constants; TOO_LATE went to the side-output stream. */
    public function record(string $eventId, string $region, int $occurredAtMs, int $amountCents): int
    {
        if ($region === '' || str_contains($region, '|')) {
            throw new \InvalidArgumentException('region must be non-empty and contain no "|"');
        }
        $start = $occurredAtMs - ($occurredAtMs % self::SIZE_MS);
        $member = $region.'|'.$start;

        return (int) Redis::eval(
            $this->script('window-ingest.lua'), 6,
            self::MAX, self::OPEN, self::STATE, $this->ids($member), $this->agg($member), self::LATE,
            $eventId, $occurredAtMs, $amountCents, $start,
            self::SIZE_MS, self::DELAY_MS, self::GRACE_MS, $member, $region,
        );
    }

    /** Fire windows the watermark passed, evict those past grace. Run from ONE process. */
    public function closeReady(): int
    {
        $max = Redis::get(self::MAX);
        if ($max === null || $max === false) {
            return 0;
        }
        $watermark = (int) $max - self::DELAY_MS;
        $emitted = 0;

        foreach (Redis::zrangebyscore(self::OPEN, '-inf', (string) $watermark) as $member) {
            [$region, $start] = explode('|', $member, 2);
            $emitted += (int) Redis::eval(
                $this->script('window-close.lua'), 6,
                self::MAX, self::OPEN, self::STATE, $this->ids($member), $this->agg($member), self::PANES,
                $member, (int) $start, (int) $start + self::SIZE_MS,
                self::DELAY_MS, self::GRACE_MS, $region,
            );
        }

        return $emitted;
    }

    private function ids(string $member): string
    {
        return '{orders}:win:ids:'.$member;
    }

    private function agg(string $member): string
    {
        return '{orders}:win:agg:'.$member;
    }

    private function script(string $name): string
    {
        static $cache = [];

        return $cache[$name] ??= file_get_contents(resource_path('lua/'.$name));
    }
}
php
<?php

namespace App\Jobs;

use App\Streams\EventTimeWindows;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

/**
 * The job carries the EVENT time, stamped where the order was placed, and a
 * stable event id, so a retried job is a no-op instead of a double count.
 */
final class RecordOrderPlaced implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public string $eventId,
        public string $region,
        public int $occurredAtMs,
        public int $amountCents,
    ) {}

    public function handle(EventTimeWindows $windows): void
    {
        $windows->record($this->eventId, $this->region, $this->occurredAtMs, $this->amountCents);
    }
}

A scheduled command closes windows; withoutOverlapping() and onOneServer() keep it to one closer.

php
<?php

namespace App\Console\Commands;

use App\Streams\EventTimeWindows;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('orders:close-windows')]
#[Description('Emit panes for event-time windows the watermark has passed')]
final class CloseOrderWindows extends Command
{
    public function handle(EventTimeWindows $windows): int
    {
        $this->info($windows->closeReady().' pane(s) emitted');

        return self::SUCCESS;
    }
}
php
<?php

use Illuminate\Support\Facades\Schedule;

// One closer at a time, on one server: two closers would race on the same
// window and could both emit its pane.
Schedule::command('orders:close-windows')
    ->everyMinute()
    ->withoutOverlapping()
    ->onOneServer();

The sink projects panes from the stream into a table, keeping only the newest pane per window.

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

/**
 * Sink: reads accumulating panes from the {orders}:panes stream and upserts
 * them by (region, window_start_ms). A pane only replaces an older pane, so
 * a redelivered old entry cannot overwrite a newer late pane.
 */
#[Signature('orders:project-panes')]
#[Description('Upsert window panes into order_window_counts')]
final class ProjectOrderPanes extends Command
{
    private const STREAM = '{orders}:panes';

    private const GROUP = 'pane-projector';

    public function handle(): int
    {
        try {
            Redis::xgroup('CREATE', self::STREAM, self::GROUP, '0', true);
        } catch (\RedisException) {
            // BUSYGROUP: the group already exists
        }

        while (true) {
            $batch = Redis::xreadgroup(self::GROUP, gethostname(), [self::STREAM => '>'], 100, 5000);
            foreach ($batch ?: [] as $entries) {
                foreach ($entries as $id => $pane) {
                    $this->upsert($id, $pane);
                    Redis::xack(self::STREAM, self::GROUP, [$id]);
                }
            }
        }
    }

    private function upsert(string $paneId, array $pane): void
    {
        DB::transaction(function () use ($paneId, $pane) {
            $current = DB::table('order_window_counts')
                ->where('region', $pane['region'])
                ->where('window_start_ms', (int) $pane['window_start'])
                ->lockForUpdate()
                ->value('pane_id');

            if ($current !== null && self::compareIds($current, $paneId) >= 0) {
                return; // already holds this pane or a newer one
            }

            DB::table('order_window_counts')->upsert([[
                'region' => $pane['region'],
                'window_start_ms' => (int) $pane['window_start'],
                'window_end_ms' => (int) $pane['window_end'],
                'orders' => (int) $pane['orders'],
                'amount_cents' => (int) $pane['amount_cents'],
                'timing' => $pane['timing'],
                'pane_id' => $paneId,
            ]], ['region', 'window_start_ms'], ['orders', 'amount_cents', 'timing', 'pane_id']);
        });
    }

    /** Stream IDs are "ms-seq"; compare numerically, not as strings. */
    private static function compareIds(string $a, string $b): int
    {
        [$am, $as] = array_map('intval', explode('-', $a, 2));
        [$bm, $bs] = array_map('intval', explode('-', $b, 2));

        return [$am, $as] <=> [$bm, $bs];
    }
}
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        // The materialized view of the stream: one row per (region, window).
        Schema::create('order_window_counts', function (Blueprint $table) {
            $table->string('region', 32);
            $table->bigInteger('window_start_ms');
            $table->bigInteger('window_end_ms');
            $table->unsignedInteger('orders');
            $table->bigInteger('amount_cents');
            $table->string('timing', 8);  // on-time | late
            $table->string('pane_id', 40); // Redis stream ID of the pane
            $table->primary(['region', 'window_start_ms']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('order_window_counts');
    }
};

The Laravel angle ​

Laravel has no stream-processing layer and does not need one for rolling up a few thousand events a minute into a dashboard table. Laravel 13 documents the queue drivers "included with the framework, including the database, Amazon SQS, Redis, and Beanstalkd drivers"; they are job queues, not logs, so a processed job cannot be replayed. The documented pieces that matter here are Redis::eval for atomic scripts, DB::table()->upsert() (which needs a primary or unique index on the conflict columns), lockForUpdate(), #[Signature]/#[Description] console attributes and Schedule::command()->everyMinute()->withoutOverlapping()->onOneServer(). Joins, session windows, many keys or exactly-once output are the point at which the work belongs in Kafka Streams or Flink, with Laravel reading the output table.

Broker differences ​

RabbitMQ ​

RabbitMQ has no window operator, no watermark and no state store, and a classic or quorum queue cannot be replayed: once acked, a message is gone. RabbitMQ Streams are different: "any consumer can start reading/consuming from any point in the log" via the x-stream-offset consumer argument, which accepts first, last, an offset, a timestamp or an interval. The timestamp is "based on message arrival time (not application-provided timestamps)" and, with AMQP 0-9-1, has one-second accuracy; consumers "attach at a chunk boundary and can receive messages published shortly before the specified timestamp", so a time-based seek must still filter. That is ingestion-time positioning, not an event-time window.

A hand-rolled consumer can use the unacked messages as its window state: hold each ack until the window is evicted, and a crash redelivers the open windows. The watermark must be stored durably before the acks, otherwise a restarted consumer would accept records for windows it already closed. Limits: prefetch must cover every unacked message of every open window (when it is full, deliveries stop and the watermark can never move), consumer_timeout (30 minutes by default) caps window plus lateness, and single active consumer is needed so one process sees a whole window.

go
// Command rabbitmq hand-rolls an event-time window on a RabbitMQ quorum
// queue. A queue forgets a message once it is acked, so there is no log to
// replay and no state store. The trick: keep every message UNACKED until
// its window is evicted (end + allowed lateness passed by the watermark).
// The unacked messages are the window state; after a crash RabbitMQ
// redelivers them and the windows are rebuilt.
//
// The watermark itself must survive a crash, or a restarted consumer would
// accept records for windows it already closed and emit a half-empty pane.
// It is written to a file before the acks; in production write it in the
// same database transaction that upserts the panes.
//
// Limits: prefetch must exceed (peak rate x (size + out-of-orderness +
// lateness)), consumer_timeout (30 minutes by default) bounds how long a
// message may stay unacked, and the watermark moves only when messages arrive.
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"time"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/stream-processing/window"
)

const (
	queue    = "orders.windowing"
	prefetch = 20000
	size     = time.Minute
	lateness = 2 * time.Minute
)

type orderPlaced struct {
	Region      string    `json:"region"`
	OccurredAt  time.Time `json:"occurred_at"`
	AmountCents int64     `json:"amount_cents"`
}

func main() {
	url := os.Getenv("AMQP_URL")
	if url == "" {
		fmt.Println("set AMQP_URL to run")
		return
	}
	metaFile := os.Getenv("WINDOWER_META")
	if metaFile == "" {
		metaFile = "windower-meta.json"
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
	ch, err := conn.Channel()
	if err != nil {
		log.Fatal(err)
	}

	// Competing consumers would each see a slice of every window and emit
	// partial counts; single active consumer keeps one window in one process.
	_, err = ch.QueueDeclare(queue, true, false, false, false, amqp.Table{
		"x-queue-type":              "quorum",
		"x-single-active-consumer":  true,
		"x-dead-letter-exchange":    "orders.dlx", // side output: too late or unparseable
		"x-dead-letter-routing-key": "orders.windowing.rejected",
	})
	if err != nil {
		log.Fatal(err)
	}
	if err := ch.Qos(prefetch, 0, false); err != nil {
		log.Fatal(err)
	}
	deliveries, err := ch.Consume(queue, "windower", false, false, false, false, nil)
	if err != nil {
		log.Fatal(err)
	}

	op, err := window.New(window.Config{
		Kind: window.Tumbling, Size: size,
		OutOfOrderness: 30 * time.Second, AllowedLateness: lateness,
	})
	if err != nil {
		log.Fatal(err)
	}
	if b, err := os.ReadFile(metaFile); err == nil {
		var m window.Meta
		if json.Unmarshal(b, &m) == nil {
			op.RestoreMeta(m, time.Now())
		}
	}

	pending := map[int64][]uint64{} // window start (ms) -> unacked delivery tags
	unacked := 0
	for d := range deliveries {
		var o orderPlaced
		if json.Unmarshal(d.Body, &o) != nil || o.OccurredAt.IsZero() {
			must(d.Reject(false)) // dead-lettered
			continue
		}
		now := time.Now()
		res := op.Add(window.Record{Partition: queue, Key: o.Region, EventTime: o.OccurredAt, Value: o.AmountCents}, now)
		if res.Outcome == window.TooLate {
			// Duplicates are possible here after a crash; dedup by event id downstream.
			must(d.Reject(false))
			continue
		}
		ms := o.OccurredAt.UnixMilli()
		start := ms - ms%size.Milliseconds() // the same epoch-aligned window the operator used
		pending[start] = append(pending[start], d.DeliveryTag)
		unacked++
		if unacked >= prefetch {
			log.Printf("window state reached prefetch=%d: no more deliveries, the watermark cannot move", prefetch)
		}

		for _, p := range op.Advance(now) {
			// Sink: upsert by (region, window start); a late pane overwrites.
			fmt.Printf("%s [%s) orders=%d cents=%d %s#%d\n", p.Key, p.Start.Format(time.RFC3339), p.Count, p.Sum, p.Timing, p.Index)
		}
		wm, ok := op.Watermark()
		if !ok {
			continue
		}
		var evicted []int64
		for s := range pending {
			if s+(size+lateness).Milliseconds() <= wm.UnixMilli() {
				evicted = append(evicted, s)
			}
		}
		if len(evicted) == 0 {
			continue
		}
		saveMeta(metaFile, op.Meta()) // first make the watermark durable ...
		for _, s := range evicted {   // ... then let RabbitMQ forget the inputs
			for _, tag := range pending[s] {
				must(ch.Ack(tag, false))
			}
			unacked -= len(pending[s])
			delete(pending, s)
		}
	}
}

func saveMeta(path string, m window.Meta) {
	b, _ := json.Marshal(m)
	tmp := path + ".tmp"
	if err := os.WriteFile(tmp, b, 0o600); err != nil {
		log.Fatal(err)
	}
	if err := os.Rename(tmp, path); err != nil {
		log.Fatal(err)
	}
}

func must(err error) {
	if err != nil {
		log.Fatal(err) // a failed ack/reject leaves the channel unusable
	}
}

The Laravel variant keeps the state in Redis and acks immediately after the atomic ingest, using the vladimir-yuldashev/laravel-queue-rabbitmq custom job class documented in its README.

php
<?php

namespace App\Queue\Jobs;

use App\Streams\EventTimeWindows;
use VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Jobs\RabbitMQJob as BaseJob;

/**
 * vladimir-yuldashev/laravel-queue-rabbitmq: registered under
 * 'options' => ['queue' => ['job' => RabbitMQJob::class]] in config/queue.php,
 * so raw JSON events from a non-Laravel producer land here. Consumed with
 * the package's rabbitmq:consume command (basic_consume).
 *
 * The window state lives in Redis, so the message is acked right after the
 * atomic ingest. The queue cannot be replayed: fixing a bug in this code
 * cannot recompute last hour's windows unless the producer resends.
 */
class RabbitMQJob extends BaseJob
{
    public function fire()
    {
        $event = json_decode($this->getRawBody(), true, flags: JSON_THROW_ON_ERROR);

        $this->resolve(EventTimeWindows::class)->record(
            $event['event_id'],
            $event['region'],
            (int) (new \DateTimeImmutable($event['occurred_at']))->format('Uv'),
            (int) $event['amount_cents'],
        );

        $this->delete(); // ack only after Redis accepted (or side-output) the event
    }

    public function getName()
    {
        return 'order-windows';
    }
}

Kafka ​

Kafka is the only one of the three with a real stream-processing ecosystem: Kafka Streams (a library) and ksqlDB on top of the log, Flink and Spark as external engines. They provide event-time windows with grace, RocksDB state with changelogs, repartitioning, KTable joins and exactly-once commits. From Go you get the transactional building block. This snippet is a hand-rolled Kafka Streams task: one operator per input partition, state changes written to a co-partitioned compacted changelog, panes plus changelog plus offsets in one transaction, restore before fetching, and a full rebuild after any abort.

go
// Command kafka is a hand-rolled version of what Kafka Streams does for a
// windowed count with processing.guarantee=exactly_once_v2:
//
//   - one task (window operator) per input partition, as in Kafka Streams;
//   - every state change goes to a compacted changelog topic partition with
//     the same number as the input partition (co-partitioned);
//   - panes, side-output records, changelog records and the consumed offsets
//     commit in ONE Kafka transaction (consume-transform-produce, KIP-447);
//   - on assignment a task is rebuilt from its changelog before fetching;
//   - on any abort the session is torn down and rebuilt, so in-memory state
//     never contains work from an aborted transaction.
//
// Topics (create them with the same partition count, compacted where noted):
// orders (input, key = region), orders-per-region-minute (compacted),
// orders-windower-changelog (compacted), orders-too-late.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/twmb/franz-go/pkg/kadm"
	"github.com/twmb/franz-go/pkg/kgo"

	"academy/stream-processing/window"
)

const (
	inputTopic     = "orders"
	outputTopic    = "orders-per-region-minute"
	changelogTopic = "orders-windower-changelog"
	lateTopic      = "orders-too-late"
	group          = "orders-windower"
)

type orderPlaced struct {
	OccurredAt  time.Time `json:"occurred_at"` // event time, stamped by the producer
	AmountCents int64     `json:"amount_cents"`
}

func newTask() *window.Operator {
	op, err := window.New(window.Config{
		Kind:            window.Tumbling,
		Size:            time.Minute,
		OutOfOrderness:  30 * time.Second,
		AllowedLateness: 5 * time.Minute,
		Mode:            window.Accumulating,
	})
	if err != nil {
		panic(err)
	}
	return op
}

func main() {
	brokers := os.Getenv("KAFKA_BROKERS")
	if brokers == "" {
		fmt.Println("set KAFKA_BROKERS to run")
		return
	}
	seeds := strings.Split(brokers, ",")
	for {
		err := run(context.Background(), seeds)
		log.Printf("session ended, rebuilding from changelog: %v", err)
		time.Sleep(time.Second)
	}
}

func run(ctx context.Context, seeds []string) error {
	var mu sync.Mutex
	tasks := map[int32]*window.Operator{}
	var restoreErr error

	host, _ := os.Hostname()
	sess, err := kgo.NewGroupTransactSession(
		kgo.SeedBrokers(seeds...),
		kgo.TransactionalID(group+"-"+host),
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(inputTopic),
		kgo.FetchIsolationLevel(kgo.ReadCommitted()), // never read aborted input
		kgo.RecordPartitioner(kgo.ManualPartitioner()),
		kgo.OnPartitionsAssigned(func(ctx context.Context, _ *kgo.Client, m map[string][]int32) {
			for _, p := range m[inputTopic] {
				op, err := restore(ctx, seeds, p)
				mu.Lock()
				if err != nil {
					restoreErr = err
				}
				tasks[p] = op
				mu.Unlock()
			}
		}),
		kgo.OnPartitionsRevoked(dropTasks(&mu, tasks)),
		kgo.OnPartitionsLost(dropTasks(&mu, tasks)),
	)
	if err != nil {
		return err
	}
	defer sess.Close()

	for {
		fetches := sess.PollFetches(ctx)
		if fetches.IsClientClosed() {
			return errors.New("client closed")
		}
		fetches.EachError(func(t string, p int32, err error) { log.Printf("fetch %s/%d: %v", t, p, err) })
		if err := sess.Begin(); err != nil {
			return err
		}
		now := time.Now()
		var out []*kgo.Record

		mu.Lock()
		if restoreErr != nil {
			mu.Unlock()
			return restoreErr
		}
		fetches.EachRecord(func(r *kgo.Record) {
			op := tasks[r.Partition]
			if op == nil {
				return // revoked during the poll; this transaction will abort
			}
			var o orderPlaced
			if json.Unmarshal(r.Value, &o) != nil || o.OccurredAt.IsZero() {
				out = append(out, side(r, "unparseable"))
				return
			}
			res := op.Add(window.Record{
				Partition: fmt.Sprint(inputTopic, "/", r.Partition),
				Key:       string(r.Key), EventTime: o.OccurredAt, Value: o.AmountCents,
			}, now)
			if res.Outcome == window.TooLate {
				out = append(out, side(r, "too-late")) // never drop silently
			}
		})
		for p, op := range tasks {
			for _, pane := range op.Advance(now) {
				out = append(out, paneRecord(p, pane))
			}
			out = append(out, changelog(p, op)...)
		}
		mu.Unlock()

		commit := kgo.TryCommit
		if err := sess.ProduceSync(ctx, out...).FirstErr(); err != nil {
			log.Printf("produce failed, aborting: %v", err)
			commit = kgo.TryAbort
		}
		// Panes, changelog, side output and input offsets: all or nothing.
		committed, err := sess.End(ctx, commit)
		if err != nil {
			return err
		}
		if !committed {
			return errors.New("transaction aborted (rebalance or produce error)")
		}
	}
}

func dropTasks(mu *sync.Mutex, tasks map[int32]*window.Operator) func(context.Context, *kgo.Client, map[string][]int32) {
	return func(_ context.Context, _ *kgo.Client, m map[string][]int32) {
		mu.Lock()
		defer mu.Unlock()
		for _, p := range m[inputTopic] {
			delete(tasks, p) // the new owner restores it from the changelog
		}
	}
}

func side(r *kgo.Record, reason string) *kgo.Record {
	return &kgo.Record{
		Topic: lateTopic, Partition: r.Partition, Key: r.Key, Value: r.Value,
		Headers: []kgo.RecordHeader{{Key: "reason", Value: []byte(reason)}},
	}
}

// paneRecord is keyed by region and window start, so the compacted output
// topic keeps the latest (accumulating) pane per window.
func paneRecord(p int32, pane window.Pane) *kgo.Record {
	v, _ := json.Marshal(map[string]any{
		"region": pane.Key, "window_start": pane.Start, "window_end": pane.End,
		"orders": pane.Count, "amount_cents": pane.Sum,
		"timing": pane.Timing.String(), "pane_index": pane.Index,
	})
	key := pane.Key + "|" + strconv.FormatInt(pane.Start.UnixMilli(), 10)
	return &kgo.Record{Topic: outputTopic, Partition: p, Key: []byte(key), Value: v}
}

// changelog turns state changes into records: "w|start|end|key" carries a
// window (nil value = tombstone), "meta" carries the watermark.
func changelog(p int32, op *window.Operator) []*kgo.Record {
	var out []*kgo.Record
	for _, st := range op.TakeChanges() {
		key := fmt.Sprintf("w|%d|%d|%s", st.Span.Start, st.Span.End, st.Key)
		var v []byte
		if !st.Deleted {
			v, _ = json.Marshal(st)
		}
		out = append(out, &kgo.Record{Topic: changelogTopic, Partition: p, Key: []byte(key), Value: v})
	}
	if len(out) == 0 {
		return nil // nothing changed: no new changelog record either
	}
	meta, _ := json.Marshal(op.Meta())
	return append(out, &kgo.Record{Topic: changelogTopic, Partition: p, Key: []byte("meta"), Value: meta})
}

// restore replays one changelog partition, read_committed, up to the end
// offset seen when restoration started. Control records are kept so the
// loop can recognise the last offset even when it is a commit marker.
func restore(ctx context.Context, seeds []string, p int32) (*window.Operator, error) {
	op := newTask()
	ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
	defer cancel()

	adm, err := kgo.NewClient(kgo.SeedBrokers(seeds...))
	if err != nil {
		return op, err
	}
	defer adm.Close()
	ka := kadm.NewClient(adm)
	starts, err := ka.ListStartOffsets(ctx, changelogTopic)
	if err != nil {
		return op, err
	}
	ends, err := ka.ListEndOffsets(ctx, changelogTopic)
	if err != nil {
		return op, err
	}
	s, ok1 := starts.Lookup(changelogTopic, p)
	e, ok2 := ends.Lookup(changelogTopic, p)
	if !ok1 || !ok2 || s.Err != nil || e.Err != nil {
		return op, fmt.Errorf("changelog partition %d not found (co-partitioned topics?)", p)
	}
	if e.Offset <= s.Offset {
		return op, nil // empty changelog: a brand-new task
	}

	cl, err := kgo.NewClient(
		kgo.SeedBrokers(seeds...),
		kgo.ConsumePartitions(map[string]map[int32]kgo.Offset{changelogTopic: {p: kgo.NewOffset().AtStart()}}),
		kgo.FetchIsolationLevel(kgo.ReadCommitted()),
		kgo.KeepControlRecords(),
	)
	if err != nil {
		return op, err
	}
	defer cl.Close()
	for {
		f := cl.PollFetches(ctx)
		if errs := f.Errors(); len(errs) > 0 {
			return op, errs[0].Err
		}
		done := false
		f.EachRecord(func(r *kgo.Record) {
			if r.Offset+1 >= e.Offset {
				done = true
			}
			if !r.Attrs.IsControl() {
				apply(op, r)
			}
		})
		if done {
			return op, nil
		}
	}
}

func apply(op *window.Operator, r *kgo.Record) {
	k := string(r.Key)
	if k == "meta" {
		var m window.Meta
		if json.Unmarshal(r.Value, &m) == nil {
			op.RestoreMeta(m, time.Now())
		}
		return
	}
	parts := strings.SplitN(k, "|", 4)
	if len(parts) != 4 || parts[0] != "w" {
		return
	}
	if r.Value == nil {
		start, _ := strconv.ParseInt(parts[1], 10, 64)
		end, _ := strconv.ParseInt(parts[2], 10, 64)
		op.Restore(window.State{Key: parts[3], Span: window.Span{Start: start, End: end}, Deleted: true})
		return
	}
	var st window.State
	if json.Unmarshal(r.Value, &st) == nil {
		op.Restore(st)
	}
}

mateusjunges/laravel-kafka gives PHP a consumer (Kafka::consumer(topics, groupId), withManualCommit(), $consumer->commit($message)), not a processor. It feeds the same Redis windows; the per-window event-id set makes redelivery harmless, and because the topic is a log, resetting the group offsets can rebuild windows that are still open.

php
<?php

namespace App\Console\Commands;

use App\Streams\EventTimeWindows;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;

/**
 * mateusjunges/laravel-kafka 2.x feeding the same Redis windows. There is
 * no Kafka Streams for PHP: no local state store, no changelog topic, no
 * exactly_once_v2. Redis writes and offset commits are separate; the event
 * id dedup set makes the at-least-once redelivery harmless, and because the
 * topic is a log, a reset of the group offsets can rebuild open windows.
 */
#[Signature('orders:consume-kafka')]
#[Description('Feed order events from Kafka into event-time windows')]
final class ConsumeOrdersFromKafka extends Command
{
    public function handle(EventTimeWindows $windows): int
    {
        Kafka::consumer(['orders'], 'order-windows-php')
            ->withManualCommit()
            ->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) use ($windows) {
                $body = $message->getBody();
                $event = is_array($body) ? $body : json_decode($body, true, flags: JSON_THROW_ON_ERROR);

                $windows->record(
                    $event['event_id'],
                    $event['region'],
                    (int) (new \DateTimeImmutable($event['occurred_at']))->format('Uv'),
                    (int) $event['amount_cents'],
                );

                $consumer->commit($message); // after the atomic Redis ingest
            })
            ->build()
            ->consume();

        return self::SUCCESS;
    }
}

Redis Streams ​

Redis has no window operator either. The XRANGE documentation lists "Returning items in a specific time range. This is possible because Stream IDs are related to time." An auto-generated ID is the server clock at XADD, so XRANGE windows are ingestion-time windows. For event time, the Go consumer keeps a max-event-time key, a dedup set and an aggregate per window, a zset of open windows scored by window end, and two Lua scripts with all keys under one {orders} hash tag; panes and too-late records go to their own streams.

go
// Command redis windows a Redis stream by EVENT time. Redis has no window
// operator, no watermark and no state store, so this builds them from
// primitives: a max-event-time key (the watermark source), one set of event
// ids and one aggregate hash per window, a zset of open windows scored by
// window end, and two Lua scripts that make ingest and close atomic. Panes
// go to a stream, too-late events to another: nothing is dropped silently.
//
// Every key carries the {orders} hash tag so one script's keys share a
// Redis Cluster slot. Run ONE consumer per stream for this design: the
// watermark is a single max, so it does not wait for slower producers.
package main

import (
	"context"
	_ "embed"
	"errors"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"
)

//go:embed ingest.lua
var ingestLua string

//go:embed close.lua
var closeLua string

var (
	ingest = redis.NewScript(ingestLua)
	closer = redis.NewScript(closeLua)
)

const (
	stream   = "orders"
	group    = "order-windows"
	maxKey   = "{orders}:win:max"
	openKey  = "{orders}:win:open"
	stateKey = "{orders}:win:state"
	panesKey = "{orders}:panes"
	lateKey  = "{orders}:too-late"
	badKey   = "{orders}:invalid"
	sizeMs   = int64(60_000)  // one-minute tumbling windows
	delayMs  = int64(30_000)  // watermark = max event time - 30s
	graceMs  = int64(120_000) // allowed lateness
)

func idsKey(m string) string { return "{orders}:win:ids:" + m }
func aggKey(m string) string { return "{orders}:win:agg:" + m }

func main() {
	addr := os.Getenv("REDIS_ADDR")
	if addr == "" {
		fmt.Println("set REDIS_ADDR to run")
		return
	}
	ctx := context.Background()
	rdb := redis.NewClient(&redis.Options{Addr: addr})
	if err := rdb.XGroupCreateMkStream(ctx, stream, group, "0").Err(); err != nil &&
		!strings.HasPrefix(err.Error(), "BUSYGROUP") {
		log.Fatal(err)
	}
	host, _ := os.Hostname()
	for {
		res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group: group, Consumer: host,
			Streams: []string{stream, ">"}, Count: 500, Block: 5 * time.Second,
		}).Result()
		if err != nil && !errors.Is(err, redis.Nil) {
			log.Fatal(err)
		}
		for _, s := range res {
			for _, m := range s.Messages {
				if err := handle(ctx, rdb, m); err != nil {
					log.Fatal(err) // not acked: stays in the PEL for XAUTOCLAIM
				}
				if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
					log.Fatal(err)
				}
			}
		}
		if err := closeWindows(ctx, rdb); err != nil {
			log.Fatal(err)
		}
	}
}

func handle(ctx context.Context, rdb *redis.Client, m redis.XMessage) error {
	eventID, _ := m.Values["event_id"].(string)
	region, _ := m.Values["region"].(string)
	at, _ := m.Values["occurred_at"].(string)
	cents, _ := m.Values["amount_cents"].(string)
	t, perr := time.Parse(time.RFC3339Nano, at)
	if eventID == "" || region == "" || perr != nil || strings.Contains(region, "|") {
		return rdb.XAdd(ctx, &redis.XAddArgs{Stream: badKey, Values: m.Values}).Err()
	}
	ts := t.UnixMilli()
	start := ts - ts%sizeMs
	member := region + "|" + strconv.FormatInt(start, 10)
	return ingest.Run(ctx, rdb,
		[]string{maxKey, openKey, stateKey, idsKey(member), aggKey(member), lateKey},
		eventID, ts, cents, start, sizeMs, delayMs, graceMs, member, region,
	).Err()
}

// closeWindows fires every window whose end the watermark passed and evicts
// those past the grace period. Run it from ONE process; each call is atomic
// and idempotent, so a crash between windows is harmless.
func closeWindows(ctx context.Context, rdb *redis.Client) error {
	maxSeen, err := rdb.Get(ctx, maxKey).Int64()
	if errors.Is(err, redis.Nil) {
		return nil
	} else if err != nil {
		return err
	}
	wm := maxSeen - delayMs
	members, err := rdb.ZRangeByScore(ctx, openKey, &redis.ZRangeBy{Min: "-inf", Max: strconv.FormatInt(wm, 10)}).Result()
	if err != nil {
		return err
	}
	for _, member := range members {
		region, startStr, _ := strings.Cut(member, "|")
		start, _ := strconv.ParseInt(startStr, 10, 64)
		err := closer.Run(ctx, rdb,
			[]string{maxKey, openKey, stateKey, idsKey(member), aggKey(member), panesKey},
			member, start, start+sizeMs, delayMs, graceMs, region,
		).Err()
		if err != nil && !errors.Is(err, redis.Nil) {
			return err
		}
	}
	return nil
}

// ingestionCount counts entries XADDed during [start, start+size). An
// auto-generated stream ID is the Redis server clock at XADD, so this is
// INGESTION time: a phone that buffered orders offline lands in the minute
// it reconnected. The end ID is incomplete; XRANGE completes it to the last
// sequence number of that millisecond.
func ingestionCount(ctx context.Context, rdb *redis.Client, start time.Time, size time.Duration) (int, error) {
	from := strconv.FormatInt(start.UnixMilli(), 10)
	to := strconv.FormatInt(start.Add(size).UnixMilli()-1, 10)
	msgs, err := rdb.XRange(ctx, stream, from, to).Result() // page with XRangeN for big windows
	return len(msgs), err
}

// perMinuteTimeSeries is the shortest path when a per-minute aggregate of
// numbers is all you need: TS.ADD at the EVENT timestamp, then TS.RANGE
// with a COUNT aggregation in 60s buckets (epoch aligned without ALIGN).
// There is no watermark or late-pane signal: a backfilled sample silently
// changes the bucket the next time you query it.
func perMinuteTimeSeries(ctx context.Context, rdb *redis.Client, eventTime time.Time, cents float64, from, to time.Time) ([]redis.TSTimestampValue, error) {
	if err := rdb.TSAdd(ctx, "{orders}:ts:cents", eventTime.UnixMilli(), cents).Err(); err != nil {
		return nil, err
	}
	return rdb.TSRangeWithArgs(ctx, "{orders}:ts:cents", int(from.UnixMilli()), int(to.UnixMilli()),
		&redis.TSRangeOptions{Aggregator: redis.Count, BucketDuration: 60_000}).Result()
}

var _, _ = ingestionCount, perMinuteTimeSeries // documented helpers, not called by main
lua
-- Atomic ingest of one event into an event-time window kept in Redis.
-- KEYS: 1 max event time, 2 open windows (zset, score = end), 3 pane state (hash),
--       4 event ids of this window (set), 5 aggregate of this window (hash), 6 too-late stream
-- ARGV: 1 event_id, 2 event time ms, 3 amount_cents, 4 window start ms,
--       5 size ms, 6 out-of-orderness ms, 7 grace ms, 8 member "region|start", 9 region
-- Returns 1 accepted, 2 duplicate (redelivery), 3 accepted late, 0 too late.
local ts = tonumber(ARGV[2])
local max = tonumber(redis.call('GET', KEYS[1]) or '')
local window_end = tonumber(ARGV[4]) + tonumber(ARGV[5])
-- Same rule as the Go operator: refuse once end + grace <= watermark.
if max and window_end + tonumber(ARGV[7]) <= max - tonumber(ARGV[6]) then
  redis.call('XADD', KEYS[6], '*', 'event_id', ARGV[1], 'occurred_at_ms', ARGV[2], 'region', ARGV[9])
  return 0
end
if (not max) or ts > max then
  redis.call('SET', KEYS[1], ARGV[2])
end
if redis.call('SADD', KEYS[4], ARGV[1]) == 0 then
  return 2
end
redis.call('HINCRBY', KEYS[5], 'cents', ARGV[3])
redis.call('ZADD', KEYS[2], window_end, ARGV[8])
if redis.call('HGET', KEYS[3], ARGV[8]) == 'fired' then
  redis.call('HSET', KEYS[3], ARGV[8], 'dirty')
  return 3
end
return 1
lua
-- Fire and, when grace has passed, evict ONE window. Idempotent.
-- KEYS: 1 max event time, 2 open windows, 3 pane state, 4 event ids, 5 aggregate, 6 panes stream
-- ARGV: 1 member "region|start", 2 window start ms, 3 window end ms,
--       4 out-of-orderness ms, 5 grace ms, 6 region
-- Returns 1 if a pane was emitted, else 0.
local max = tonumber(redis.call('GET', KEYS[1]) or '')
if not max then
  return 0
end
local wm = max - tonumber(ARGV[4])
local window_end = tonumber(ARGV[3])
if window_end > wm then
  return 0
end
local st = redis.call('HGET', KEYS[3], ARGV[1])
local emitted = 0
if st ~= 'fired' then
  local timing = 'on-time'
  if st == 'dirty' then
    timing = 'late'
  end
  -- Accumulating pane: the absolute count, so the sink can upsert it.
  redis.call('XADD', KEYS[6], '*', 'region', ARGV[6], 'window_start', ARGV[2], 'window_end', ARGV[3],
    'orders', redis.call('SCARD', KEYS[4]), 'amount_cents', redis.call('HGET', KEYS[5], 'cents') or '0',
    'timing', timing)
  redis.call('HSET', KEYS[3], ARGV[1], 'fired')
  emitted = 1
end
if window_end + tonumber(ARGV[5]) <= wm then
  redis.call('DEL', KEYS[4], KEYS[5])
  redis.call('ZREM', KEYS[2], ARGV[1])
  redis.call('HDEL', KEYS[3], ARGV[1])
end
return emitted

Redis TimeSeries is the short path when a numeric per-bucket aggregate is enough: TS.ADD at the event timestamp, then TS.RANGE ... AGGREGATION count 60000; "Without ALIGN, bucket start times are multiples of bucketDuration". TS.CREATERULE maintains a compacted series, but "Only new samples that are added into the source series after the creation of the rule will be aggregated." Neither gives a watermark or a late-pane signal. The Laravel consumer reads the same stream with Redis::xreadgroup and acks after the ingest.

php
<?php

namespace App\Console\Commands;

use App\Streams\EventTimeWindows;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

/**
 * Raw Redis Streams through the Redis facade (phpredis). Laravel's redis
 * queue driver uses lists and sorted sets, not streams.
 */
#[Signature('orders:consume-stream')]
#[Description('Feed the orders stream into event-time windows')]
final class ConsumeOrdersFromRedisStream extends Command
{
    public function handle(EventTimeWindows $windows): int
    {
        try {
            Redis::xgroup('CREATE', 'orders', 'order-windows', '0', true); // MKSTREAM
        } catch (\RedisException) {
            // BUSYGROUP: the group already exists
        }

        while (true) {
            $batch = Redis::xreadgroup('order-windows', gethostname(), ['orders' => '>'], 500, 5000);
            foreach ($batch ?: [] as $entries) {
                foreach ($entries as $id => $fields) {
                    $windows->record(
                        $fields['event_id'],
                        $fields['region'],
                        (int) (new \DateTimeImmutable($fields['occurred_at']))->format('Uv'),
                        (int) $fields['amount_cents'],
                    );
                    Redis::xack('orders', 'order-windows', [$id]); // after the ingest
                }
            }
            $windows->closeReady(); // single consumer: it may also be the closer
        }
    }

    /**
     * Entries XADDed during [start, start + 60s): INGESTION time, because an
     * auto-generated ID is the Redis server clock at XADD.
     */
    public static function ingestedDuringMinute(int $startMs): int
    {
        return count(Redis::xrange('orders', (string) $startMs, (string) ($startMs + 59_999)));
    }
}

In production systems ​

  • Kafka Streams documents RocksDB as the default persistent key-value store, compacted changelog topics per store, and num.standby.replicas to avoid long restores after task migration (Kafka 4.4 docs, Processor API and Architecture).
  • Kafka Streams final-only window results come from suppress(Suppressed.untilWindowCloses(...)) (KIP-328); without it, a windowed count() emits intermediate updates limited only by the record cache and commit interval.
  • Flink's end-to-end exactly-once with Kafka arrived with TwoPhaseCommitSinkFunction in Flink 1.4.0, released in December 2017, as described on the Flink blog in February 2018.
  • ksqlDB's default grace period is 24 hours when none is specified, which keeps window state for a day; set it explicitly.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A shop counts orders per minute for its admin dashboard. The simplest correct design needs no stream processor: store occurred_at on the order row and compute GROUP BY date_trunc('minute', occurred_at) on read, or keep a small summary table updated by an upsert in the same transaction as the order. The concepts still apply: group by event time, and decide when a minute is final (for example "two minutes after it ends").

Modular monolith: one deployment, several modules ​

Orders, payments and fulfilment are modules with their own tables. A reporting module needs "orders paid within 10 minutes of placement". Emitting domain events into an in-process bus and joining them in memory loses state on restart; a persistent outbox table plus a scheduled job that joins by order id in SQL is the honest monolith version of a windowed stream-stream join.

Microservices: events across service boundaries ​

Orders publishes OrderPlaced to Kafka (key region), Payments publishes PaymentCaptured (key order_id). An analytics service runs Kafka Streams: re-key payments by order id (a repartition topic appears), join with orders within a 15-minute JoinWindows, window the joined stream per region per minute with a 2-minute grace, suppress until the window closes, and write orders-paid-per-minute with exactly_once_v2. A Laravel dashboard reads that compacted topic into a table with idempotent upserts. The outbox makes the source events reliable; CDC is the alternative feed.

Distributed data: replicas, caches and multiple regions ​

Two regions each produce to a local cluster and mirror to a central one. Mirroring adds skew, so the central job's out-of-orderness bound must include replication lag, and a partition fed only by a quiet region needs idleness handling. Processing-time windows here would mix up regions' lag with business volume. State store restores move across availability zones; standby replicas placed with rack awareness reduce failover time. Cached dashboards must accept that a minute can still change until its lateness horizon has passed.

Scaling path ​

LoadDesignExample
1×SQL GROUP BY on event time, or Redis Lua windowsAdmin dashboard over thousands of orders per hour
10×Kafka Streams or ksqlDB, 12 partitions, grace and suppressPer-region revenue per minute, EOS output topic
100×Flink or Kafka Streams with RocksDB, standbys, careful keys, idlenessFraud features over millions of cards, joins with reference tables

Lab ​

1. Run the window operator (run on the host) ​

bash
cd docs/snippets/messaging/stream-processing/go
go test ./window
go run ./after

Output of go run ./after, produced on the host for this page:

text
t+1s   orders/0 eu event=12:00:10 -> on time
t+2s   orders/1 us event=12:00:15 -> on time
        watermark 11:59:40, open windows 2
t+3s   orders/0 eu event=12:00:50 -> on time
        watermark 11:59:45, open windows 2
t+4s   orders/0 eu event=12:01:40 -> on time
        watermark 11:59:45, open windows 3
t+5s   orders/1 us event=12:01:35 -> on time
        pane eu [12:00,12:01) orders=2 cents=1650 on-time#0
        pane us [12:00,12:01) orders=1 cents=900 on-time#0
        watermark 12:01:05, open windows 4
t+6s   orders/1 us event=12:00:40 -> late (accepted)
        pane us [12:00,12:01) orders=2 cents=1700 late#1
        watermark 12:01:05, open windows 4
t+7s   orders/0 eu event=12:04:10 -> on time
        watermark 12:01:05, open windows 5
t+1m40s orders/0 eu event=12:04:20 -> on time
        pane eu [12:01,12:02) orders=1 cents=700 on-time#0
        pane us [12:01,12:02) orders=1 cents=300 on-time#0
        watermark 12:03:50, open windows 3
t+1m41s orders/1 us event=12:00:50 -> too late -> side output
        watermark 12:03:50, open windows 3
t+1m42s orders/1 us event=12:03:55 -> on time
        watermark 12:03:50, open windows 4
t+1m43s orders/0 eu event=12:06:10 -> on time
        watermark 12:03:50, open windows 5
t+1m44s orders/1 us event=12:07:00 -> on time
        pane us [12:03,12:04) orders=1 cents=100 on-time#0
        pane eu [12:04,12:05) orders=2 cents=1150 on-time#0
        watermark 12:05:40, open windows 4

Read it against the concepts: the watermark waits for partition 1 (steps 1–2), the late us record produces an accumulating late pane, partition 1 goes idle after 60 s of silence and releases the watermark, the [12:00,12:01) windows are evicted at 12:03 and the next record for them is too late, and the watermark never moves backwards when partition 1 wakes up. Change Mode to window.Discarding and the late pane shows orders=1 cents=800.

2. Kafka timestamp type (expected, not run) ​

bash
kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics \
  --entity-name orders --add-config message.timestamp.type=LogAppendTime
kafka-console-producer.sh --bootstrap-server localhost:9092 --topic orders \
  --property parse.key=true --property key.separator=:
# eu:{"occurred_at":"2026-11-26T12:04:10Z","amount_cents":1200}
kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic orders \
  --from-beginning --property print.timestamp=true
# expected, not run: LogAppendTime:<broker time>, not 12:04:10; the payload still carries event time

3. Exactly-once windowing with the Go Kafka task (expected, not run) ​

Create orders, orders-per-region-minute (compacted), orders-windower-changelog (compacted) and orders-too-late, all with 3 partitions. Run KAFKA_BROKERS=localhost:9092 go run ./kafka, produce a few orders, then kill the process with kill -9 and start it again.

text
1 first run: panes for eu [12:00,12:01) appear in orders-per-region-minute (read_committed)
2 kill -9 during a transaction: that transaction aborts; read_committed consumers never see it
3 restart: "changelog partition N" restored before fetching; offsets resume from the last commit
4 expected, not run: no window count is doubled, no pane disappears

4. RabbitMQ window held in unacked messages (expected, not run) ​

bash
AMQP_URL=amqp://guest:guest@localhost:5672/ go run ./rabbitmq
rabbitmqctl list_queues name messages_ready messages_unacknowledged
# expected, not run: messages_unacknowledged grows while windows are open and
# drops when a window passes end + 2 minutes of lateness

Stop the consumer with kill -9 while windows are open: the unacked messages return to the queue, the restarted consumer restores the watermark from windower-meta.json and rebuilds the open windows.

5. Redis windows and the ingestion-time trap (expected, not run) ​

bash
redis-cli XADD orders '*' event_id e1 region eu occurred_at 2026-11-26T12:04:10Z amount_cents 1200
redis-cli XADD orders '*' event_id e2 region eu occurred_at 2026-11-26T12:07:00Z amount_cents 500
REDIS_ADDR=localhost:6379 go run ./redis &
redis-cli XRANGE '{orders}:panes' - +
# expected, not run: pane eu window_start=<12:04 ms> orders=1 timing=on-time once the watermark passes 12:05
redis-cli XADD orders '*' event_id e1 region eu occurred_at 2026-11-26T12:04:10Z amount_cents 1200
# expected, not run: duplicate e1 is ignored (SADD returns 0); no second count

Compare with XRANGE orders <now-60000> <now>: both orders fall in the ingestion minute in which you typed them, regardless of occurred_at.

Common misconceptions ​

BeliefReality
The record timestamp is always event timeKafka CreateTime is whatever the producer set; LogAppendTime is ingestion time
Processing-time windows are fine for business metricsThey change with backlog, outages and replays
A watermark is a guaranteeA heuristic watermark is an estimate; late data still arrives
Watermark = newest timestamp seenNewest minus out-of-orderness, and the minimum across inputs
An idle partition is harmlessIt holds the watermark (or stream time) and no window closes
Late data is lost dataWithin allowed lateness/grace it is counted and causes a late pane
A window emits exactly onceKafka Streams and Flink emit updates unless you suppress or use a final-only trigger
"Sliding window" means the same everywhereFlink/Dataflow sliding = Kafka Streams hopping; Kafka SlidingWindows differ
State lives in KafkaIt lives in local RocksDB; Kafka holds the changelog for recovery
Any two topics with the same key can be joinedEqui-joins need co-partitioning; re-keying adds a repartition topic
More instances always means more throughputParallelism is capped by input partitions
exactly_once_v2 covers my HTTP callIt covers Kafka offsets, state and Kafka output only
RabbitMQ or Redis can do this nativelyNeither has windows, watermarks or state stores; you build them
ksqlDB windows close quickly by defaultThe default grace period is 24 hours

Cheat sheet ​

TopicRemember
TimeGroup by event time from the payload; processing time only for pipeline monitoring
Kafka timestampsmessage.timestamp.type: CreateTime (default) or LogAppendTime
Window boundsTumbling/hopping are [start, end), epoch aligned
NamingFlink sliding = Kafka Streams hopping
WatermarkMax minus delay, min across inputs, monotonic
Idle inputFlink withIdleness; Kafka Streams needs records; register partitions
LatenessFlink allowedLateness (0), Kafka Streams grace, ksqlDB 24 h default
Too lateSide output, never silent drop
PanesAccumulating for upserts, discarding for adders, retractions for sessions
Final onlysuppress(untilWindowCloses), EMIT FINAL
StateRocksDB + compacted changelog; standbys for fast failover
JoinsStream-stream needs a join window; equi-joins need co-partitioning
Exactly-onceexactly_once_v2 inside Kafka; Flink barriers + 2PC sinks
ScalingInput partitions cap tasks
RabbitMQ / RedisHand-rolled only; durable watermark, idempotent sink

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A phone buffers an order placed at 12:04:10 and sends it at 12:08:55. Which minute is it in, by event time and by ingestion time with LogAppendTime? Must-know ​

Answer

Answer: Event time: 12:04. With LogAppendTime the record timestamp is the broker append time, so 12:08 by ingestion time, even though the payload still says 12:04:10.

2 — With 10-minute windows advancing every 5 minutes, which windows contain 12:07? Must-know ​

Answer

Answer: [12:00, 12:10) and [12:05, 12:15): size divided by advance gives two windows, epoch aligned and half-open.

3 — Two partitions have maxima 12:05:00 and 12:01:30, out-of-orderness 30 s. What is the watermark, and what happens if the second partition goes silent? Important ​

Answer

Answer: 12:01:00, the minimum minus 30 s. If it stays silent the watermark stays there and later windows do not close, unless idleness detection marks it idle.

4 — Why does a single eviction rule (end + lateness ≤ watermark) for both state deletion and refusal matter? Good to know ​

Answer

Answer: If a window's state is deleted but records for it are still accepted, a new partial window is created and its pane overwrites the correct one with a smaller number.

5 — Which accumulation mode suits a sink that upserts by (region, window start), and which suits a counter that can only add? Important ​

Answer

Answer: Accumulating for the upsert sink, because each pane carries the full value; discarding for the add-only counter, because each pane carries only the delta.

6 — Why does a session merge need retractions? Good to know ​

Answer

Answer: The merged session has new bounds. Downstream rows keyed by the old sessions' bounds would otherwise remain as stale, overlapping results.

7 — What does exactly_once_v2 make atomic, and what does it not cover? Must-know ​

Answer

Answer: Input offset commits, state store changelog writes and output topic writes in one Kafka transaction. It does not cover external effects such as HTTP calls, emails or non-transactional databases.

8 — Two topics share the key customer_id, one has 12 partitions and the other 6. Can Kafka Streams equi-join them? Important ​

Answer

Answer: Not directly: co-partitioning requires the same partition count and partitioner. Repartition one side, or use a GlobalKTable or a foreign-key join where they fit.

9 — Why can the RabbitMQ hand-rolled window deadlock when prefetch is too small? Good to know ​

Answer

Answer: Open windows keep messages unacked. When unacked messages reach the prefetch limit, RabbitMQ stops delivering, so no newer record arrives to advance the watermark, and no window can close to release acks.

10 — Why are XRANGE time windows on a Redis stream ingestion-time windows? Important ​

Answer

Answer: Auto-generated stream IDs come from the Redis server clock at XADD, not from the event's own timestamp.

Glossary ​

TermMeaning
Bounded / unbounded dataFinite and complete versus endless input
Dataflow modelAkidau et al. 2015: what, where (event time), when (processing time), how (refinement)
Event timeWhen the event happened at the source
Ingestion timeWhen the broker stored the record
Processing timeWhen the processor read the record
message.timestamp.typeKafka topic config: CreateTime (producer) or LogAppendTime (broker)
TimestampExtractorKafka Streams plug-in that decides each record's timestamp
Stream timeKafka Streams per-task progress: the largest timestamp seen
Out-of-order dataRecords whose event time is older than records already seen
Window assignerFunction from a record to its windows
Tumbling windowFixed size, non-overlapping
Hopping windowFixed size, overlapping, starting every advance (Flink: sliding)
Sliding windowKafka Streams: record-driven window by maximum time difference
Session windowPer-key window closed by an inactivity gap; merges
WatermarkEstimate that no earlier event times are still expected
Perfect / heuristic watermarkGuaranteed from full input knowledge / estimated
Bounded out-of-ordernessWatermark = max timestamp minus a fixed delay
Idle partition / withIdlenessA silent input; Flink option to stop it holding the watermark
Watermark alignmentFlink pausing splits whose watermark runs too far ahead
max.task.idle.msKafka Streams wait for empty partitions before processing others
TriggerRule that decides when a window emits
PaneOne emission for one window: early, on-time or late
Accumulating / discardingPanes carry the total / only the delta
RetractionWithdrawal of a previously emitted value
suppress / EMIT FINALKafka Streams / ksqlDB final-only window results
Allowed latenessFlink: time after the window end during which late data is still added
Grace periodKafka Streams/ksqlDB name for allowed lateness
Late data / too-late dataBehind the watermark but inside lateness / past it
Side outputSeparate output for too-late or invalid records
State storeLocal key-value store used by stateful operators
RocksDBEmbedded LSM-tree store; Kafka Streams default persistent store
Changelog topicCompacted Kafka topic that records every state store update
Standby replicaWarm copy of a task's state on another instance
Stream-table dualityA stream is a table's changelog; a table is a stream's latest state
KStream / KTable / GlobalKTableRecord stream / partitioned table / fully replicated table
Co-partitioningSame partition count and partitioner on joined inputs
Repartition topicInternal topic written when the key changes
Join windowMaximum time difference for a stream-stream join
Foreign-key joinKTable-KTable join on a non-key field
exactly_once_v2Kafka Streams transactional processing guarantee
read_committedConsumer isolation level that hides aborted transactions
Checkpoint barrierFlink marker separating records of consecutive snapshots
Unaligned checkpointFlink checkpoint that overtakes in-flight data and stores it
Two-phase commit sinkSink that pre-commits per checkpoint and commits after it completes
SavepointManually triggered Flink snapshot for upgrades
Key GroupFlink's unit of keyed-state redistribution
BackpressureUpstream slowdown when downstream cannot keep up
FlinkDistributed stream processor with watermarks and checkpoints
Kafka StreamsJava library for stream processing on Kafka
ksqlDBSQL engine built on Kafka Streams
Spark Structured StreamingSpark's micro-batch streaming DataFrame API
Materialize / RisingWaveStreaming SQL databases with incrementally maintained views
mz_now() / temporal filterMaterialize's time function / time-bounded view predicate
x-stream-offsetRabbitMQ Streams consumer argument for the start position
Redis TimeSeriesRedis data type with TS.ADD, TS.RANGE aggregation and TS.CREATERULE compaction

References ​

Built by Morteza Negahi