What Is Windowing in Kafka?

What Is Windowing in Kafka?

A complete guide to tumbling, hopping, sliding and session windows: how Kafka turns an endless river of events into answers you can actually use, and how to run it safely in production.

Imagine standing beside a river and being asked, “How much water flows past you?” The question sounds simple, but it has no answer until you decide how long to watch. A minute? An hour? A day? The river never stops, so you must pick a slice of time and measure inside it. That single idea, cutting an endless flow into measurable pieces, is exactly what windowing does in Apache Kafka.

Kafka carries streams of events that never end: card payments, video plays, ride requests, sensor readings, page clicks. Businesses do not want to stare at raw events. They want answers such as “How many payments did this card make in the last five minutes?” or “How many rides were requested in this neighborhood this hour?” Windowing is the tool that makes those answers possible. In this guide you will learn what windows are, why they exist, the four kinds you can use, how they work inside Kafka Streams, how late data is handled, and how to run them at scale without waking up at 3 a.m.

1What Windowing Means

A window is a slice of time. Windowing is the act of grouping events into those slices so they can be counted, summed or compared.

Let us start with the building blocks. An event is a small record that says something happened, such as “Priya paid 40 dollars at 10:03:12”. A stream is an ordered, never-ending sequence of events. Apache Kafka is a platform that stores and delivers these streams reliably to many programs at once. Kafka stores events in named logs called topics, and each topic is split into partitions so that many machines can share the work.

Now the key definition. Windowing means dividing a stream into finite groups of events based on time, then running a calculation on each group. The group is called a window. Each window has a start time, an end time, and a result. When you ask “how many logins per minute?”, every minute is one window, and the count inside it is that window’s result.

Everyday analogy

Think of a highway toll booth. Cars never stop arriving. The manager cannot report “total cars ever”, because that number only grows and tells nothing useful. Instead the manager writes down how many cars passed every hour. Each hourly tally sheet is a window. Rush hour shows a big number, midnight shows a tiny one, and suddenly the data means something.

An important clarification: Kafka brokers do not do windowing

Many learners assume the Kafka server itself creates windows. It does not. The Kafka brokers are responsible for storing events durably and handing them out in order. They know nothing about “five-minute buckets”. Windowing is performed by stream processing applications that read from Kafka. The most common tool is Kafka Streams, a Java library that lives inside your own application. Another popular option is ksqlDB, which lets you write windowed queries in a SQL-like language. Big engines such as Apache Flink and Spark also read from Kafka and offer their own windowing features, with slightly different rules.

In this article, unless stated otherwise, we describe the behavior of Kafka Streams, because it is the reference implementation most people mean when they say “windowing in Kafka”.

4
window types in Kafka Streams: tumbling, hopping, sliding, session
1 : 1
each input partition maps to exactly one processing task
0
windowing logic inside the Kafka brokers
i
Remember this

A window answers the question “which events belong together in time?” The rest of this guide is about how to choose the shape of that grouping and how to keep it correct when the real world gets messy.

2Why Streams Need Windows

Without windows, a stream aggregation grows forever, uses more memory every day, and answers questions nobody asked.

Suppose you write a program that counts payments per card. Without windows, the count for every card simply climbs forever. After a year, the number tells you the card’s lifetime activity, which is fine for a bank statement but useless for spotting fraud. Fraud shows up as bursts: twenty purchases in three minutes. To see a burst you must look at a short slice of time. Windows give you that slice.

Three problems windows solve

Problem 1

Unbounded data

A stream never ends, so “the total” never finishes. A window creates a finish line so a result can be produced.

Problem 2

Meaningful questions

People ask “per minute”, “per hour” or “per visit”. Windows match the shape of the question.

Problem 3

Bounded memory

Old windows can be closed and deleted, so state does not grow without limit.

Problem 4

Trend detection

Comparing this window with the previous one reveals spikes, drops and slow drifts.

Typical jobs that use windows

Fraud detection

Flag a card that makes more than ten purchases within five minutes, or two purchases in two different countries within one hour.

Operational monitoring

Count errors per service per minute. If the count jumps above the normal level, page the on-call engineer.

Real-time dashboards

Show orders per minute, active drivers per city, or stream starts per region, refreshed continuously.

User behavior analysis

Group clicks into visits, then measure how long each visit lasted and what the user did.

Everyday analogy

A doctor checking your heart does not count every beat you will ever have. She counts beats for fifteen seconds, multiplies by four, and reads the result as “beats per minute”. The fifteen-second count is a window, and the multiplication turns it into an answer people understand.

?
Where windows are not needed

If you only need the latest value per key, such as the current balance of an account, you do not need windows. A plain aggregation into a table is enough. Windows are for questions that include a time span.

3Time in Kafka: The Clock That Decides Everything

Before any window can be drawn, the system must know what time each event happened. This is trickier than it sounds.

A window is built from timestamps, so the meaning of “time” matters a great deal. Kafka Streams recognizes three notions of time, and mixing them up is the number one source of confusing bugs.

Kind of timeWho sets itMeaningTypical use
Event timeThe producer or the source deviceWhen the thing actually happened in the real worldAccurate business metrics
Ingestion timeThe Kafka brokerWhen the event was appended to the topic logSimple setups where devices have unreliable clocks
Processing timeThe stream applicationWhen the application happened to process the eventRarely correct for windows; changes on every replay

Event time versus processing time

Picture a mobile game. A player scores a goal at 10:00:05 while riding in a subway tunnel with no signal. The phone uploads the event at 10:07:30 after leaving the tunnel. The event time is 10:00:05, because that is when the goal happened. The processing time is about 10:07:30, because that is when your program saw it. If you built windows on processing time, this goal would be counted in the wrong minute, and the leaderboard for 10:00 would be too low. Event time gives the correct answer.

Kafka Streams normally uses event time. Every Kafka record carries a timestamp. By default, that timestamp is the time the producer created the record. A topic can instead be configured so the broker stamps each record when it is appended, which is the ingestion-time behavior. If your timestamp lives inside the message body, for example a field named “transactionTime”, you can supply a custom timestamp extractor so Kafka Streams reads the right value.

Everyday analogy

Event time is the date written on a postcard’s front: “Wish you were here, 3 June”. Processing time is the date the mail carrier drops it in your box. A postcard sent from a faraway island might arrive weeks late. If you sort your postcards by arrival date, your holiday memories end up in the wrong order. Sorting by the date written on the card keeps the story straight.

Stream time: the application’s internal clock

Here is a concept unique to Kafka Streams: stream time. Stream time is the largest event timestamp the application has seen so far, tracked separately for each task. It only moves forward. If the newest record seen carries a timestamp of 10:15, stream time is 10:15, even if the wall clock says it is already 11:00 because the topic was quiet or a backlog was being replayed.

Why does this matter? Because Kafka Streams decides when a window is finished by looking at stream time, not the wall clock. A window that ends at 10:05 is considered closed only when stream time has moved beyond 10:05 plus the grace period. This design makes results reproducible: if you replay the same data tomorrow, you get the same windows and the same answers, no matter how fast or slow the replay runs.

!
Gotcha

Because stream time only advances when new records arrive, a partition that goes silent will not close its windows. The last window may stay open until the next event shows up. If you rely on “final” results for a quiet key range, plan for this behavior.

i
Production tip

Check that producers set sensible timestamps. A device with a clock set to the year 2035 can push stream time far into the future and cause every normal record to be treated as late. Validate timestamps at the edge, or use a custom extractor that rejects impossible values.

4Tumbling Windows: Fixed Buckets That Never Overlap

The simplest and most popular window: equal-sized time slices placed one after another, like the days on a calendar.

A tumbling window has a single setting: its size. If the size is five minutes, the windows are 10:00 to 10:05, then 10:05 to 10:10, then 10:10 to 10:15, and so on. Each window starts exactly when the previous one ends. There are no gaps and no overlaps, so every event belongs to exactly one window. The start of a window is included and the end is excluded, so an event stamped exactly 10:05:00 falls into the 10:05 to 10:10 window.

Kafka Streams aligns windows to the epoch, which is midnight on 1 January 1970 in UTC. In practice this means five-minute windows always begin at :00, :05, :10 and so on, no matter when your application started. Two different applications computing five-minute windows will therefore agree on the boundaries. This alignment is also why days in a tumbling-window setup follow UTC unless you handle time zones yourself.

flowchart LR
  subgraph W1["Window 10:00 to 10:05"]
    e1["Payment at 10:01"]
    e2["Payment at 10:03"]
  end
  subgraph W2["Window 10:05 to 10:10"]
    e3["Payment at 10:06"]
  end
  subgraph W3["Window 10:10 to 10:15"]
    e4["Payment at 10:12"]
    e5["Payment at 10:14"]
  end
  W1 --> W2
  W2 --> W3
Figure 1: Tumbling windows of five minutes. Every event lands in exactly one window.

The diagram shows five payments. The first two land in the first window, giving a count of two. The third lands alone in the second window, giving a count of one. The last two land together in the third window, giving a count of two. Nothing is counted twice and nothing is missed.

Everyday analogy

A tumbling window works like the tiles on a bathroom floor. Each tile touches the next, tiles never sit on top of one another, and every spot on the floor belongs to exactly one tile. Choose big tiles for a coarse view and small tiles for fine detail.

When tumbling windows are the right choice

Reports

Per-period totals

Orders per hour, revenue per day, signups per minute. Anything that maps to a clean calendar-style report.

Billing

Usage metering

API calls per customer per minute for rate reporting and invoices, where double counting would be a serious error.

Monitoring

Error rates

Errors per service per minute, compared with the previous minute to spot sudden change.

Sampling

Downsampling sensors

Reduce ten readings per second into one summary per minute to save storage and cost.

Production example: Netflix-style quality monitoring

Large streaming services track playback events such as start failures and buffering across millions of devices. Grouping those events into short tumbling windows per region and device type lets engineers see within a minute or two whether a new app release is hurting viewers, and roll it back before many people notice.

Strengths

  • Easy to explain and to reason about
  • No double counting, so totals add up
  • Lowest storage and compute cost of all window types

Weaknesses

  • A burst that straddles a boundary gets split in two
  • Results jump at the edges instead of changing smoothly
!
The boundary problem

Suppose a fraud rule says “block a card after ten purchases in five minutes”. A thief makes six purchases at 10:04 and six more at 10:06. That is twelve purchases in three minutes, but a tumbling window splits them into six and six, and neither reaches ten. For rules like this, use hopping or sliding windows, which we cover next.

5Hopping Windows: Overlapping Buckets on a Schedule

A hopping window has a size and a smaller “hop”. Windows overlap, so one event can appear in several of them.

A hopping window has two settings. The size says how long each window lasts. The advance (also called the hop) says how far the start moves forward to create the next window. If the size is ten minutes and the advance is five minutes, you get windows of 10:00 to 10:10, then 10:05 to 10:15, then 10:10 to 10:20. Each window starts five minutes after the previous one, yet each still looks ten minutes wide, so neighbors share five minutes of time.

Because of the overlap, a single event belongs to more than one window. The number of windows is simply the size divided by the advance. With size ten and advance five, each event lands in two windows. With size sixty minutes and advance one minute, each event lands in sixty windows. That last setup is popular for “last hour, updated every minute” dashboards, but it multiplies the work sixty times, so choose the hop with care.

flowchart TB
  E["Login event at minute 7"] --> A["Window minute 0 to 10"]
  E --> B["Window minute 5 to 15"]
  A --> RA["Count for window A updated"]
  B --> RB["Count for window B updated"]
Figure 2: With size 10 and advance 5, one event updates two windows.
Everyday analogy

Weather apps often show “average temperature over the last seven days”, recalculated every morning. Each morning’s number covers a week, but tomorrow’s number covers almost the same week shifted by one day. Six of the seven days are shared. That is a hopping window with size seven days and advance one day, and it produces a smooth curve instead of a jumpy staircase.

Why teams choose hopping windows

Hopping windows solve the boundary problem from the previous chapter, at least partly. A burst that crosses one edge is very likely to sit fully inside another window. They also give smoother charts because the answer changes gradually. The price is extra storage and compute, plus the fact that totals across windows no longer add up, since the same event is counted several times. You cannot sum hourly hopping counts to get a daily count.

Strengths

  • Smooth, continuously updated view of recent history
  • Catches bursts that would be split by tumbling edges
  • Familiar “last N minutes” style of reporting

Weaknesses

  • Cost grows with size divided by advance
  • Events counted many times; totals cannot be added
  • Still uses fixed edges, so extreme bursts can slip through
i
Rule of thumb

If the advance equals the size, a hopping window is just a tumbling window. If the advance is larger than the size, you leave gaps and some events belong to no window, which is almost never what you want.

6Sliding Windows: Windows Shaped by the Data Itself

Sliding windows do not follow a fixed clock schedule. They are defined by a maximum time distance between events.

Tumbling and hopping windows use fixed edges laid out in advance. Sliding windows, added to Kafka Streams in version 2.7, work differently. You give them one setting: the maximum time difference between records. Two records belong to the same window if their timestamps are no further apart than that difference. Both the start and the end of a sliding window are inclusive, unlike tumbling and hopping windows where the end is excluded.

Behind the scenes, Kafka Streams creates windows around the arriving records so that every distinct group of records that fit within the time difference gets its own result. It does not create empty windows for quiet periods, and it does not produce identical duplicate results, which keeps it far cheaper than a hopping window with a tiny advance.

Everyday analogy

Ask “did this person cough twice within any five-minute stretch?” You do not stop at fixed clock marks. You slide a five-minute frame along the timeline and check every position. If two coughs ever fit inside the frame, the answer is yes. A sliding window asks that question for every possible position, so nothing can hide between edges.

Where sliding windows shine

Burst detection and rate limiting

“More than ten failed logins within any five-minute period” is a rule about any five minutes, not the five minutes between :00 and :05. Sliding windows evaluate exactly that.

Fraud rules on card activity

Payment platforms commonly watch for rapid repeated attempts. A sliding window ensures a burst is caught wherever it starts.

Quality-of-service alerts

Alert when latency spikes above a threshold for any continuous stretch of a given length, not only at clock-aligned intervals.

Strengths

  • No boundary problem; every burst is caught
  • Only creates windows where data exists
  • Cheaper than hopping with a very small advance

Weaknesses

  • Results are not aligned to clean clock times, so reports look unfamiliar
  • Newer feature; not available in older library versions
  • Harder to explain to non-engineers
?
Version note

Sliding windows require Kafka Streams 2.7 or newer. ksqlDB offers tumbling, hopping and session windows in its query language. Always check the documentation of the exact version you run before designing around a feature.

7Session Windows: Grouping Activity by Silence

Session windows have no fixed length. A session keeps growing as long as events keep arriving, and ends after a quiet gap.

A session window is defined by an inactivity gap. Suppose the gap is thirty minutes. As long as a user’s events arrive less than thirty minutes apart, they belong to the same session. When thirty minutes pass with no event for that user, the session ends. The next event begins a new session. One user’s session might last two minutes; another’s might last three hours. The window length adapts to human behavior.

Session windows are always calculated per key. If the key is the user ID, each user has their own independent sessions. Two users can be in the middle of a session at the same time, and one user’s silence never closes another user’s session.

flowchart LR
  c1["Click 10:00"] --> c2["Click 10:10"]
  c2 --> c3["Click 10:15"]
  c3 --> s1["Session 1 ends after 30 minute gap"]
  s1 --> c4["Click 11:00"]
  c4 --> c5["Click 11:05"]
  c5 --> s2["Session 2 ends after 30 minute gap"]
Figure 3: Two sessions for one user, separated by a gap longer than thirty minutes.

Sessions can merge

Here is the subtle part. Because events can arrive out of order, a late event might fill a gap between two sessions and join them together. Imagine session one ended at 10:15 and session two began at 10:40, with a gap of 25 minutes, but the gap limit is 30. If both sessions already existed when this is discovered, they were separate only because of how the events happened to arrive. Kafka Streams handles this by merging the two sessions into one larger session. The old session results are retracted (a deletion marker is emitted downstream) and the new merged result is emitted. Anything that consumes session results must be ready for this “update by replacement”.

Everyday analogy

Think of a coffee shop customer who comes in, orders, chats, orders again, then leaves. If the staff say “a visit ends when the customer is gone for more than half an hour”, the visit is a session. A quick trip to the car does not end the visit, but going home does. Visits vary from five minutes to three hours, and that is exactly why a fixed-size window would be a poor fit.

Common uses

Web

Website visits

Group clicks into visits, then compute pages per visit, time on site and conversion.

Mobile

App usage

Measure how long a person uses an app in one sitting and what they did.

Support

Customer conversations

Bundle chat messages into a single support conversation for satisfaction analysis.

Gaming

Play sessions

Track how long players stay engaged before leaving, per game and per region.

!
Watch the cost

Sessions for very active keys can grow without limit. A bot that clicks every ten seconds around the clock creates one enormous session that never closes. Consider capping session duration in your business logic or filtering obvious bots before windowing.

8Choosing the Right Window Type

The four window types answer four different kinds of questions. Match the shape of the window to the shape of the question.

FeatureTumblingHoppingSlidingSession
SettingsSizeSize and advanceMax time differenceInactivity gap
Window lengthFixedFixedFixed distance, data-drivenVariable
OverlapNoneYesYesNone per key
Events per window setOne windowSize divided by advanceAny number that fitsOne session
Aligned to clockYesYesNoNo
Relative costLowestHigherMediumMedium
Best forPeriodic reportsSmooth moving viewsBurst detectionUser activity visits

A simple decision path

1

Is the question about a calendar period?

“Per minute”, “per hour”, “per day”. Choose tumbling. It is cheapest and totals add up.

2

Do you need a smooth “last N minutes” view?

Choose hopping, and keep size divided by advance as small as the dashboard allows.

3

Must you catch a burst wherever it starts?

Choose sliding. It watches every position of the frame, not only clock marks.

4

Is the length decided by human activity?

Choose session. The window opens with the first event and closes after a quiet gap.

Pick the window that fits the question, not the one that is easiest to configure.

9Architecture and Components

A windowed application is a small team of parts: topics that carry data, tasks that process it, and stores that remember the running totals.

Let us walk through the pieces. Everything begins with producers, the applications that write events into Kafka. Events land in an input topic, which is divided into partitions. Your Kafka Streams application reads from that topic. The application can be run as several copies, called instances, on different machines. Kafka splits the partitions among the instances so that the work is shared.

flowchart LR
  P["Producers"] --> LB["Load Balancer and API Gateway"]
  LB --> IN["Input Topic with Partitions"]
  IN --> A1["Streams App Instance 1"]
  IN --> A2["Streams App Instance 2"]
  A1 --> S1["Window State Store 1"]
  A2 --> S2["Window State Store 2"]
  S1 --> CL["Changelog Topic"]
  S2 --> CL
  A1 --> OUT["Output Topic"]
  A2 --> OUT
  OUT --> D["Dashboards and Alerts"]
  OUT --> DB["Serving Database"]
Figure 4: A windowed Kafka Streams application from producers to consumers.

The components in plain words

Data in

Producers, gateway and load balancer

Web servers, phones and services send events. An API gateway and load balancer typically sit in front, spreading traffic and enforcing authentication before events reach Kafka.

Storage

Topics and partitions

Durable, ordered logs. Events with the same key always go to the same partition, which keeps each key’s events in order.

Compute

Stream tasks

The unit of parallel work. There is one task per input partition, and each task owns its own state and its own stream time.

Memory

Window state store

A local database, RocksDB by default, keeping one entry per key per window. It holds the running counts and sums.

Safety

Changelog topic

Every state store change is also written to a special compacted Kafka topic. If a machine dies, the store is rebuilt from it.

Data out

Output topic

Window results are written here for dashboards, alerts, databases and other services to consume.

How the store keeps track of windows

The state store does not hold “a window” as one object. It holds many small entries, each identified by three pieces: the key, the window start time, and the aggregated value. For example: “card 4711, window starting 10:05, count 3”. When a new event arrives, the application finds the entry for that key and window, updates the value, and writes it back. This is why the number of entries equals the number of active keys multiplied by the number of open windows per key.

When results flow downstream, the key is wrapped so that it carries the window boundaries along with the original key. Consumers therefore know both who the result belongs to and which time slice it covers. If a consumer wants a plain key, it converts the wrapped key back to the original in a later step.

i
Design tip

Windowing needs all events of one key to reach the same task. If your input topic is not keyed by the value you want to group on, Kafka Streams inserts a repartition step automatically, writing the data to an internal topic with the new key. That extra hop costs network and storage, so key your data correctly at the source whenever you can.

10Internal Working: The Life of One Event

Follow a single payment event from the moment it enters the application until its window result leaves it.

1

The event is read from a partition

A task pulls the record from its assigned partition. Records within one partition arrive in the order they were written, though their timestamps may not be perfectly increasing.

2

The timestamp is extracted

The application reads the event time from the record, using the default rule or a custom extractor that reads it from the message body.

3

Stream time is updated

If this timestamp is larger than any seen before by the task, stream time moves forward to it. Otherwise stream time stays where it is.

4

The windows for this event are computed

Using the timestamp and the window settings, the application works out which windows the event belongs to: one for tumbling, several for hopping, and so on.

5

Each window is checked for lateness

If the window’s end plus the grace period is already behind stream time, the window is closed and the event is dropped. Otherwise it is accepted.

6

The state store is updated

The aggregate for that key and window is read, combined with the new event, and written back. The write is also recorded in the changelog topic.

7

The result is forwarded downstream

The updated result is sent to the next step, and eventually to the output topic, subject to caching and the commit interval described later.

flowchart TD
  R["Record arrives with timestamp"] --> ST["Update stream time to the maximum seen"]
  ST --> Q{"Is window end plus grace behind stream time"}
  Q -->|"No, window still open"| U["Update aggregate in state store"]
  Q -->|"Yes, window closed"| D["Drop record and count it in a metric"]
  U --> F["Forward updated result downstream"]
  U --> CH["Write change to changelog topic"]
Figure 5: The decision every windowed record goes through.
Everyday analogy

Picture a school where the lunch bell rings only when the newest student arrives at the gate, and each class register closes ten minutes after its lesson ends. A student who walks in after the register has closed is marked absent. The bell is stream time, and the ten extra minutes are the grace period. The teacher never checks the wall clock, only the bell.

?
Parallel by design

Each task keeps its own stream time. A busy partition may be hours ahead of a slow one. This is fine for aggregations, but it matters when joining streams, where the library may briefly wait for the slower side so that time stays roughly in step.

11Late and Out-of-Order Data: Grace Periods

Real events arrive late. The grace period is how long a window waits for stragglers before it is sealed.

In a perfect world, events reach Kafka in the order they happened. In the real world, networks stall, phones lose signal, retries happen, and batch uploads arrive hours later. An event is out of order when its timestamp is older than one that arrived before it. An event is late when it arrives after its window would normally be considered finished.

Kafka Streams handles this with a grace period, a setting you choose for every window definition. The rule is simple: a window remains open for updates until stream time passes the window end plus the grace period. Consider a five-minute window ending at 10:05 with a grace of two minutes. An event stamped 10:04 that shows up when stream time is 10:06 is still accepted, because 10:06 is before 10:07. The same event arriving when stream time is 10:08 is rejected, because the window closed at 10:07.

Grace periodBenefitCost
ZeroWindows close immediately; final results available soonest; least state keptAny straggler is dropped, so counts may be slightly low
A few seconds to minutesHandles ordinary network jitter and retriesResults are final a little later; a little more state kept
HoursTolerates mobile uploads and batch delaysWindows stay open long; much more state; late final results

What happens to events that are too late?

Records that arrive after their window closes are dropped. Kafka Streams does not crash or block. It increments a “dropped records” metric, so you can see how often it happens. That is your early warning. If the dropped-records rate is high, your grace period is shorter than the real-world delay, and your numbers are undercounting.

Production example: ride-hailing demand counts

Large ride-hailing platforms count ride requests per city zone to decide when to raise prices. Driver and rider apps send events over mobile networks, so a small fraction arrive several seconds late. A grace period of a few seconds keeps demand numbers accurate without delaying the price signal by a noticeable amount.

!
Older library versions

In older releases, a window that did not specify a grace period silently kept a default of about twenty-four hours. Newer releases require you to state the grace period explicitly. Always read your version’s documentation. A grace period that is far too long can make memory and disk use balloon without anyone noticing.

i
How to pick a value

Measure. Look at the gap between event time and arrival time for your real traffic and choose a grace period that covers the vast majority of events, such as the ninety-ninth percentile. Then watch the dropped-records metric and adjust.

12When Do Results Come Out?

A window has a result long before it closes. Understanding continuous updates versus final results prevents nasty surprises.

By default, Kafka Streams behaves as if every window were a live scoreboard. Each time an event updates a window, a new result for that window can be emitted. If a five-minute window sees a hundred events, downstream consumers may see many successive versions of the count as it climbs. This is called the continuous refinement model. It gives low latency, because you see numbers immediately, but it means the same window and key appear many times in the output.

Two things reduce the noise. First, Kafka Streams keeps a small record cache in memory in front of the state store, so that several quick updates to the same key and window are merged into one before being forwarded. Second, the cache is flushed on a schedule known as the commit interval. The default is about thirty seconds under normal settings and much shorter when exactly-once processing is enabled. A shorter interval means fresher results and more output traffic; a longer one means fewer, larger updates.

Final results only

Some downstream systems cannot cope with repeated updates. A billing system, for example, must receive one final number per customer per window. For those cases you can ask Kafka Streams to hold results back until a window is closed, meaning stream time has passed its end plus grace. Older releases do this with a suppression step. Newer releases include a built-in option to emit results only when the window closes. In ksqlDB the same idea appears as an “emit final” mode.

Everyday analogy

Compare a live cricket scoreboard with the newspaper printed the next morning. The scoreboard changes every ball, which is useful while the match is on. The newspaper prints only the final score. Continuous refinement is the scoreboard, and final-only emission is the newspaper. You choose based on who is reading.

Continuous updates

  • Lowest latency; dashboards feel live
  • No waiting for the window to close
  • Consumers must handle repeated results for the same window

Final results only

  • Exactly one result per key per window
  • Delayed until the window closes, at least window end plus grace
  • Needs stream time to advance, and buffers results in memory or storage until then
!
Quiet stream trap

Because final results depend on stream time, and stream time depends on new records arriving, a window may never be finalized if no further events show up on that partition. Teams sometimes add a periodic heartbeat event to keep time moving on low-traffic topics.

Reading windowed results later

Window state stores can also be queried directly through the interactive queries feature of Kafka Streams, so an application can answer “what is the current count for this key in the current window?” without going through the output topic. The store keeps windows for a retention period that must be at least the window size plus grace. If you want to query older windows, you must extend the retention, which costs extra disk space.

13Windowed Joins: Matching Events in Time

Windows are not only for counting. They also decide which events from two different streams belong together.

Imagine two streams. One holds “ad shown” events. The other holds “ad clicked” events. To measure click-through you must match each click with the ad that was shown to the same user. But a click can only sensibly be connected to a display that happened shortly before it, perhaps within thirty minutes. A click a month later is a different story. A stream-stream join uses a time window to express this: two records match only if they share the same key and their timestamps are within the allowed window of each other.

The join window can be symmetric or lopsided. You can say “match a click with any display up to thirty minutes before it and up to zero minutes after it”. Kafka Streams keeps recent events from both streams in window stores so that a record arriving on one side can find its partner from the other side. Just like aggregations, joins use a grace period for late records, and old entries are removed once they pass the retention limit.

Everyday analogy

Think of a restaurant matching orders with plates ready in the kitchen. An order and a finished plate for the same table belong together only if they are within a few minutes of each other. A plate from an hour ago belongs to someone else. The join window is the “few minutes” rule.

i
Co-partitioning rule

For a join to work, both input topics must use the same key and the same number of partitions, so that matching events end up in the same task. If they do not, the data must be repartitioned first. This is a common source of mysterious “no matches” bugs.

Production example: advertising attribution

Ad platforms match impressions with clicks and purchases within an attribution window. Companies that have described Kafka-based ad pipelines, such as Pinterest, use streaming aggregation to track spend against budgets in near real time, which depends on the same windowed grouping ideas.

14Data Flow, Failure Recovery and Exactly-Once

Machines crash. A good windowed design survives that without losing or double counting a single event.

Window state lives on local disks, so what happens when a machine dies? The answer is the changelog topic. Every update to a window store is also written to a compacted Kafka topic. When a task moves to another instance, the new owner replays the changelog to rebuild the local store, then resumes reading input from where the old owner left off. Because both the changelog and the input offsets are stored in Kafka, nothing is lost.

flowchart TD
  F["Instance crashes"] --> RB["Group rebalance reassigns tasks"]
  RB --> ST{"Standby replica available"}
  ST -->|"Yes"| FAST["Promote standby and catch up briefly"]
  ST -->|"No"| SLOW["Restore store from changelog topic"]
  FAST --> RES["Resume processing from committed offsets"]
  SLOW --> RES
Figure 6: How windowed state is recovered after a failure.

Rebuilding a large store from scratch can take many minutes. To shorten that time, you can ask for standby replicas: warm copies of the state kept up to date on other instances. When the primary fails, a standby takes over almost immediately.

Exactly-once processing

If a crash happens after a window was updated but before the application recorded that it had read the event, the event could be processed twice, doubling the count. Kafka Streams can prevent this with exactly-once processing. When it is enabled, reading the input, updating the state, and writing the output are committed together as one atomic transaction. Either all three happen or none do. For counts that feed billing or compliance reports, this setting is well worth its small cost in throughput.

?
Delivery guarantee cheat sheet

At-least-once means no event is lost but duplicates are possible after a crash. Exactly-once means neither loss nor duplicates within Kafka. Consumers outside Kafka, such as an external database, may still need to be idempotent, meaning a repeated write does not change the outcome.

15Advantages, Disadvantages and Trade-offs

Windowing is powerful, yet every choice trades something for something else. Know the trades before you commit.

Advantages

  • Turns endless streams into finite, meaningful answers
  • Bounds memory by letting old windows expire
  • Runs inside your own application; no separate cluster needed for Kafka Streams
  • Scales out by adding instances up to the partition count
  • Fault tolerant through changelog topics and standby replicas
  • Results are repeatable because logic follows event time

Disadvantages

  • State grows with keys times windows, and can become large
  • Late data forces a hard choice between accuracy and freshness
  • Overlapping windows multiply cost
  • Recovery of big state stores can take minutes
  • Stream time semantics surprise newcomers, especially on quiet partitions
  • Kafka Streams is a Java library, so the team needs JVM skills

The four big trade-offs

Trade-off 1

Accuracy versus latency

A longer grace period catches more late events but delays final results. A shorter one is fast but may undercount.

Trade-off 2

Smoothness versus cost

Small hops give smooth charts but multiply storage and compute. Big hops are cheap but jumpy.

Trade-off 3

Freshness versus traffic

Short commit intervals refresh outputs often, sending more messages downstream. Long ones are calm but stale.

Trade-off 4

Retention versus disk

Keeping windows longer allows more historical queries but consumes more local storage on every instance.

i
Think in budgets

Set a latency budget (“results within one minute”), an accuracy budget (“at most one percent of events dropped as late”) and a cost budget (“storage under a set amount”). Then choose window type, grace and retention to satisfy all three together.

16Performance and Scalability

A well-designed windowed application can handle hundreds of thousands of events per second. The secret is understanding what limits it.

Scaling in Kafka Streams follows one simple rule: parallelism equals the number of input partitions. Each partition is handled by one task, and each task is handled by one thread at a time. If your input topic has twelve partitions, you can usefully run up to twelve threads spread over any number of instances. Adding a thirteenth thread brings no benefit, because there is no task left for it. Choose the partition count at design time with growth in mind, since increasing it later changes how keys map to partitions.

What makes windowing expensive

FactorEffectHow to control it
Number of distinct keysMore keys means more state entries per windowGroup by a coarser key when the business allows
Size divided by advanceEach event updates many windowsIncrease the advance or use sliding windows
Grace and retentionLonger means more open windows keptSet to measured needs, not guesses
Value sizeBig aggregates slow every read and writeStore compact summaries such as counts and sums
Hot keysOne busy key overloads one taskSpread the key or pre-aggregate before the main step
Everyday analogy

Picture a supermarket with twelve checkout lanes, one per partition. Twelve cashiers can work at once, but a thirteenth cashier has no lane to serve. And if one customer arrives with forty trolleys of shopping, that single lane stalls no matter how many other cashiers are free. That customer is a hot key.

Practical tuning levers

Memory

Record cache size

A larger cache merges more updates before they hit the store and output, lowering both disk writes and downstream traffic.

Disk

Fast local storage

Window stores read and write constantly. Solid state disks make a large difference compared with network-attached slow volumes.

Threads

Threads per instance

Match threads to available processor cores, and never exceed the total number of partitions across the application.

Compaction

Pre-aggregation

If one key is extremely busy, aggregate in small steps first so the heavy key is spread before the final window.

!
Scale check

Before launch, replay a full day of realistic traffic at higher than production speed. Watch disk growth, consumer lag and restore time. Problems that appear only at scale are far cheaper to find in a rehearsal than in production.

Databases, caching and load balancing around windows

Windowed results are rarely the end of the road. They often flow into a fast database or cache so that user-facing services can read them in milliseconds. Kafka Connect is a common way to copy the output topic into such a store. Load balancers and API gateways matter at the front door: they spread incoming events across producer instances and reject bad or unauthenticated traffic before it can pollute your timestamps. A healthy front end keeps the stream clean, which makes every window downstream more trustworthy.

17High Availability and Reliability

A dashboard nobody can trust is worse than no dashboard. Reliability means the numbers stay right even when machines fail.

Data safety

Replicated topics

Input, changelog and output topics should each be replicated across brokers, commonly with three copies, so a broker failure loses nothing.

Fast failover

Standby replicas

Warm copies of state on other instances turn a long restore into a brief catch-up.

Stability

Static membership

Giving each instance a stable identity avoids needless task shuffling during quick restarts and rolling deployments.

Correctness

Exactly-once

Atomic commits stop a crash from causing duplicate counts in a window.

Deployments deserve special care. Restarting all instances at once forces every task to move and every store to restore. A gentle rolling restart, one instance at a time and with warm standbys ready, keeps the application producing results throughout. Newer versions of Kafka use an incremental rebalancing process that moves only the tasks that must move, further reducing disruption.

Production example: bank fraud scoring

A bank scoring card transactions cannot pause for ten minutes while state rebuilds, because every declined or approved payment is customer-visible. Such systems use replicated topics, standby replicas and rolling upgrades so that a single machine failure is invisible to shoppers.

18Security

Windowed state contains real user activity. Protect it like the sensitive data it is.

In transit

Encrypt connections

Use TLS between applications and brokers so events and results cannot be read or altered on the network.

Identity

Authenticate applications

Each Streams application should prove who it is, for example with SASL or client certificates, and use its own credentials.

Access

Least-privilege ACLs

Grant read on input topics, write on output topics, and access to the internal topics whose names start with the application identifier, and nothing more.

At rest

Encrypt local state

State stores live on local disks and contain per-key aggregates. Use disk encryption and restrict who can log in to the machines.

Privacy

Minimize personal data

Key windows by an internal identifier instead of names or emails, and remove data after retention ends.

Input quality

Validate timestamps

Wrong timestamps are a data quality problem and an attack path. A forged far-future timestamp can push stream time ahead and cause valid events to be dropped.

!
Often forgotten

The changelog topics are full copies of your window state. Anyone who can read them can read the aggregates. Apply the same access rules and encryption to internal topics as to any sensitive business topic.

19Monitoring, Logging and Metrics

You cannot fix what you cannot see. A handful of signals reveal almost every windowing problem.

SignalWhat it tells youTypical action
Dropped-records rateHow many events arrive after their window closedRaise grace or investigate slow producers
Consumer lagHow far behind the application is from the newest dataAdd instances or fix slow processing
Event-time skewGap between event timestamps and wall clockCheck device clocks and upstream delays
State store sizeDisk used by windows and retentionShorten retention or grace, coarsen keys
Restore timeHow long a task takes to rebuild stateAdd standbys; shrink state
Rebalance frequencyStability of the cluster of instancesUse static membership; fix flapping nodes
Output rateVolume of window updates sent downstreamTune cache and commit interval

Set alerts on lag and on the dropped-records rate first; they catch most trouble early. Log rebalances and restores with timestamps so that you can connect a dip in results with a specific restart. Finally, keep a small set of known-answer test streams. If a synthetic stream that should produce exactly ten events per minute suddenly reports nine, you know something in the pipeline changed.

i
A useful habit

Publish a heartbeat metric from your own windowed job, such as “latest window end seen”. If it stops moving while traffic is normal, stream time is stuck, which usually points to an idle partition or a bad timestamp.

20Design Patterns and Anti-patterns

A few proven shapes solve most windowing needs. A few tempting shortcuts cause most of the outages.

Patterns that work

Pattern

Two-stage aggregation

Aggregate in small windows first, then roll those results into bigger ones. Hourly totals from minute totals costs far less than recomputing from raw events.

Pattern

Windowed alert stream

Compute counts per window, filter for thresholds, and write only breaches to an alerts topic that paging tools consume.

Pattern

Sessionize then aggregate

Group events into sessions, then compute per-session measures such as duration and pages viewed as a second step.

Pattern

Lambda-free reporting

Use the same event-time windows for live and replayed data, so backfills give identical answers with no separate batch code.

Anti-patterns to avoid

AP-01Avoid
What people do

Build windows using the time the program processes each event instead of the time the event happened.

Why it hurts

Results change whenever the application runs faster or slower, restarts, or replays old data. Two runs over the same input disagree, and debugging becomes guesswork.

Do this instead

Use event time with a sensible grace period, and validate timestamps at the edge.

AP-02Avoid
What people do

Choose a huge grace period “just to be safe”, such as a full day, for a job that needs answers in a minute.

Why it hurts

Windows stay open for a day, state balloons, and final results arrive a day late. Storage bills climb while the real delay of most events is only seconds.

Do this instead

Measure real lateness and choose a grace that covers nearly all events, then monitor drops.

AP-03Avoid
What people do

Create a one-hour window that advances every second so the chart looks perfectly smooth.

Why it hurts

Every event updates thousands of windows. Throughput collapses and the state store swells for a visual nicety nobody needed.

Do this instead

Advance every minute, or use sliding windows if the goal is to catch bursts.

AP-04Avoid
What people do

Add up hopping-window counts to compute a daily total.

Why it hurts

Overlap means each event was counted several times, so the total is inflated by a factor equal to size divided by advance.

Do this instead

Use tumbling windows for totals and keep hopping windows for moving views only.

21Best Practices and Common Mistakes

A short checklist gathered from many production systems. Follow it and you avoid most windowing pain.

1

Decide the business question first

Write the sentence “we want to know X per Y” before choosing a window type. The sentence tells you the answer.

2

Use event time and clean timestamps

Set producer timestamps reliably, reject impossible values, and document which field carries event time.

3

Measure lateness, then set grace

Look at real arrival delay and choose a grace period from the data, not from instinct.

4

Key data correctly at the source

Avoid unnecessary repartitioning by producing with the grouping key already in place.

5

Plan the partition count for growth

Parallelism is capped by partitions, and changing them later reshuffles keys.

6

Provision standbys and test recovery

Kill an instance in a rehearsal and time the recovery. Do this before an outage does it for you.

7

Alert on drops, lag and idle windows

These three signals reveal lateness problems, capacity problems and stuck time.

Mistakes seen again and again

Mistake

Forgetting time zones

Day windows follow UTC. A report for “today in Mumbai” needs care, such as shifting timestamps or using a custom approach.

Mistake

Expecting one result per window

By default, results refine continuously. Consumers that assume a single value per window will double count.

Mistake

Ignoring idle partitions

Quiet partitions freeze stream time and delay final results. Add heartbeats where traffic is thin.

Mistake

Mismatched join partitions

Joining topics with different partition counts or keys silently yields no matches.

Mistake

Unbounded retention

Keeping every window forever fills the disks. Set retention to what queries truly need.

Mistake

Skipping replay tests

If a replay of yesterday’s data does not reproduce yesterday’s numbers, something depends on the wall clock.

22Worked Example: One Card, Four Window Types

The same five events produce four different answers depending on the window you choose. Seeing the numbers side by side makes the differences stick.

Suppose a payment company watches one card, number 4711. The card makes purchases at these times: 10:01, 10:03, 10:04, 10:07 and 10:52. The business question is “how active is this card?” Let us answer it with each window type and see how the story changes.

With tumbling windows of five minutes

The windows are 10:00 to 10:05, 10:05 to 10:10, and 10:50 to 10:55. The first window contains three purchases (10:01, 10:03, 10:04). The second contains one (10:07). The third contains one (10:52). The answers are three, one and one. Notice that the activity between 10:03 and 10:07 was really four purchases in about four minutes, but the boundary at 10:05 split them into three and one.

With hopping windows of ten minutes advancing every five

Now the windows are 10:00 to 10:10, 10:05 to 10:15, and later ones near 10:50. The window from 10:00 to 10:10 contains four purchases. The window from 10:05 to 10:15 contains only the 10:07 purchase. The 10:45 to 10:55 and 10:50 to 11:00 windows each contain the 10:52 purchase. The maximum count is now four, which is closer to the truth, and the burst is visible. The cost is that the 10:07 purchase was counted twice, once in each overlapping window.

With sliding windows and a six-minute difference

The sliding window asks, for every position, which purchases fit within six minutes of each other. The purchases at 10:01 and 10:07 are exactly six minutes apart, so all four early purchases (10:01, 10:03, 10:04 and 10:07) fit in one window, giving a count of four. The 10:52 purchase is far away, so it forms its own window with a count of one. Had the limit been five minutes, the largest group would be three, because 10:01 and 10:07 would no longer fit together. The important point is that the answer comes from the data itself and does not depend on where a clock boundary happened to fall.

With session windows and a ten-minute gap

The purchases at 10:01, 10:03, 10:04 and 10:07 are each less than ten minutes apart, so they form one session that runs from 10:01 to 10:07 with four purchases. The purchase at 10:52 is forty-five minutes after the last one, which is more than the gap, so it begins a second session with one purchase. Session windows tell you there were two visits, one busy and one quiet, which is a different and often more natural view of behavior.

Window typeHighest count seenWhat it reveals
Tumbling, 5 minutes3Clean per-period totals, but the burst is split
Hopping, 10 by 54Burst visible; some events counted twice
Sliding, 6 minutes4Burst found wherever it starts
Session, 10 minute gap4 in session oneTwo visits: one busy, one quiet
i
Lesson

None of these answers is wrong. Each answers a slightly different question. Choose the one whose question matches what the business really wants to know.

23Capacity Planning: How Big Will the State Get?

Window state lives on disk and in memory. A rough calculation before launch prevents nasty surprises after it.

The basic formula is easy to remember: state entries equal the number of active keys multiplied by the number of windows kept open per key. Then multiply by the average size of one entry, including the key, the window boundaries and the aggregated value. The result is the size of the state store across the whole application, which is then divided among the instances.

Consider a payment company with five million active cards. If it uses five-minute tumbling windows with a two-minute grace period, most cards have only one or two open windows at a time, since a window stays open until its end plus grace. Suppose each entry takes about one hundred bytes. The estimate is five million times two times one hundred bytes, which is roughly one gigabyte. That is comfortable on a single machine, and easily shared across several.

Now suppose the team switches to hourly windows that advance every minute, so each event lands in sixty windows, and each card holds around sixty open windows. The estimate becomes five million times sixty times one hundred bytes, which is about thirty gigabytes. The same business idea now needs thirty times more storage, and every event triggers sixty updates. This is why the ratio of size to advance is the first number to check in a design review.

~1 GB
5 million keys, 2 open windows each, about 100 bytes per entry
~30 GB
same keys, 60 open windows each
30x
storage growth from hopping with a small advance

Do not forget retention and history

Retention adds to the total. If you keep windows for a day so that dashboards can look back, then the number of stored windows per key is a full day divided by the window size, not just the few that are open. Keeping five-minute windows for a day means 288 windows per key. With five million keys and one hundred bytes each, that is about 144 gigabytes. Many teams are surprised to find that retention, not the open windows, dominates their disk usage.

!
Illustrative numbers

These figures are examples to show the method. Real entry sizes depend on your keys, values and storage overhead, so measure with a rehearsal on realistic data before you commit to hardware.

24Testing and Debugging Windowed Applications

Time-based logic is famously hard to test. The trick is to control the clock instead of waiting for it.

Because Kafka Streams follows event time, tests do not need to wait five real minutes to see a five-minute window close. A test can feed the topology a handful of events with chosen timestamps, then feed one more event with a much later timestamp to push stream time forward and close the earlier windows. The library provides a test driver for exactly this purpose, and it runs entirely in memory without any Kafka cluster.

1

Test the normal case

Send events inside one window and check that the count matches by hand.

2

Test the edges

Send an event exactly on a boundary. Confirm it lands in the window you expect, remembering that starts are included and ends are excluded for tumbling and hopping windows.

3

Test lateness

Send an event that arrives within the grace period and one that arrives after it. The first must be counted and the second must be dropped.

4

Test the closing event

Confirm that final results appear only after a later event moves stream time past window end plus grace.

5

Test replay

Run the same events twice, possibly in a different arrival order within the grace period, and check that the results match.

Debugging a wrong number

When a window count looks wrong, ask four questions in order. First, are the timestamps what you think they are? Print a few and compare them with the real times. Second, is the window boundary where you expect, remembering the alignment to UTC? Third, is the dropped-records metric rising, meaning events are arriving after their window closed? Fourth, is the consumer of the output seeing several refinements of the same window, and treating each as a new one? These four causes explain the large majority of confusing results.

Everyday analogy

Testing a windowed job by waiting for real time is like testing a smoke alarm by waiting for a fire. A better plan is to hold a small flame near the sensor on purpose. Feeding chosen timestamps into the test driver is that small controlled flame.

25Time Zones, Daylight Saving and Calendar Windows

Business people think in local days and months. Kafka windows think in fixed slices of UTC. Bridging the two needs care.

A window of twenty-four hours is not the same as a calendar day in every place. In a region that observes daylight saving, one day a year has twenty-three hours and another has twenty-five. A month has anywhere from twenty-eight to thirty-one days. Fixed-length windows cannot represent these calendar ideas exactly, because they always cover the same number of milliseconds.

Teams usually pick one of three approaches. The first is to accept UTC days and label the reports clearly. This is simple and consistent, and it suits global products. The second is to shift each timestamp by the local offset before windowing, so that local midnight becomes a window boundary. This works well for one region but must be handled carefully around daylight saving changes. The third is to compute hourly windows and combine them into local days in the reporting layer, where a database or query engine understands calendars properly. This third option is the most flexible and is a common choice for products that serve several time zones.

i
Practical advice

Store and process everything in UTC, and convert to local time only when showing results to people. Doing the conversion late keeps the data consistent and avoids most daylight saving bugs.

26Real-World and Industry Examples

Windowing sits behind many everyday digital experiences. Here is how the ideas in this guide show up in well-known kinds of companies.

Apache Kafka was created at LinkedIn to move activity events, and it is now used across industries by companies of every size. Public engineering talks and blog posts describe patterns like the ones below. The details of each company’s internal systems differ and change over time, so treat these as illustrations of the technique rather than exact blueprints.

Ride-hailing: demand and supply per zone

A ride-hailing platform divides a city into small zones and counts ride requests and available drivers per zone in short tumbling or hopping windows. When requests outnumber drivers in a zone, prices rise or drivers are nudged to move. Short windows keep the signal fresh, and a small grace period absorbs mobile network delays.

Video streaming: playback health

Streaming services collect start, stop and buffering events from millions of screens. Per-minute windows grouped by country, device model and app version reveal whether a problem is global or limited to one device family. Engineers can pause a rollout within minutes of seeing errors rise.

Payments: velocity checks

Payment companies watch how many attempts a card, account or device makes in a period. Sliding windows are a natural fit because a fraudster does not respect clock boundaries. Rules such as “too many attempts in any short stretch” trigger extra verification or a block.

Advertising: budget pacing

Ad platforms track how much each advertiser has spent so far in the current hour or day, and compare it with the budget. Windowed sums feed a control loop that speeds up or slows down ad delivery so that budgets are used evenly. Pinterest has publicly described using Kafka Streams for this kind of predictive budgeting.

E-commerce: live sales dashboards

Retailers show orders per minute during big sales. Tumbling windows feed the main chart, while hopping windows draw a smooth moving average beside it. Sales events create sudden spikes, so partition counts and cache sizes are planned before the event.

Internet of Things: sensor smoothing

Factories and utilities receive thousands of readings per second. Windowed averages, minimums and maximums reduce noise, and a sliding window can raise an alert when a temperature stays above a limit for a continuous period.

i
Pattern to notice

In every example, the window type follows the question: tumbling for periodic reports, hopping for smooth trends, sliding for bursts, and session for visits. The technology is secondary to choosing the right shape.

27Kafka Streams, ksqlDB and Other Engines

Several tools can window Kafka data. They share ideas but differ in details.

ToolHow you use itWindow supportHow lateness is handled
Kafka StreamsJava library embedded in your applicationTumbling, hopping, sliding, sessionStream time and grace period
ksqlDBSQL-like statements run on a serverTumbling, hopping, sessionGrace period on the window clause
Apache FlinkSeparate cluster with its own APIsTumbling, sliding, session and moreWatermarks and allowed lateness
Spark Structured StreamingSeparate cluster, batch-style engineTumbling, sliding, sessionWatermarks

The biggest conceptual difference is how “time has moved on” is decided. Kafka Streams uses stream time, the largest timestamp seen by a task. Flink and Spark use watermarks, which are markers that flow through the pipeline saying “no event older than this is expected any more”. The goal is the same: decide when a window can be sealed. Kafka Streams is the lightest option to deploy, since it needs no separate cluster, while dedicated engines offer richer features for very large or very complex jobs.

?
Choosing a tool

If your team writes JVM services and wants simple deployment, start with Kafka Streams. If analysts prefer SQL, look at ksqlDB. If you already run Flink or Spark for other work, using their windowing on Kafka input keeps the platform uniform.

28Frequently Asked Questions

Quick answers to the questions that come up most when people first use windowing.

Q1Is windowing a feature of the Kafka broker?
No. Brokers only store and serve events. Windowing is performed by stream processing applications such as Kafka Streams or ksqlDB that read from Kafka.
Q2What is the difference between tumbling and hopping windows?
Tumbling windows are fixed-size and never overlap, so each event is in exactly one window. Hopping windows are fixed-size but start more often than their length, so they overlap and each event can belong to several windows.
Q3How do sliding windows differ from hopping windows?
Hopping windows start on a fixed schedule, so they may split a burst across edges. Sliding windows are defined by the time difference between records, are created only where data exists, and catch any group of events that fit inside the given distance.
Q4What is a session window and when should I use it?
A session window groups events for one key until an inactivity gap passes. Use it when the length of a period is decided by behavior, such as website visits or gaming sessions.
Q5What is stream time?
Stream time is the largest event timestamp a task has seen so far. It moves only forward and is used to decide when windows close, making results repeatable across replays.
Q6What is a grace period?
The extra time a window stays open after its end to accept late events. Once stream time passes window end plus grace, the window is closed and later events for it are dropped.
Q7What happens to late events that miss the grace period?
They are dropped and counted in a metric. The application continues normally. A rising drop rate signals that the grace period is too short for real-world delays.
Q8Why do I see many results for the same window?
By default, Kafka Streams emits updated results as events arrive, merged by a cache and the commit interval. If you need only one final result, use the final-results option in your version, and remember that it waits for the window to close.
Q9Why is my last window never finalized?
Windows close when stream time advances, and stream time advances only with new records. If a partition goes quiet, its last window can stay open. Regular heartbeat events keep time moving.
Q10Do windows survive a crash?
Yes. State is backed by a changelog topic in Kafka, and the new owner of a task rebuilds it before resuming. Standby replicas shorten this recovery, and exactly-once processing prevents double counting.
Q11How do I get daily windows for my local time zone?
Windows align to UTC. To get local-day reports, adjust timestamps by the time zone offset before windowing, or aggregate into hourly windows and combine them in the reporting layer, taking care with daylight saving changes.
Q12How many windows can I run at once?
There is no fixed limit. The practical limit is the state size, which grows with the number of keys times open windows. Watch disk use and restore time, and reduce grace, retention or overlap if they grow too large.

29Summary and Key Takeaways

Windowing is how Kafka-based applications turn endless events into answers tied to time.

Key Takeaways

  • Windowing groups events by time. It gives an endless stream finite slices so counts, sums and averages have meaning, and it is performed by stream processors such as Kafka Streams, not by the brokers.
  • Pick the window to match the question. Tumbling for clean periodic totals, hopping for smooth moving views, sliding for burst detection, and session for activity that ends after a gap.
  • Use event time. Stream time, the largest timestamp seen, decides when windows close, which makes results repeatable even on replay.
  • Grace periods trade accuracy for latency. Measure real lateness, set grace from data, and watch the dropped-records metric.
  • Know when results are emitted. Results refine continuously by default. Use the final-results option if consumers need one value per window, and remember quiet partitions can delay it.
  • Design state for scale and failure. Parallelism equals partitions; use changelog topics, standby replicas and exactly-once processing for reliability, and secure both the topics and the local state.
  • Avoid the classic mistakes. Do not sum overlapping windows, do not use processing time, do not choose enormous grace or tiny hops without measuring the cost.