Apache Flink
Apache Flink is an open-source engine for stateful stream processing. You write a program that reads unbounded streams of events (usually from Kafka or Kinesis), transforms, joins and aggregates them while keeping state such as counts, windows or recent history, and writes results continuously to databases, other topics or files. Flink runs that program in parallel across a cluster, keeps its state fault-tolerant with periodic snapshots, and recovers from failures without losing or double-counting events.
The properties that define it:
- True streaming: events are processed one at a time as they arrive, not in small batches, so latency is typically milliseconds to low seconds.
- Stateful: operators keep large amounts of state (gigabytes to terabytes across the job) locally, partitioned by key, so lookups are local memory or disk reads, not network calls.
- Exactly-once state: after a failure, Flink restores a consistent snapshot of all state and rewinds its sources, so every event affects the state exactly once.
- Event time: Flink can compute results by when events happened, not when they arrived, using watermarks to handle out-of-order and late data.
- Unified batch and streaming: a bounded dataset is just a stream that ends, so the same program and SQL can run over historical data or live streams.
Flink comes up in interviews whenever a design needs to compute something continuously over a stream: real-time counts and aggregations (ad click aggregation, trending hashtags, live dashboards), streaming fraud rules ("five countries in one minute"), sessionization, enrichment and joins, or real-time ETL. Saying "a Flink job consumes from Kafka" is the easy part. Interviewers then ask how it handles late events, what happens when a machine dies, whether counts can be duplicated, and how state scales. This post covers those answers.
The Programming Model
A Flink program describes a dataflow graph: sources that read streams, operators that transform them, and sinks that write results. Here's a job that counts clicks per ad per minute, by event time:
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(30_000); // snapshot state every 30 s
KafkaSource<Click> source = KafkaSource.<Click>builder()
.setBootstrapServers("kafka:9092")
.setTopics("ad-clicks")
.setGroupId("click-counter")
.setValueOnlyDeserializer(new ClickDeserializer())
.build();
WatermarkStrategy<Click> wm = WatermarkStrategy
.<Click>forBoundedOutOfOrderness(Duration.ofSeconds(10)) // events may be up to 10 s late
.withTimestampAssigner((click, ts) -> click.eventTimeMillis());
env.fromSource(source, wm, "clicks")
.filter(c -> !c.isBot())
.keyBy(Click::adId) // partition by ad
.window(TumblingEventTimeWindows.of(Duration.ofMinutes(1)))
.aggregate(new CountClicks()) // incremental count per window
.sinkTo(clickCountSink); // e.g. an OLAP store or Kafka topic
env.execute("ad-click-counter");
The same logic in Flink SQL:
SELECT ad_id,
window_start,
COUNT(*) AS clicks
FROM TABLE(
TUMBLE(TABLE ad_clicks, DESCRIPTOR(event_time), INTERVAL '1' MINUTE))
GROUP BY ad_id, window_start, window_end;
A few ideas from that program carry most of Flink's model:
Parallelism. Each operator runs as N parallel subtasks. A source with parallelism 32 reads 32 slices of the input (for example, Kafka partitions); a window operator with parallelism 64 runs 64 instances, each owning a share of the keys.
keyBy and partitioning. keyBy(adId) repartitions the stream over the network so that every event for the same ad goes to the same subtask. That's what makes per-key state possible: the subtask that owns ad 42 holds ad 42's counters, and nothing else touches them. It's the streaming equivalent of a shuffle.
Operator chaining. Operators that don't need a shuffle between them (source → filter) are fused into one task and run in the same thread, passing records by function call. Only keyBy, rebalances and similar steps cross the network.