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 for | Go to |
|---|---|
| Which timestamp to group by | Event, ingestion and processing time |
| Tumbling vs hopping vs sliding vs session | Windows |
| When a window is "done" and why it stalls | Watermarks |
| Early, on-time and late results | Triggers and panes |
grace, allowedLateness, side outputs | Lateness |
RocksDB, changelog topics, KTable | State |
| Stream-stream, stream-table, table-table joins | Joins |
exactly_once_v2, checkpoint barriers, 2PC sinks | Exactly-once |
| Kafka Streams vs Flink vs ksqlDB vs Spark vs Materialize | Per-engine behaviour |
| What RabbitMQ and Redis can do instead | Broker differences |
| A runnable window operator with tests | Go and Lab |
Everything in one minute
| Concept | Plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Event time | When it happened | Order placed 12:04:10 on a phone | A backlog moves orders into the wrong minute |
| Processing time | When the processor saw it | Worker read it at 12:09:02 | Replays give a different answer every run |
| Window | A 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 s | You never know when 12:04 is final |
| Trigger / pane | When to emit a result for a window | On-time pane at the watermark, then late panes | One answer too late, or no correction |
| Allowed lateness / grace | How long to keep a fired window open | 2 minutes after the window end | Late data corrupts or is dropped silently |
| Side output | Where too-late records go | orders-too-late topic | Data loss that no dashboard shows |
| State store + changelog | Durable, local window state | RocksDB plus a compacted topic | A crash loses or double-counts open windows |
| Exactly-once in the processor | Offsets, state and output commit together | exactly_once_v2, Flink checkpoints | Duplicates or holes after every restart |
| Question | Kafka Streams | Flink | RabbitMQ | Redis Streams |
|---|---|---|---|---|
| Window operator | windowedBy(...) | window(...) assigners | None | None |
| Progress signal | Stream time (max timestamp seen per task) | Watermarks, min over inputs | None | None |
| Late-data bound | Grace period | allowedLateness | Hand-rolled | Hand-rolled |
| Durable state | RocksDB + changelog topic | State backend + checkpoints | Unacked messages, or an external store | Keys you design |
| Replay | Yes, the topic is a log | Yes, from a checkpoint or savepoint | No (queues); yes (RabbitMQ Streams) | Yes, while entries are retained |
| Exactly-once scope | Kafka in, Kafka out | Sources and 2PC sinks | None | None |
| Window kind | Defined by | One record belongs to |
|---|---|---|
| Tumbling | Size | Exactly one window |
| Hopping | Size + advance | Size ÷ advance windows |
| Sliding | Maximum time difference | Windows defined by the records themselves |
| Session | Inactivity gap, per key | One 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 answer | More late records, more corrections or drops |
| Higher latency for every window | Lower 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:
- "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.
- "A watermark guarantees no more late data." A heuristic watermark is an estimate; late data is normal and needs a policy.
- "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.
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.
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 latenessReal 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).
| Product | Bounded input | Unbounded input |
|---|---|---|
| Flink | Batch execution mode, same API | Streaming mode |
| Kafka Streams | A topic read from offset 0 is still treated as unbounded | Native |
| Spark Structured Streaming | DataFrame batch | Micro-batch (default) streaming query |
| Apache Beam | PCollection bounded | PCollection 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".
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:04Real 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 from | Product and setting | Meaning |
|---|---|---|
| Producer sets it (default) | Kafka topic message.timestamp.type=CreateTime | Event time if the producer stamps it from the source |
| Broker overwrites it | Kafka message.timestamp.type=LogAppendTime | Ingestion time |
| Broker rejects future records | Kafka message.timestamp.after.max.ms (default 3600000, 1 hour) with CreateTime | Bounds clock skew into the future |
| Broker rejects old records | Kafka message.timestamp.before.max.ms (default Long.MAX) | No bound unless you set one |
| Processor extracts it | Kafka Streams TimestampExtractor / default.timestamp.extractor | Payload field, record timestamp or wall clock |
| Processor extracts it | Flink WatermarkStrategy.withTimestampAssigner | Event time from the payload or Kafka record |
| Auto-generated ID | Redis XADD * | Server clock at append: ingestion time |
| Consumer argument | RabbitMQ 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."
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).
| Concept | Kafka Streams | ksqlDB | Flink DataStream | Spark Structured Streaming | Dataflow / Beam |
|---|---|---|---|---|---|
| Fixed, non-overlapping | TimeWindows.ofSizeWithNoGrace / ofSizeAndGrace | WINDOW TUMBLING (SIZE ...) | TumblingEventTimeWindows | window(ts, "10 minutes") | Fixed windows |
| Fixed, overlapping | TimeWindows...advanceBy (hopping) | WINDOW HOPPING (SIZE, ADVANCE BY) | SlidingEventTimeWindows | window(ts, "10 minutes", "5 minutes") | Sliding windows |
| Record-driven | SlidingWindows.ofTimeDifferenceAndGrace, JoinWindows | Join WITHIN | Interval join | Not built in | Not built in |
| Per-key activity | SessionWindows.ofInactivityGap... | WINDOW SESSION (...) | EventTimeSessionWindows.withGap | session_window(ts, "5 minutes") | Sessions |
| Everything, custom trigger | Not built in | Not built in | GlobalWindows + trigger | Not built in | Global 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."
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 lateThat 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).
| Behaviour | Flink | Kafka Streams | Spark Structured Streaming | RisingWave |
|---|---|---|---|---|
| Watermark source | WatermarkStrategy.forBoundedOutOfOrderness(d) (periodic) or a punctuated generator | No watermark object: per-task "stream time" = max timestamp seen | withWatermark("ts", "10 minutes"): max event time minus delay | WATERMARK FOR col AS col - INTERVAL ... on a source |
| Several inputs | Operator event time is "the minimum of its input streams’ event times" | Task processes partitions by timestamp; max.task.idle.ms waits for empty ones | Global watermark = min by default; spark.sql.streaming.multipleWatermarkPolicy=max | Per source |
| Idle input | withIdleness(Duration) marks a split idle | Stream time does not advance without records | Slow stream holds the min | Per source |
| Fast input | withWatermarkAlignment(group, maxDrift, interval) pauses fast splits | Not applicable | Not applicable | Not applicable |
| Kafka-aware | Per-partition watermarks inside the Kafka source | Per partition (task) by design | Per query | Per 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.
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 sessionsReal 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).
| Product | Default emission | Final-only option | Accumulation |
|---|---|---|---|
| Kafka Streams | Every update, rate-limited by the record cache (statestore.cache.max.bytes, commit.interval.ms) | suppress(Suppressed.untilWindowCloses(...)) (KIP-328) | Accumulating (a KTable per window) |
| ksqlDB | EMIT CHANGES | EMIT FINAL | Accumulating |
| Flink | EventTimeTrigger: on watermark, and again per late element | Custom trigger / no lateness | Depends on the window function; PurgingTrigger discards |
| Spark Structured Streaming | Output mode update | Output mode append (final rows only) | Accumulating per mode |
| Beam / Dataflow | Watermark trigger | Watermark trigger, no late firings | accumulatingFiredPanes / discardingFiredPanes |
| Go library (this page) | On-time pane at watermark, late panes per Advance | Set AllowedLateness to 0 | Accumulating 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."
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-lateReal 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).
| Product | Knob | Default | Too-late handling |
|---|---|---|---|
| Flink | .allowedLateness(Duration) | 0 | Dropped, or .sideOutputLateData(OutputTag) then getSideOutput |
| Kafka Streams | ofSizeAndGrace(size, grace), ofSizeWithNoGrace | Chosen per window; the ...WithNoGrace factories set no grace | Discarded: "will not be processed in that window" |
| ksqlDB | GRACE PERIOD in the WINDOW clause | "a default of 24 hours when no grace period is specified" | Not included in the result |
| Spark Structured Streaming | withWatermark delay | None | Rows older than the watermark may be dropped |
| Go library (this page) | Config.AllowedLateness | 0 | Result.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".
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 replayReal 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).
| Concern | Kafka Streams | Flink | Hand-rolled (Go on this page) |
|---|---|---|---|
| Local store | RocksDB (persistent, default) or in-memory | Heap or embedded RocksDB | Go maps |
| Durability | Compacted changelog topic per store | Checkpoints to durable storage | Compacted changelog written in the same transaction |
| Fast failover | num.standby.replicas, warm-up replicas | Local recovery, incremental checkpoints | Not implemented: full replay |
| Upgrade with state | Same application.id, compatible topology | Savepoints | Changelog format is yours to version |
| Sharding unit | Task per input partition | Key Group | Operator 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.
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).
| Join | Kafka Streams | Flink | ksqlDB | Needs a window? |
|---|---|---|---|---|
| Stream-stream | join/leftJoin/outerJoin with JoinWindows | Interval join, window join | JOIN ... WITHIN | Yes |
| Stream-table | KStream.join(KTable) | Temporal / lookup join | Stream-table join | No |
| Table-table | KTable.join(KTable), foreign-key join | Regular join (state grows) | Table-table join | No |
| Stream-global table | KStream.join(GlobalKTable, keyMapper, joiner) | Broadcast state | Not applicable | No |
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 / 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 changelogReal 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).
| Product | Mechanism | Boundary | Cost |
|---|---|---|---|
| Kafka Streams | exactly_once_v2, transactions, KIP-447 producer per thread | Kafka input, state changelogs, Kafka output | Commit latency (100 ms default interval), 3+ brokers recommended |
| Flink | Aligned (or unaligned) checkpoints, 2PC sinks | Replayable sources, operator state, transactional sinks | Checkpoint alignment latency, sink transaction timeouts |
| Spark Structured Streaming | Checkpointed offsets and state; idempotent or transactional sinks | File sink exactly-once; Kafka sink documented as at-least-once | Micro-batch latency |
Go kafka snippet | franz-go GroupTransactSession, changelog in the same transaction | Kafka in, Kafka out | You own restore and changelog format |
| RabbitMQ, Redis | None | None | Idempotent 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.
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-topologyReal 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.
| Limit | Kafka Streams | Flink | Hand-rolled |
|---|---|---|---|
| Parallelism cap | Input partitions | Max parallelism / Key Groups | Partitions, or one consumer (RabbitMQ SAC) |
| Hot key | One task | One subtask | One process |
| Backpressure signal | Consumer lag | Backpressure metrics, checkpoint duration | Lag, 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
| Engine | Model | State | Event-time progress | Lateness | Exactly-once | Typical fit |
|---|---|---|---|---|---|---|
| Kafka Streams | Java library inside your service | RocksDB + changelog | Stream time per task | Grace period | exactly_once_v2 (Kafka to Kafka) | Kafka-centric microservices |
| ksqlDB | SQL server on Kafka Streams | Same as Kafka Streams | Same | GRACE PERIOD (24 h default) | Inherits Kafka Streams | SQL over Kafka topics |
| Apache Flink | Cluster, DataStream and SQL APIs | Heap or RocksDB backend, checkpoints | Watermarks, idleness, alignment | allowedLateness, side outputs | Checkpoints + 2PC sinks | Large stateful jobs, many sources |
| Spark Structured Streaming | Micro-batch DataFrame queries | State store + checkpoint | withWatermark (global min by default) | Watermark delay | Sink dependent | Teams already on Spark |
| Materialize | Incrementally maintained SQL views | Internal | Temporal filters with mz_now() | Rows leave views as time moves | Consistent views | Live SQL views over CDC and Kafka |
| RisingWave | Streaming SQL database | Internal | WATERMARK FOR col AS ... | Watermark-based state cleanup | Consistent views | Postgres-compatible streaming SQL |
| Apache Beam | API over runners (Flink, Dataflow, Spark) | Runner | Dataflow watermarks | Allowed lateness | Runner dependent | Portable pipelines, Go SDK |
| Go / PHP by hand | Your code | Your store | Your watermark | Your rule | Only what you build | Small, 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
| Product | Knob | Default (docs read 2026-11-26) | Effect |
|---|---|---|---|
| Kafka topic | message.timestamp.type | CreateTime | LogAppendTime makes record time ingestion time |
| Kafka topic | message.timestamp.after.max.ms | 3600000 | Rejects CreateTime records too far in the future |
| Kafka Streams | processing.guarantee | at_least_once | exactly_once_v2 enables transactions |
| Kafka Streams | commit.interval.ms | 30000, or 100 with exactly-once | Commit (and with EOS, visibility) frequency |
| Kafka Streams | num.standby.replicas | 0 | Warm copies of state for fast failover |
| Kafka Streams | max.task.idle.ms | 0 | Wait for empty partitions to avoid out-of-order joins and merges |
| Kafka Streams | statestore.cache.max.bytes | 10485760 | Record cache; fewer intermediate updates downstream |
| Kafka Streams | default.timestamp.extractor | FailOnInvalidTimestamp (the record's embedded timestamp) | Plug event-time extraction from the payload |
| Flink | forBoundedOutOfOrderness(d) | None | Watermark = max timestamp minus d |
| Flink | withIdleness(d) | Off | Idle splits stop holding the watermark |
| Flink | allowedLateness(d) | 0 | Keeps fired windows for late elements |
| Flink | enableCheckpointing(ms) / execution.checkpointing.interval | Disabled | Checkpoint period; required for exactly-once |
| Flink | CheckpointingMode.EXACTLY_ONCE | Exactly-once when checkpointing is on | AT_LEAST_ONCE skips alignment |
| Spark | withWatermark(col, delay) | None | State cleanup and late-row dropping |
| Spark | spark.sql.streaming.multipleWatermarkPolicy | min | max follows the fastest stream |
| ksqlDB | GRACE PERIOD | 24 hours | Window close time |
| RabbitMQ | consumer_timeout | 1800000 (30 min) | Bounds how long a message can stay unacked |
| RabbitMQ Streams | x-stream-offset | Next offset | first, last, offset, timestamp, interval |
Symptoms and what they mean Important
| Symptom | Meaning | Fix |
|---|---|---|
| Windows never close, no output | Watermark or stream time not advancing: an idle partition, or no new records | Idleness detection; heartbeat events; Kafka Streams needs new records per task |
| Output bursts after an outage | Processing-time windows, or a watermark that jumps after backlog | Use event time; expect late panes |
| Totals lower than a batch recount (Kafka Streams, ksqlDB) | Records later than the grace period were discarded | Longer grace, or reconcile from the raw topic |
| Restore takes many minutes after rebalance | Changelog replay into a new store | num.standby.replicas, smaller state, retention |
| RocksDB disk grows without bound | No eviction: unbounded keys or no grace/retention | Grace, retention, TTL, key design |
| Joins produce no matches | Not co-partitioned, or timestamps outside the join window | Same partition count and partitioner; check extractor |
| Flink checkpoints time out | Backpressure delays barriers | Unaligned checkpoints, reduce state, scale the slow operator |
| Duplicates downstream after restart | At-least-once sink outside the transaction | Idempotent upsert, or a transactional sink |
AMQP 406 PRECONDITION_FAILED on a channel holding unacked window messages | RabbitMQ consumer_timeout hit | Shorter windows plus lateness, or external state |
Solving classic problems
Orders per minute that survive replays and late data
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Kafka Streams windowed count | groupByKey().windowedBy(ofSizeAndGrace).count() | Full model, EOS, standbys | JVM service |
| ksqlDB | SQL with WINDOW TUMBLING and GRACE PERIOD | No code | Another server to run |
| Flink SQL or DataStream | Event-time windows, watermarks | Many sources and sinks | A cluster to operate |
| Hand-rolled Go operator + Kafka transaction | This page's kafka snippet | Go only, readable | You own restore, changelog, upgrades |
| Redis Lua windows | This page's redis snippet and Laravel class | Shares state across runtimes | No exactly-once; single watermark |
| Batch reconciliation | Nightly job over the raw topic and side output | Simple, exact for the past | Not real time |
ksqlDB, from its documentation's grace-period example, adapted to the order stream:
-- 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.
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
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| Kafka already, JVM services, Kafka-in and Kafka-out | Kafka Streams | exactly_once_v2, standbys | Library, no cluster, full model |
| Same, but SQL users | ksqlDB | EMIT FINAL, explicit GRACE PERIOD | No code; mind the 24 h default |
| Many sources and sinks, very large state | Flink | RocksDB backend, idleness, savepoints | Watermarks and checkpoints at scale |
| Team on Spark, minute-level latency is fine | Spark Structured Streaming | withWatermark, append mode | Reuse the platform |
| Live SQL views over CDC | Materialize or RisingWave | Temporal filters / watermarks | Incremental views, Postgres wire |
| Go service, one simple aggregation on Kafka | Hand-rolled operator + transaction | Changelog topic, idempotent sink | Small and readable; know its limits |
| RabbitMQ queues only | External state (Redis/DB) or move the stream to Kafka/RabbitMQ Streams | Single active consumer | Queues cannot replay |
| Redis Streams, small volume | Lua windows or Redis TimeSeries | Hash-tagged keys, dedup set | Fast; no exactly-once, no multi-input watermark |
| Analytics over history, not real time | Batch / columnar store | Reconcile side outputs | OLAP 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.
// 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.
// 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.
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.
// 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
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
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
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
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
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
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
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.
// 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
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.
// 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
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.
// 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-- 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-- 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 emittedRedis 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
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.replicasto 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 windowedcount()emits intermediate updates limited only by the record cache and commit interval. - Flink's end-to-end exactly-once with Kafka arrived with
TwoPhaseCommitSinkFunctionin 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
| Load | Design | Example |
|---|---|---|
| 1× | SQL GROUP BY on event time, or Redis Lua windows | Admin dashboard over thousands of orders per hour |
| 10× | Kafka Streams or ksqlDB, 12 partitions, grace and suppress | Per-region revenue per minute, EOS output topic |
| 100× | Flink or Kafka Streams with RocksDB, standbys, careful keys, idleness | Fraud features over millions of cards, joins with reference tables |
Lab
1. Run the window operator (run on the host)
cd docs/snippets/messaging/stream-processing/go
go test ./window
go run ./afterOutput of go run ./after, produced on the host for this page:
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 4Read 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)
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 time3. 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.
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 disappears4. RabbitMQ window held in unacked messages (expected, not run)
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 latenessStop 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)
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 countCompare with XRANGE orders <now-60000> <now>: both orders fall in the ingestion minute in which you typed them, regardless of occurred_at.
Common misconceptions
| Belief | Reality |
|---|---|
| The record timestamp is always event time | Kafka CreateTime is whatever the producer set; LogAppendTime is ingestion time |
| Processing-time windows are fine for business metrics | They change with backlog, outages and replays |
| A watermark is a guarantee | A heuristic watermark is an estimate; late data still arrives |
| Watermark = newest timestamp seen | Newest minus out-of-orderness, and the minimum across inputs |
| An idle partition is harmless | It holds the watermark (or stream time) and no window closes |
| Late data is lost data | Within allowed lateness/grace it is counted and causes a late pane |
| A window emits exactly once | Kafka Streams and Flink emit updates unless you suppress or use a final-only trigger |
| "Sliding window" means the same everywhere | Flink/Dataflow sliding = Kafka Streams hopping; Kafka SlidingWindows differ |
| State lives in Kafka | It lives in local RocksDB; Kafka holds the changelog for recovery |
| Any two topics with the same key can be joined | Equi-joins need co-partitioning; re-keying adds a repartition topic |
| More instances always means more throughput | Parallelism is capped by input partitions |
exactly_once_v2 covers my HTTP call | It covers Kafka offsets, state and Kafka output only |
| RabbitMQ or Redis can do this natively | Neither has windows, watermarks or state stores; you build them |
| ksqlDB windows close quickly by default | The default grace period is 24 hours |
Cheat sheet
| Topic | Remember |
|---|---|
| Time | Group by event time from the payload; processing time only for pipeline monitoring |
| Kafka timestamps | message.timestamp.type: CreateTime (default) or LogAppendTime |
| Window bounds | Tumbling/hopping are [start, end), epoch aligned |
| Naming | Flink sliding = Kafka Streams hopping |
| Watermark | Max minus delay, min across inputs, monotonic |
| Idle input | Flink withIdleness; Kafka Streams needs records; register partitions |
| Lateness | Flink allowedLateness (0), Kafka Streams grace, ksqlDB 24 h default |
| Too late | Side output, never silent drop |
| Panes | Accumulating for upserts, discarding for adders, retractions for sessions |
| Final only | suppress(untilWindowCloses), EMIT FINAL |
| State | RocksDB + compacted changelog; standbys for fast failover |
| Joins | Stream-stream needs a join window; equi-joins need co-partitioning |
| Exactly-once | exactly_once_v2 inside Kafka; Flink barriers + 2PC sinks |
| Scaling | Input partitions cap tasks |
| RabbitMQ / Redis | Hand-rolled only; durable watermark, idempotent sink |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Bounded / unbounded data | Finite and complete versus endless input |
| Dataflow model | Akidau et al. 2015: what, where (event time), when (processing time), how (refinement) |
| Event time | When the event happened at the source |
| Ingestion time | When the broker stored the record |
| Processing time | When the processor read the record |
message.timestamp.type | Kafka topic config: CreateTime (producer) or LogAppendTime (broker) |
TimestampExtractor | Kafka Streams plug-in that decides each record's timestamp |
| Stream time | Kafka Streams per-task progress: the largest timestamp seen |
| Out-of-order data | Records whose event time is older than records already seen |
| Window assigner | Function from a record to its windows |
| Tumbling window | Fixed size, non-overlapping |
| Hopping window | Fixed size, overlapping, starting every advance (Flink: sliding) |
| Sliding window | Kafka Streams: record-driven window by maximum time difference |
| Session window | Per-key window closed by an inactivity gap; merges |
| Watermark | Estimate that no earlier event times are still expected |
| Perfect / heuristic watermark | Guaranteed from full input knowledge / estimated |
| Bounded out-of-orderness | Watermark = max timestamp minus a fixed delay |
Idle partition / withIdleness | A silent input; Flink option to stop it holding the watermark |
| Watermark alignment | Flink pausing splits whose watermark runs too far ahead |
max.task.idle.ms | Kafka Streams wait for empty partitions before processing others |
| Trigger | Rule that decides when a window emits |
| Pane | One emission for one window: early, on-time or late |
| Accumulating / discarding | Panes carry the total / only the delta |
| Retraction | Withdrawal of a previously emitted value |
suppress / EMIT FINAL | Kafka Streams / ksqlDB final-only window results |
| Allowed lateness | Flink: time after the window end during which late data is still added |
| Grace period | Kafka Streams/ksqlDB name for allowed lateness |
| Late data / too-late data | Behind the watermark but inside lateness / past it |
| Side output | Separate output for too-late or invalid records |
| State store | Local key-value store used by stateful operators |
| RocksDB | Embedded LSM-tree store; Kafka Streams default persistent store |
| Changelog topic | Compacted Kafka topic that records every state store update |
| Standby replica | Warm copy of a task's state on another instance |
| Stream-table duality | A stream is a table's changelog; a table is a stream's latest state |
KStream / KTable / GlobalKTable | Record stream / partitioned table / fully replicated table |
| Co-partitioning | Same partition count and partitioner on joined inputs |
| Repartition topic | Internal topic written when the key changes |
| Join window | Maximum time difference for a stream-stream join |
| Foreign-key join | KTable-KTable join on a non-key field |
exactly_once_v2 | Kafka Streams transactional processing guarantee |
read_committed | Consumer isolation level that hides aborted transactions |
| Checkpoint barrier | Flink marker separating records of consecutive snapshots |
| Unaligned checkpoint | Flink checkpoint that overtakes in-flight data and stores it |
| Two-phase commit sink | Sink that pre-commits per checkpoint and commits after it completes |
| Savepoint | Manually triggered Flink snapshot for upgrades |
| Key Group | Flink's unit of keyed-state redistribution |
| Backpressure | Upstream slowdown when downstream cannot keep up |
| Flink | Distributed stream processor with watermarks and checkpoints |
| Kafka Streams | Java library for stream processing on Kafka |
| ksqlDB | SQL engine built on Kafka Streams |
| Spark Structured Streaming | Spark's micro-batch streaming DataFrame API |
| Materialize / RisingWave | Streaming SQL databases with incrementally maintained views |
mz_now() / temporal filter | Materialize's time function / time-bounded view predicate |
x-stream-offset | RabbitMQ Streams consumer argument for the start position |
| Redis TimeSeries | Redis data type with TS.ADD, TS.RANGE aggregation and TS.CREATERULE compaction |
References
- Tyler Akidau et al., "The Dataflow Model: A Practical Approach to Balancing Correctness, Latency, and Cost in Massive-Scale, Unbounded, Out-of-Order Data Processing", PVLDB 8(12), 2015: PDF, Google Research.
- Tyler Akidau, The world beyond batch: Streaming 101 (5 August 2015) and Streaming 102 (20 January 2016), O'Reilly Radar.
- Apache Kafka 4.4, Kafka Streams: Core Concepts, Architecture, Streams DSL, Processor API, Configuring a Streams Application, Topic configs.
- KIPs: KIP-328 suppress, KIP-447 producer scalability for exactly once.
- Apache Flink: Timely Stream Processing, Stateful Stream Processing, Generating Watermarks, Windows, Side Outputs, Checkpointing, State Backends.
- Piotr Nowojski and Mike Winters, An Overview of End-to-End Exactly-Once Processing in Apache Flink, Flink blog, 28 February 2018.
- ksqlDB: Time and Windows. Spark: Structured Streaming APIs on DataFrames and Datasets. Materialize: Docs, Temporal filters. RisingWave: Watermarks. Apache Beam: Go SDK.
- Redis: Streams, XRANGE, Time series, TS.RANGE, TS.CREATERULE.
- RabbitMQ: Streams, Consumers.
- Laravel 13: Queues, Redis, Query Builder, Task Scheduling, Artisan, Migrations.
- Packages: laravel-kafka v2.13 creating a consumer, consumer options, message handlers, laravel-queue-rabbitmq README, phpredis README.
- Go: franz-go
kgo, go-redis v9, amqp091-go.