Kafka Streams의 윈도우 연산
Kafka Streams에서 이벤트를 집계하기 위한 시간 기반 윈도우를 정의하는 방법을 배우며, 텀블링·호핑·슬라이딩 윈도우를 함께 다룹니다.
Kafka Streams의 윈도우 연산은(는) CoddyKit의 무료 Apache Kafka & Stream Processing Fundamentals 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Apache Kafka & Stream Processing Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Apache Kafka & Stream Processing Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro to Stream Windows
In stream processing, data arrives continuously. To perform calculations like "total sales per hour" or "average temperature every 5 minutes," we need to group these continuous events into finite, manageable segments.
This grouping of events based on time is called windowing. It allows us to apply aggregations and transformations over specific periods.
Why Windowing Matters
Imagine analyzing website clicks. You might want to know:
- How many clicks happened in the last minute?
- What's the average user activity over the past 5 minutes, updated every minute?
- When did a user become inactive?
Windowing provides the framework to answer these questions by defining boundaries around your data streams.
Event Time vs. Processing Time
Kafka Streams primarily uses event time. This is the timestamp embedded in the event itself, indicating when the event actually happened at the source.
- Event Time: When the event occurred (preferred).
- Processing Time: When the event is processed by the stream application (less reliable for ordering).
Using event time ensures that results are consistent, even if events arrive out of order or with delays.
Tumbling Windows: Fixed & Non-Overlapping
Tumbling windows are like non-overlapping, fixed-size buckets of time. Each event belongs to exactly one window.
- They are fixed in duration (e.g., 5 minutes).
- They do not overlap.
- They are contiguous, covering all time.
Think of them as a series of distinct time slots, where each event falls into one specific slot.
Tumbling Window Code
Here's how to define a 5-second tumbling window in Kafka Streams to count messages. We use TimeWindows.of() and count().
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.TimeWindows;
import java.time.Duration;
import java.util.Properties;
public class TumblingWindowApp {
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "tumbling-window-app");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey()
.windowedBy(TimeWindows.of(Duration.ofSeconds(5))) // 5-second tumbling window
.count(Materialized.as("tumble-counts"))
.toStream()
.print(org.apache.kafka.streams.kstream.Printed.toSysOut());
KafkaStreams streams = new KafkaStreams(builder.build(), props);
streams.start();
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
}
}Hopping Windows: Overlapping & Moving
Hopping windows are also fixed-size, but they can overlap. They "hop" forward by a specified interval, which is typically smaller than the window size.
- Fixed size (e.g., 10 minutes).
- Overlap with previous/next windows.
- Hop interval (e.g., moves every 5 minutes).
This allows for smoother, more frequently updated aggregations, as a new window result is emitted more often.
Hopping Window Code
Here's how to create a 10-second hopping window that advances every 5 seconds. Events will be counted in multiple overlapping windows.
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.TimeWindows;
import java.time.Duration;
import java.util.Properties;
public class HoppingWindowApp {
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "hopping-window-app");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey()
.windowedBy(TimeWindows.of(Duration.ofSeconds(10)) // 10-second window
.advanceBy(Duration.ofSeconds(5))) // hops every 5 seconds
.count(Materialized.as("hop-counts"))
.toStream()
.print(org.apache.kafka.streams.kstream.Printed.toSysOut());
KafkaStreams streams = new KafkaStreams(builder.build(), props);
streams.start();
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
}
}Session Windows: Data-Driven Activity
Session windows are different. They are data-driven, not fixed-time. They group events that occur within a specified "inactivity gap."
- Window closes if no new event for a key arrives within the gap duration.
- Variable size, non-overlapping for a given key.
- Useful for user activity tracking or network sessions.
If a new event arrives for the same key after the inactivity gap, a new session window starts.
Session Window Code
This example shows how to define a session window with a 5-second inactivity gap. If a key doesn't receive an event for 5 seconds, its current session window closes.
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.SessionWindows;
import java.time.Duration;
import java.util.Properties;
public class SessionWindowApp {
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "session-window-app");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
StreamsBuilder builder = new StreamsBuilder();
builder.stream("input-topic", Consumed.with(Serdes.String(), Serdes.String()))
.groupByKey()
.windowedBy(SessionWindows.with(Duration.ofSeconds(5))) // 5-second inactivity gap
.count(Materialized.as("session-counts"))
.toStream()
.print(org.apache.kafka.streams.kstream.Printed.toSysOut());
KafkaStreams streams = new KafkaStreams(builder.build(), props);
streams.start();
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
}
}Grace Period for Late Events
Events don't always arrive in order or on time. Kafka Streams handles this with a grace period.
- It's extra time a window stays open to accept late-arriving records.
- Defined as part of the window definition (e.g.,
.grace(Duration.ofSeconds(10))). - Events arriving after the grace period are typically dropped or forwarded to a late record topic.
This helps ensure accuracy for aggregations over event time.
Check Your Understanding
Which of the following statements about Kafka Streams windowing are TRUE?
Recap: Windowing in Kafka Streams
We've explored how windowing allows us to perform time-based aggregations on continuous data streams in Kafka Streams.
- Tumbling windows: Fixed, non-overlapping.
- Hopping windows: Fixed, overlapping, advance by an interval.
- Session windows: Data-driven, based on an inactivity gap.
- Grace period: Important for handling late-arriving events.
Mastering these window types is crucial for building robust real-time analytics and stream processing applications.
자주 묻는 질문
“Kafka Streams의 윈도우 연산” 강의는 무료인가요?
네 — “Kafka Streams의 윈도우 연산” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Apache Kafka & Stream Processing Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Apache Kafka & Stream Processing Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
“Kafka Streams의 윈도우 연산”에서 뭘 배우나요?
Kafka Streams에서 이벤트를 집계하기 위한 시간 기반 윈도우를 정의하는 방법을 배우며, 텀블링·호핑·슬라이딩 윈도우를 함께 다룹니다. 브라우저에서 직접 실행하는 실습 코드로 Apache Kafka & Stream Processing Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Apache Kafka & Stream Processing Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Apache Kafka & Stream Processing Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Kafka Streams의 윈도우 연산” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Apache Kafka & Stream Processing Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Apache Kafka & Stream Processing Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Kafka Streams의 윈도우 연산
- 스트림의 조인 및 집계
- 스트림 분석을 위한 KSQL 소개
- 대화형 쿼리와 상태 저장소