What is a KStream?
Solution and explanation
What it is
A KStream is Kafka Streams' abstraction of a **record stream**: an unbounded sequence of independent events. Each record is a new fact; a later record with the same key does **not** replace an earlier one.
KStream of payments (key = account):
ACC-1 → ₹500
ACC-2 → ₹200
ACC-1 → ₹300 both ACC-1 events stay; they are separate payments
Typical operations
KStream<String, Payment> payments = builder.stream("payments");
KStream<String, Payment> large = payments.filter((acc, p) -> p.amount() > 100_000);
KStream<String, String> alerts = large.mapValues(p -> "Large payment " + p.id());
alerts.to("payment-alerts");
// Branch by type
Map<String, KStream<String, Payment>> branches = payments.split(Named.as("pay-"))
.branch((k, p) -> p.type() == UPI, Branched.as("upi"))
.branch((k, p) -> p.type() == CARD, Branched.as("card"))
.defaultBranch(Branched.as("other"));
- Stateless:
filter,map,mapValues,flatMap,peek,merge,split. - Re-keying:
selectKey(triggers repartitioning before grouping). - Stateful:
groupByKey().count()/aggregate()turns a stream into a **KTable**. - Joins: stream-stream (within a time window) and stream-table (enrichment).
Examples of things that are streams
Clicks, payments, application submissions, sensor readings, log lines: every event matters on its own.
Summary
A KStream is an append-only stream of independent events where every record counts; you filter, transform, join and aggregate it.
