Simple definition#
Stream processing computes results continuously as events arrive: filtering, enriching, aggregating, joining and detecting patterns. Batch processing instead waits for a complete dataset. The result is another stream, a table or an action, available in milliseconds to seconds.
The problem#
Fraud must be stopped before money leaves. Risk limits, customer notifications and dashboards lose value with every minute of delay. Running batch jobs more often does not scale and cannot handle late or out-of-order events correctly.
Core concepts#
| Concept | Meaning |
|---|---|
| Stateless operation | Each event is handled alone: map, filter, route, mask |
| Stateful operation | Needs memory of earlier events: counts, sums, joins, deduplication, pattern detection |
| Event time | When the event happened (in the payload) |
| Processing time | When the processor sees it |
| Watermark | The processor’s estimate that “no more events older than T will arrive”. It lets windows close. |
| Window | A finite slice of an infinite stream |
| State backend | Where keyed state lives: memory, RocksDB, or remote / disaggregated storage |
| Checkpoint | A consistent snapshot of all state and source offsets, used for recovery |
Event time and watermarks#
Mobile payments may arrive minutes late, and partitions progress at different speeds. Processing by event time gives correct results regardless of arrival order. Watermarks trade completeness against latency:
flowchart LR
E1["event t=10:00:02"] --> W["watermark = max event time − 5s"]
E2["event t=10:00:09"] --> W
E3["late event t=10:00:01<br/>arrives after window closed"] --> L["allowed lateness → update<br/>or side output for late data"]
W --> C["window [10:00:00, 10:00:05) closes<br/>when watermark ≥ 10:00:05"]
- Set the out-of-orderness bound from measured lateness (for example p99).
- Use idleness detection, so one quiet partition does not stall the watermark.
- Route late events to a side output rather than silently dropping them.
Windows#
| Window | Shape | Example |
|---|---|---|
| Tumbling | Fixed size, no overlap | Payments per merchant per minute |
| Hopping / sliding | Fixed size, overlapping | Spend over the last 1 hour, updated every 5 minutes |
| Session | Activity separated by a gap | A user’s banking session |
| Global + trigger | Custom | Every 100 events |
Joins#
- Stream–stream join (windowed): match
PaymentInitiatedwithPaymentConfirmedwithin 10 minutes. - Stream–table join: enrich each payment with the latest customer risk profile from a compacted topic or CDC stream (a temporal or lookup join).
- Interval join: events from two streams within a time bound of each other.
State, checkpoints and exactly-once#
flowchart LR
SRC["Kafka source<br/>offsets"] -->|"barrier n"| OP1["keyBy(account)<br/>window state"] -->|"barrier n"| SINK["Kafka sink<br/>transaction"]
OP1 -.->|"snapshot state n"| STORE["Durable checkpoint storage<br/>(S3, HDFS)"]
SRC -.->|"offsets n"| STORE
SINK -.->|"pre-commit txn n"| STORE
Flink injects barriers into the stream. Every operator snapshots its state when the barrier passes. The Kafka sink pre-commits a transaction and commits it only when the checkpoint completes (two-phase commit), giving end-to-end exactly-once from Kafka to Kafka. After a failure, Flink restores the last checkpoint and rewinds the source offsets.
Apache Flink vs Kafka Streams#
| Apache Flink | Kafka Streams | |
|---|---|---|
| Form | Distributed processing engine (cluster, Kubernetes operator) | Java library inside your application |
| Sources and sinks | Kafka, files, CDC, JDBC, Iceberg, Pulsar, Kinesis and many more | Kafka in, Kafka out |
| State | RocksDB or disaggregated state (Flink 2.x ForSt on object storage) | RocksDB plus changelog topics |
| APIs | DataStream, Table API, Flink SQL, CEP, PyFlink | Streams DSL, Processor API |
| Scale | Very large, multi-tenant | Scales with your app instances and partitions |
| Best for | Complex pipelines, large state, SQL analytics, many systems | Kafka-centric microservices doing joins and aggregations |
What is new:
- Flink 2.0 (2025) introduced disaggregated state management (state on remote storage with a local cache), a materialised-table model that unifies batch and streaming, and removed old APIs such as DataSet and the Scala API.
- Flink 2.2 (December 2025) focused on real-time AI:
ML_PREDICTmodel inference in Flink SQL and aVECTOR_SEARCHfunction for streaming similarity search, plus scheduling improvements. - Kafka Streams gained server-side rebalancing (KIP-1071, GA with a limited feature set in Kafka 4.2).
Flink SQL example: velocity check#
-- Payments per card in 10-minute hopping windows; flag bursts
CREATE TABLE payments (
payment_id STRING, card_token STRING, merchant_id STRING,
amount DECIMAL(18,2), country STRING, event_time TIMESTAMP(3),
WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND
) WITH ('connector' = 'kafka', 'topic' = 'payments.authorised.v1', 'format' = 'avro-confluent', ...);
INSERT INTO fraud_alerts
SELECT card_token, window_start, window_end,
COUNT(*) AS txn_count, SUM(amount) AS total, COUNT(DISTINCT country) AS countries
FROM TABLE(HOP(TABLE payments, DESCRIPTOR(event_time), INTERVAL '1' MINUTE, INTERVAL '10' MINUTE))
GROUP BY card_token, window_start, window_end
HAVING COUNT(*) > 8 OR COUNT(DISTINCT country) > 2;
A real-time fraud scoring pipeline#
- Payment and device events land on Kafka topics keyed by account or card token.
- A Flink job computes features in event-time windows (velocity, spend, new device, geo distance), keeping keyed state with checkpoints.
- Features are written to a low-latency feature cache, which the authorisation service reads synchronously within its latency budget (often under 50 ms).
- High-risk patterns produce alerts for case management. All events also land in the lakehouse for model training and audit.
Streaming for AI#
- Fresh context: stream changes into vector stores and feature stores so RAG and models see current data.
- Inference in the stream: score events with models (Flink
ML_PREDICT, or a call-out to a model service with async I/O). - Agent events: agents can consume and produce events. Treat their outputs as untrusted input, and govern them like any other producer. See AI security.
Operating stream processors#
- Size parallelism to the partition count and plan savepoints for upgrades. Keep operator UIDs stable so state maps correctly.
- Watch checkpoint duration and size, backpressure, watermark lag, consumer lag and late-event rates.
- Run on Kubernetes with the Flink Kubernetes Operator, or use a managed service (Confluent Cloud for Flink, Amazon Managed Service for Apache Flink, Ververica).
Common mistakes#
Quick check#
What is a watermark? The processor’s assertion that no more events older than time T are expected, which lets event-time windows close. It trades latency for completeness.
Tumbling vs hopping vs session windows? Tumbling windows are fixed and non-overlapping. Hopping windows are fixed and overlap. Session windows are bounded by inactivity gaps.
How does Flink achieve exactly-once to Kafka? Checkpoint barriers snapshot state and source offsets consistently. The Kafka sink uses transactions that commit when the checkpoint completes.
When pick Kafka Streams over Flink? For Kafka-in, Kafka-out processing embedded in a microservice, without running a separate cluster.
What did Flink 2.x add?
Disaggregated state on remote storage (2.0), and AI functions such as ML_PREDICT and VECTOR_SEARCH in SQL (2.2).
Summary#
- Stream processing turns events into continuous answers. Stateful operations need state, checkpoints and event time.
- Watermarks and windows give correct results with late, out-of-order data.
- Flink suits large, multi-system and SQL-heavy pipelines. Kafka Streams suits Kafka-centric services.
- Streaming increasingly feeds AI: features, embeddings and in-stream inference.
References#
- Apache Flink, documentation and Flink 2.2.0 release announcement.
- Apache Kafka, Kafka Streams documentation.
- Tyler Akidau et al., Streaming Systems (O’Reilly), the definitive treatment of event time and watermarks.