Skip to content

Apache Flink and Stream Processing

Advanced 57 min read Part 15 of 18

Flink in practice: dataflow jobs and parallelism, keyed state and backends, checkpoints and exactly-once, event time and watermarks, windows, Kafka I/O.

Summary#

Apache Flink is a distributed engine for stateful stream processing: it runs continuous computations over unbounded streams of events (clicks, payments, sensor readings, database changes), keeping per-key state such as counts, sessions and models, and producing results with millisecond-to-second latency.

You write a job, a graph of operators (sources, maps, filters, keyBy, windows, joins, sinks). Flink splits each operator into parallel subtasks that run in task slots on TaskManagers, coordinated by a JobManager.

What makes Flink valuable is what it does for you that a hand-rolled Kafka consumer does not:

  • Managed keyed state. State lives in memory or in local RocksDB, partitioned by key so it scales out, and redistributed automatically when you rescale.
  • Fault tolerance with exactly-once state. Periodic, asynchronous checkpoints use barriers flowing with the data. After a crash, Flink restores the last checkpoint and rewinds the sources, so every event affects the state exactly once.
  • Event-time processing. Watermarks track how far event time has progressed. Windows therefore aggregate by when events happened, not when they arrived, even when events arrive out of order or late.
  • End-to-end exactly-once. It combines replayable sources (Kafka) with transactional or idempotent sinks.

Use Flink for:

  • real-time aggregation (ad clicks per minute, live dashboards, Top-K);
  • fraud and anomaly detection;
  • streaming ETL and CDC pipelines;
  • real-time features for ML;
  • event-driven applications.

The first question is always "do we really need real-time?" If minutes or hours of latency are acceptable, a periodic batch job (Spark, SQL in a warehouse) is simpler and cheaper to run. Kafka Streams fits smaller Kafka-to-Kafka apps as a library. Spark Structured Streaming fits when you're already on Spark and sub-second latency isn't needed.

Why It Exists#

Start with the simplest streaming job: a service reads click events from a Kafka topic, reformats each one, and writes it to a database. Each event is processed independently. If the service crashes, it restarts from its last committed Kafka offset. To scale, you add consumers. This is stateless processing, and any plain Kafka consumer handles it well. (Consumer groups and offsets are covered in Apache Kafka in Practice.)

Now change the requirement slightly: count clicks per ad over each one-minute window. Suddenly every event depends on the ones before it. You need state, the running count per ad per minute, and four hard problems appear at once.

  1. Crash recovery. Keep the counters in memory, and a crash loses them. Re-reading the whole topic to rebuild the counts is slow and expensive. Worse, it's easy to get wrong: did you commit Kafka offsets before or after the counts were safely written? Commit before, and a crash loses events. Commit after, and a crash double-counts them. Getting exactly-once effect requires that the offsets and the state be saved atomically together.
  2. Scaling. Add a fourth consumer and Kafka rebalances partitions across consumers. The counters for the partitions that moved are still in the old consumer's memory. Moving state safely between machines, without losing or double-counting anything in flight, is a delicate distributed protocol.
  3. Out-of-order and late events. A phone that was offline sends a click from 10:00:58 at 10:01:20. Count by arrival time (processing time), and the click lands in the wrong minute. Count by event time, and you need to know when the 10:00 minute is complete so you can emit it, without waiting forever for stragglers.
  4. Windows, joins and timers. Sessions that close after 30 minutes of inactivity, joins between a payment stream and a refund stream within 24 hours, "alert if no heartbeat in 60 seconds": each needs timers, buffers and state cleanup that survive failures.

You can build all this yourself on top of raw consumers, a database and cron, and many teams have. But it's subtle, error-prone and expensive to maintain. Stream processing engines package the solutions as reusable abstractions:

  • managed state;
  • consistent distributed snapshots;
  • event time with watermarks;
  • windowing;
  • exactly-once sinks.

A brief history.

  • Flink grew out of Stratosphere, a research project at TU Berlin and partner institutions (around 2009–2014). It became an Apache top-level project in December 2014.
  • Its founders started data Artisans, which Alibaba acquired in 2019 (renamed Ververica). Alibaba also merged back many improvements from its internal fork, Blink.
  • Flink 1.0 shipped in 2016. Flink 2.0 shipped in 2025, adding disaggregated state stored in object storage.

Two papers shaped the design:

  • Google's "The Dataflow Model" (Akidau et al., VLDB 2015), which defined the vocabulary of event time, watermarks, windows and triggers. Apache Beam and Google Cloud Dataflow implement it.
  • Flink's own "Lightweight Asynchronous Snapshots for Distributed Dataflows" (Carbone, Fóra, Ewen, Haridi and Tzoumas, 2015), which adapted the Chandy–Lamport snapshot algorithm (1985) into Flink's checkpointing.

A word of caution before you reach for it. Stream processing is harder to build, test and operate than batch:

  • Jobs run forever.
  • State must stay compatible across code changes.
  • Watermarks must be tuned.
  • Backpressure and checkpoint failures need on-call attention.

Many problems that look like streaming problems are really batch problems with a short schedule, or simple stateless consumers. For example, a nightly report, an hourly rollup, or a dashboard that can lag by 5 minutes. Ask "what latency does the business actually need?" before committing. The engineers who inherit the system will thank you for the simpler choice when it's enough.

How It Works#

We'll go from the programming model (streams, operators, jobs) to the runtime (JobManager, TaskManagers, slots), then to the three ideas that make Flink special: state, time and checkpoints. After that come Kafka integration, the APIs, and worked sample jobs.

Streams, sources, sinks and operators#

A stream is a potentially infinite sequence of records. Flink treats batch as a special case, a bounded stream, so the same engine and APIs run both. In practice, Flink is chosen mostly for unbounded streams.

Sources bring data in:

  • Kafka, by far the most common;
  • Amazon Kinesis and Pulsar;
  • files and directories, including continuously monitored S3 prefixes;
  • CDC connectors, through Flink CDC, which reads MySQL binlogs or PostgreSQL logical replication directly;
  • sockets and custom sources.

Since Flink 1.12 the unified Source API (FLIP-27) splits a source into a split enumerator on the JobManager, which discovers splits such as Kafka partitions or files, and readers on the workers. That's how a Kafka source picks up new partitions while running.

Sinks send results out: Kafka, databases over JDBC, Elasticsearch/OpenSearch, Redis, Cassandra, S3 or HDFS (the FileSink writes Parquet or ORC and commits files on checkpoints), Iceberg, Delta and Hudi tables, and OLAP stores such as ClickHouse, Druid and Pinot. Each sink's guarantee depends on whether it can join Flink's checkpoint protocol (transactional) or tolerate replays (idempotent upserts).

Operators transform streams.

OperatorWhat it does
map, filter, flatMapOne record in, one, zero or many out (stateless)
keyBy(key)Repartitions the stream by key, so all records with the same key go to the same parallel instance; creates a KeyedStream that unlocks keyed state, timers and windows
reduce, aggregateRolling or windowed aggregation per key
window(...)Groups keyed records into finite windows (tumbling, sliding, session) and applies a function when each window fires
process (KeyedProcessFunction)The low-level escape hatch: per-record logic with full access to keyed state and event-time or processing-time timers
union, connectMerge streams of the same type, or co-process two streams of different types with shared state (for example, rules plus events)
join, intervalJoin, coGroupJoin two keyed streams within a window or time interval
Async I/OEnrich records by calling an external service or database without blocking, with many requests in flight per subtask
Side outputsEmit secondary streams from an operator, for example late events or malformed records
Broadcast stateSend a low-volume stream (rules, config) to every parallel instance of an operator

Your program declares a dataflow graph: sources, then operators, then sinks. When it's submitted, Flink converts it in stages:

  1. StreamGraph: your logical operators.
  2. JobGraph: chained operators, where consecutive one-to-one operators such as map → filter are fused into one task, avoiding serialisation between them.
  3. ExecutionGraph: the physical plan, with one vertex per parallel subtask, scheduled onto the cluster.

Edges between tasks are either forward (one-to-one, chainable), hash (after keyBy, all-to-all by key), rebalance (round-robin) or broadcast.

Defining and submitting a job#

Jobs are written against one of several APIs, each on top of the same runtime:

  • DataStream API (Java, Python): full control over operators, state and timers.
  • Table API / Flink SQL: declarative relational queries over streams, with an optimiser. Windowed aggregations, joins, deduplication and Top-N become a few lines of SQL. Most new pipelines at many companies start here.
  • ProcessFunction: the lowest level, embedded in the DataStream API.
  • Libraries on top, including FlinkCEP for complex event patterns (such as "three failed logins then a success from a new country within 10 minutes") and the Stateful Functions project.

The ad-click aggregation from the problem statement, in Flink SQL:

CREATE TABLE clicks (
  impression_id STRING, ad_id STRING, user_id STRING, ts TIMESTAMP(3),
  WATERMARK FOR ts AS ts - INTERVAL '10' SECOND          -- tolerate 10 s out-of-order
) WITH ('connector' = 'kafka', 'topic' = 'clicks', 'format' = 'json',
        'properties.bootstrap.servers' = 'kafka:9092', 'scan.startup.mode' = 'group-offsets');
 
CREATE TABLE ad_clicks_per_minute (
  ad_id STRING, window_start TIMESTAMP(3), clicks BIGINT,
  PRIMARY KEY (ad_id, window_start) NOT ENFORCED          -- upsert sink: replays overwrite, never double-add
) WITH ('connector' = 'jdbc', 'url' = 'jdbc:postgresql://olap:5432/ads', 'table-name' = 'ad_clicks_per_minute');
 
INSERT INTO ad_clicks_per_minute
SELECT ad_id, window_start, COUNT(*) AS clicks
FROM TABLE(TUMBLE(TABLE clicks, DESCRIPTOR(ts), INTERVAL '1' MINUTE))
GROUP BY ad_id, window_start, window_end;

In the DataStream API, the same logic reads, in pseudo-code: source(kafka "clicks") → assignTimestampsAndWatermarks(boundedOutOfOrderness 10s) → keyBy(adId) → window(TumblingEventTimeWindows.of(1 min)) → aggregate(count) → sink(upsert).

Submitting. You package the job (a JAR, Python files or a SQL script) and submit it to a cluster. There are three deployment modes:

  • Application mode (the production default): the cluster is created for the application and its main() runs on the JobManager. That gives one isolated cluster per job, and a cluster that dies with the job.
  • Session mode: a long-running cluster shared by many jobs. Startup is fast, but isolation is weak: one job's TaskManager crash affects the others.
  • Per-job mode on YARN, now deprecated in favour of application mode.

On Kubernetes, the Flink Kubernetes Operator manages jobs as custom resources. It handles upgrades with savepoints, autoscaling, and restarts. Managed offerings include Amazon Managed Service for Apache Flink (formerly Kinesis Data Analytics), Confluent Cloud for Apache Flink, Ververica, Alibaba Cloud Realtime Compute, and Aiven.

Running jobs are controlled with flink run, flink cancel, flink savepoint and flink stop --savepointPath, or through the REST API and web UI. The UI shows the job graph, per-operator throughput, backpressure, watermarks, checkpoint history and state sizes.

Cluster architecture: JobManager, TaskManagers and slots#

The JobManager is the coordinator, and it has three parts:

  • The Dispatcher accepts submissions and serves the REST API and web UI.
  • The ResourceManager acquires TaskManager slots. On Kubernetes or YARN it requests new pods or containers on demand.
  • A JobMaster runs per job. It builds the ExecutionGraph, schedules tasks into slots, triggers checkpoints, and orchestrates failover.

For high availability, a standby JobManager takes over through leader election in ZooKeeper or Kubernetes ConfigMaps, and job metadata and checkpoint pointers live in durable storage. That's one of the main uses of coordination services described in ZooKeeper and etcd.

TaskManagers are the worker JVMs that execute tasks, buffer and exchange data over the network, and hold state. Each TaskManager offers a fixed number of task slots, each a fraction of its managed memory. A common setup is one slot per CPU core.

Slots and parallelism. Each operator has a parallelism, the number of parallel subtasks that run it. Set it globally (parallelism.default), per operator, or let the adaptive scheduler choose. By default, Flink uses slot sharing: one slot can host one subtask of each operator in the job, so a whole pipeline slice (source → window → sink) lives in one slot. The rule of thumb that follows is total slots needed = the maximum operator parallelism. Slot sharing also co-locates cheap and expensive operators, which evens out load.

Data exchange and backpressure. Records between tasks on different machines are serialised into network buffers (32 KB by default) and sent over long-lived TCP connections. Since Flink 1.5, flow control is credit-based: a receiver announces how many buffers it has free, and the sender only sends that many. When a downstream operator is slow (a slow sink, a hot key, GC), its input buffers fill up. Credits stop, and the sender's output buffers fill. Then the sender slows down, and the pressure propagates all the way back to the source, which simply reads from Kafka more slowly. This backpressure is a feature, not a bug: nothing is dropped and nothing overflows memory. Kafka absorbs the backlog as consumer lag. But persistent backpressure means the job can't keep up, and it slows checkpoints too, as we'll see. The web UI marks backpressured tasks, and the busyTimeMsPerSecond and backPressuredTimeMsPerSecond metrics show which operator is the bottleneck. It's usually the first one that isn't backpressured downstream.

Parallelism, keys and key groups#

Here's a job with parallelism 3, reading a 6-partition Kafka topic:

keyBy hashes each key (murmur hash of the key's hashCode) into one of maxParallelism key groups. By default that's at least 128, and it's set once per job. The key groups are split into contiguous ranges, one range per parallel subtask. Key groups are the unit of state redistribution. When you rescale from 3 to 4 subtasks (by restoring a savepoint with a new parallelism), Flink reassigns key-group ranges and each new subtask reads exactly the state files for its ranges. No per-key reshuffling is needed. That's why maxParallelism can't change without losing keyed state: set it generously (for example 720 or 1,024 for jobs that may grow) when the job is first deployed.

Two practical consequences:

  • Source parallelism is bounded by Kafka partitions. With 6 partitions, a source parallelism above 6 leaves subtasks idle. Downstream operators can have higher parallelism than the source. Plan the Kafka partition count with stream processing in mind.
  • Hot keys can't be split by adding parallelism. All records for one key land in one subtask. If one ad gets 30% of all clicks (the celebrity ad), one subtask is overloaded and backpressures the whole job. The fix is key salting with two-stage aggregation. First key by adId + random(0..N) and pre-aggregate per salted key in a short window. Then key by adId and sum the partial counts. Flink SQL does this automatically with local-global aggregation (table.optimizer.agg-phase-strategy: TWO_PHASE, with mini-batch enabled) and split-distinct aggregation for COUNT(DISTINCT).

State is any data an operator remembers between records. Flink manages it so that it's partitioned, fault-tolerant and rescalable.

Keyed state is scoped to the current key. Inside a keyed operator, state.value() returns the value for the key of the record being processed. The primitives are:

  • ValueState<T>: one value per key, such as a running count or the last-seen timestamp.
  • ListState<T>: a list per key, such as recent transactions.
  • MapState<K, V>: a map per key, such as per-merchant counts for a card. With RocksDB, individual entries are read and written without deserialising the whole map.
  • ReducingState, AggregatingState: values folded on insert.

Window contents, timers and SQL aggregation accumulators are all built on keyed state.

Operator state (non-keyed) is scoped to a parallel subtask instead of a key. The prime example is the Kafka source's partition offsets, which are redistributed across subtasks on rescale. Broadcast state is a special operator state replicated to every subtask, used for rules and configuration that every instance must see.

State TTL expires entries automatically after a configured time since their last write or read. Without it, a job that remembers "every user we've ever seen" grows without bound. Always set TTLs, or clear state with timers, for per-key state whose key space is unbounded: user IDs, session IDs, impression IDs.

State backends decide where the working state lives:

BackendWhere state livesStrengthsLimits
HashMapStateBackendJava objects on the TaskManager heapFastest access (no serialisation per read)State must fit in heap; large heaps mean GC pauses; full snapshots each checkpoint
EmbeddedRocksDBStateBackendRocksDB (an embedded LSM-tree store) on local disk, with a block cache in managed memoryState far larger than RAM (TBs per job); incremental checkpoints upload only new SST filesEvery access serialises/deserialises; slower per record (micro- rather than nanoseconds); needs fast local SSD
ForSt (Flink 2.0, disaggregated)Primary copy in remote object storage (S3), with a local cacheFast rescaling and recovery (no state download); compute and storage scale separatelyNewer; remote-access latency hidden by asynchronous state access

The checkpoint storage (where snapshots are persisted) is configured separately. In production it's always durable remote storage, such as S3, GCS, HDFS or Azure Blob, never the JobManager's memory.

Choosing: use RocksDB for any state that can grow past a few GB per TaskManager, or that benefits from incremental checkpoints. That covers most production jobs with windows over many keys, joins or deduplication. Use the heap backend for small, latency-critical state. The LSM-tree internals that make RocksDB fast for writes and slower for reads are covered in Storage Engines: B-Trees vs LSM Trees.

Time: event time, processing time and watermarks#

Flink distinguishes two notions of time:

  • Processing time: the wall clock of the machine running the operator when it handles the record. It's simple and has the lowest latency, but it isn't deterministic. Replay yesterday's data and every record lands in "now"'s window. A slow consumer or a backlog after an outage shifts records into the wrong windows.
  • Event time: the timestamp inside the record, when the click or payment actually happened. Results are correct and reproducible, and replays give the same answer. The price is that Flink must reason about completeness: when has it seen all the events for 10:00–10:01?

(Ingestion time, the time a record entered Flink, is a middle ground that's rarely used now.)

Watermarks answer the completeness question. A watermark is a special record flowing through the stream that carries a timestamp W. It's an assertion: "no more events with timestamp ≤ W are expected". When an event-time window's end is ≤ the current watermark, the window can fire and emit its result.

The usual watermark strategy is bounded out-of-orderness: watermark = (maximum event timestamp seen so far) − (allowed delay). With a 10-second bound, after seeing an event stamped 10:01:12, the watermark advances to 10:01:02. That closes the 10:00–10:01 window, because 10:01:00 ≤ 10:01:02.

How watermarks flow through a parallel job:

  • Each source subtask, ideally each Kafka partition, generates its own watermarks, because partitions progress at different speeds.
  • An operator with several inputs tracks the watermark of each input, and its own watermark is the minimum across them. The slowest input holds back time for everyone, which is correct: you can't close 10:00 if partition 3 is still delivering 9:59.
  • Idle sources are the classic pitfall. A Kafka partition with no traffic never advances its watermark, so the minimum never moves and windows never fire. withIdleness(Duration.ofMinutes(1)) marks a silent partition as idle, so it's excluded from the minimum until data returns.
  • Watermark alignment (since 1.15) pauses source splits that run too far ahead of the others. That keeps window state from ballooning when one partition is far behind, for example while catching up a backlog.

The latency and completeness trade-off. The out-of-orderness bound is a dial:

  • A small bound (1 s) gives fast results but drops or mis-assigns events delayed by more than 1 s.
  • A large bound (5 min) handles stragglers but delays every result by 5 minutes, and holds 5 extra minutes of window state.

The right value comes from measuring actual lateness. For example, "p99.9 of clicks arrive within 8 s of their event time" suggests a 10 s bound. Mobile clients that buffer events while offline produce long tails, sometimes hours, which are handled by the late-data tools below rather than by a huge bound.

Late events, those arriving after the watermark has passed their window, can be handled three ways:

  1. Dropped, the default.
  2. Allowed lateness: allowedLateness(Duration.ofMinutes(5)) keeps a fired window's state for 5 more minutes, and re-fires it with an updated result for each late event. The sink must handle updates, typically with upserts keyed by (key, window).
  3. Side output: sideOutputLateData(tag) sends late events to a separate stream, for example to S3 for the batch reconciliation job, or to a correction pipeline.

Windows#

Windows cut an infinite keyed stream into finite chunks you can aggregate.

  • Tumbling windows have a fixed size and don't overlap: clicks per minute, revenue per hour. Each event belongs to exactly one window. This is the cheapest kind.
  • Sliding (hopping) windows have a size and a slide, such as "the last 5 minutes, updated every minute". Each event belongs to size/slide windows, 5 here. A naive implementation stores each event 5 times. Flink SQL's window aggregations and pre-aggregating AggregateFunctions keep one accumulator per window rather than the raw events. For very fine slides (a 1-hour window sliding every second, 3,600 windows per event), use a pane-based approach: aggregate per-second tumbling panes, then sum the latest 3,600 panes.
  • Session windows are per key and close after a gap of inactivity: a user's browsing session ends after 30 minutes of silence. They merge, because an event arriving between two sessions can join them into one. That makes them more expensive, and only mergeable state works.
  • Global windows with custom triggers, such as "every 100 events" or "when the total exceeds $1,000".
  • Cumulative windows (Flink SQL): "today so far, updated every minute". This is the natural shape for a live daily dashboard.

Triggers decide when a window emits:

  • By default, at the end of the window in event time, when the watermark passes it.
  • Early-firing triggers emit partial results before the window closes. For example, every 2 seconds of processing time while a 1-minute window is open. That's how a live dashboard shows the current minute filling up, with low latency on top of event-time correctness. In the reference's ad-click design this is the "flush interval" lever: aggregate per minute, but flush updates every few seconds, so the latest minute is simply incomplete until its boundary passes.
  • Later firings either replace or add to earlier ones. With replacing results and an upsert sink, downstream values are always correct.
  • Evictors remove elements before or after the window function runs. They're rarely needed, and they force Flink to keep the raw elements.

Window cost, as a worked example.

  • Inputs: 1 million active ads, a 1-minute tumbling count, and a 10-second out-of-orderness bound.
  • Open windows: at any moment, about 1.17 minutes of windows are open per key (the current minute, plus the previous one until the watermark passes it). That's about 2 accumulators per active key.
  • State: each accumulator is a key (about 40 bytes serialised), a window, and an 8-byte count, about 100 bytes in RocksDB with overhead. That's about 2 M × 100 B = 200 MB of state, which is tiny.
  • The same with a 24-hour sliding window updated every minute: 1,440 windows per key, so about 144 GB. The pane approach above (1,440 per-minute panes, summed on demand) has the same state size but far fewer updates per event.

This is the kind of arithmetic that decides between a heap backend and RocksDB, and that sometimes says "do the 24-hour number in the OLAP store, not in Flink".

Checkpoints and exactly-once#

Flink's fault tolerance rests on consistent distributed snapshots of all operator state, taken while the job keeps running. The algorithm is asynchronous barrier snapshotting, a variant of Chandy and Lamport's 1985 algorithm for determining global states of distributed systems.

  1. Trigger. The JobMaster's checkpoint coordinator periodically tells every source to start checkpoint n. A typical interval is 10 seconds to a few minutes.
  2. Sources snapshot their position (the Kafka offsets per partition, as operator state), then inject a barrier n into their output streams. A barrier is a marker that splits the stream into "before checkpoint n" and "after".
  3. Barriers flow with the data. When an operator with several inputs gets barrier n on one input, it waits until barrier n has arrived on all its inputs. Meanwhile it buffers records arriving after the barrier on the inputs that already delivered it. This is barrier alignment. It guarantees that the operator's state reflects exactly the records before the barrier on every input.
  4. Operators snapshot their state. Once aligned, an operator takes a synchronous, cheap part: with RocksDB, a local checkpoint that hard-links the immutable SST files. Then it forwards the barrier and keeps processing. The upload to S3 happens asynchronously in the background. That's why checkpoints don't pause the pipeline for long.
  5. Acknowledgement. Each task acks to the coordinator when its snapshot is durable. When all tasks have acked, the coordinator writes the checkpoint metadata: the checkpoint is complete. Older checkpoints can then be discarded (by default, Flink retains the latest one).

Recovery. When a task fails (a machine dies, an exception, an out-of-memory error), Flink stops the affected tasks:

  • Restore: it reloads every operator's state from the last completed checkpoint.
  • Rewind: it resets the sources to the offsets stored in that checkpoint.
  • Replay: processing resumes from there.

Records processed after the checkpoint are re-processed, but the state they affected was rolled back too. So every record affects the state exactly once. That's what "exactly-once" means in Flink: exactly-once state consistency, not "each record processed exactly once physically".

Regional failover restarts only the tasks connected to the failed one, through pipelined data exchanges. Restart strategies decide how often to retry: fixed-delay, exponential-delay (the default in recent versions) or failure-rate.

End-to-end exactly-once also needs the outside world to agree. That means:

  • A replayable source: Kafka, Kinesis or files, any source that can rewind to a stored offset.
  • A sink that's either idempotent or transactional:
    • Idempotent sinks write results keyed so that a replay overwrites rather than duplicates. Examples: an upsert into a database keyed by (ad_id, window_start), a Redis SET of a window total, or an Elasticsearch document with a deterministic id. This is the simplest and most common approach. Downstream readers may briefly see a value that a replay later overwrites with the same value.
    • Transactional sinks use two-phase commit tied to checkpoints, via Flink's TwoPhaseCommitSinkFunction and the newer Sink V2 committer. Between checkpoints, the sink writes into an open transaction. On the barrier it pre-commits (flushes) and records the transaction id in its state. Only when the checkpoint completes does it commit. If the job fails before that, the transaction is aborted on recovery and the replay writes it again.
    • The Kafka sink with DeliveryGuarantee.EXACTLY_ONCE uses Kafka transactions this way. The FileSink does the same with in-progress, pending and finished files.

The cost of transactional exactly-once is latency and coupling to the checkpoint interval. Downstream consumers using isolation.level=read_committed see results only when the checkpoint commits. With a 60 s checkpoint interval, results appear in up to 60 s bursts. And if Kafka's transaction timeout (transaction.timeout.ms, capped by the broker's transaction.max.timeout.ms, 15 minutes by default) is shorter than the time a job can spend recovering, the broker aborts pending transactions and data is lost. Flink's producer defaults to a 1-hour timeout, so you either raise the broker limit or lower Flink's setting deliberately. Delivery-guarantee semantics in general are covered in Delivery Guarantees: At-Most, At-Least and Exactly-Once.

Checkpoints vs savepoints.

  • Checkpoints are automatic, owned by Flink, optimised for fast recovery (incremental, native format), and deleted when superseded.
  • Savepoints are manually triggered, owned by you, and portable (a canonical format, or native for speed). You use them for planned operations:
    • upgrading the job's code;
    • changing parallelism, which re-distributes key groups;
    • migrating clusters or Flink versions;
    • A/B-running two versions from the same state.

Give every stateful operator an explicit, stable uid. Savepoint state is mapped to operators by uid, and auto-generated ids change when the job graph changes, which orphans state.

When checkpointing isn't worth much

Checkpointing earns its keep when state is expensive to rebuild: a 7-day window, a join holding 24 hours of events, deduplication over the last day, a large ML feature state. For a job with 1-minute windows over a Kafka topic retained for 7 days, the state is at most a few minutes of data. On failure, you could restart from a timestamp a few minutes back and re-aggregate. With an upsert sink, the result is the same.

Proposing checkpointing reflexively in that situation misses the point. A stronger answer:

  • "With minute windows and Kafka retention, recovery is just replay. Checkpointing still gives us exact offsets and faster restarts, so I'd keep it on at a modest interval. But correctness doesn't depend on it."
  • "For multi-day windows, checkpoints are essential."

Being able to say why a feature matters in this design is exactly what interviewers probe.

Kafka sources and sinks#

Flink and Kafka are the canonical pairing. Kafka provides durable, partitioned, replayable logs. Flink provides stateful computation with exactly-once state.

KafkaSource:

  • Offsets. It reads assigned partitions and stores offsets in Flink's checkpointed state, which is the source of truth for recovery. It also commits offsets back to Kafka on checkpoint completion, but only for monitoring: consumer-lag dashboards and external tools.
  • Startup modes: earliest, latest, committed group offsets, or a specific timestamp. Starting from a timestamp is how you replay "from 09:00" after a bug fix.
  • Partition discovery: an interval setting lets it pick up partitions added while the job runs.
  • Watermarks are generated per partition inside the source, so one slow partition can't make another partition's late events look on time.
  • Parallelism: at most one useful reader per partition. Choose the topic's partition count for the processing parallelism you'll need, because it's hard to change without reshuffling keys.

KafkaSink:

  • Delivery guarantees: NONE, AT_LEAST_ONCE (flush on checkpoint) and EXACTLY_ONCE (transactions, with a transactionalIdPrefix unique per job).
  • Key the output if downstream consumers need per-key ordering.
  • Compacted topics for state. For "latest value per key" outputs, such as the current balance per account, write to a compacted topic, so consumers can rebuild the latest state.
  • The Upsert Kafka SQL connector interprets a keyed topic as a changelog: the latest value per key, with tombstones for deletes.

Patterns around the pair:

  • Kafka → Flink → OLAP. For example, to ClickHouse, Druid or Pinot for real-time analytics, or to Redis for low-latency serving.
  • CDC → Flink → search or cache. Debezium or Flink CDC streams database changes. Flink enriches and joins them, then writes denormalised documents to Elasticsearch or Redis. See Change Data Capture and the Outbox Pattern.
  • Kafka → Flink → Kafka. Multi-stage pipelines, where each stage is an independent job with its own scaling and on-call.
  • Raw events to the data lake in parallel. Kafka Connect S3 sink or Firehose archives the raw stream, and batch jobs reconcile the streaming results. More on this below.

Sample jobs#

1) A real-time dashboard on Redis

Goal: a live dashboard showing clicks and unique users per ad for the current minute and the last hour, updated every few seconds.

The job:

  1. Read the clicks topic, with event-time watermarks (bounded out-of-orderness of 10 s, idleness 1 min).
  2. Key by ad_id, and apply a 1-minute tumbling window with an early-fire trigger every 2 s of processing time. The aggregate is a count, plus an approximate distinct users count (a HyperLogLog accumulator, a few KB per window).
  3. Sink to Redis. On each firing, HSET ad:{ad_id}:m:{window_start} clicks <n> users <u> with a TTL of 2 hours. SET overwrites, so the write is idempotent: early firings, the final firing and any replay after recovery all converge on the right value.
  4. Serve. A dashboard API reads the last 60 minute-keys per ad with a Redis pipeline and pushes updates to browsers over Server-Sent Events. SSE is a good fit for one-way server-to-client push (see Realtime Communication).

This one job shows most of the core concepts: sources, event time, keyed windows, triggers, idempotent sinks, and side outputs for late data.

2) Fraud detection on card transactions

Goal: flag a transaction within about 100 ms if it looks fraudulent, so the authorisation service can decline it or trigger step-up authentication.

The job:

  1. Ingest the transactions stream (card_id, merchant, amount, country, device, ts). Key by card_id.
  2. Keep keyed state per card:
    • the last N transactions (ListState, with a TTL of 24 h);
    • a per-country count (MapState);
    • the last known location and timestamp (ValueState);
    • a running average spend.
  3. Evaluate rules in a KeyedProcessFunction:
    • Velocity: more than 5 transactions in 60 seconds.
    • Impossible travel: distance from the last location divided by the time difference exceeds 900 km/h.
    • Amount anomaly: more than 5× the 30-day average.
    • Sequences via FlinkCEP, such as "three declines followed by a success within 10 minutes", a classic card-testing pattern.
  4. Distribute rules dynamically with broadcast state. The risk team publishes rule changes to a rules topic. Flink broadcasts them to every subtask, which applies them on the next record, with no job redeploy.
  5. Enrich with async I/O: device reputation, merchant category, and an ML model score from a feature or model service. Many requests run in flight per subtask, with a timeout and fallback.
  6. Timers. "If no 3-D Secure confirmation arrives within 2 minutes of a high-risk authorisation, raise an alert." A processing-time timer per transaction is cleared when the confirmation event arrives.
  7. Sink alerts to a fraud-alerts topic, read by the authorisation service and the case-management tooling. All decisions and features go to the lake for model training.

Latency budget: Kafka about 5–10 ms, Flink processing about 1–5 ms per record, async enrichment about 10–30 ms. Comfortably under 100 ms at p99, if the job has no backpressure. Checkpoints are essential here: 24-hour per-card state across 100 M cards is tens of GB, which can't be rebuilt by replay in minutes.

3) The ad click aggregator, end to end

The Ad Click Aggregator case study is the canonical interview problem for Flink. The design moves through three stages:

  • Bad: store raw clicks in the transactional DB and run GROUP BY at query time. It collapses at 10k clicks/s and with large time ranges.

  • Good: raw clicks go to a data lake and a separate OLAP store, with a Spark batch job every few minutes or hourly. It's correct and scalable, but latency is bounded by the job schedule. Running Spark every few seconds is impractical, because each run carries startup and scheduling overhead.

  • Great: clicks → Kafka/Kinesis → Flink windowed aggregation → OLAP. Flink provides:

    • event-time windows, so out-of-order clicks land in the right minute;
    • watermarks, so windows close at the right moment;
    • managed fault-tolerant state;
    • exactly-once state.

    Compared with the batch design, the latency lever is far better: you can shrink windows or fire early to get updates every few seconds.

Then come the deep dives:

  • Scaling to 10k+ clicks/s.
    • Partition the stream by ad_id, so each Flink subtask aggregates its own ads independently. Kinesis shards cap at 1 MB/s or 1,000 records/s each, so size the shard count accordingly.
    • Scale the click service horizontally.
    • For self-managed OLAP like ClickHouse, shard by advertiser so dashboards hit one node.
  • Hot ads. A viral ad overwhelms one partition and one subtask. Salt the key (ad_id:0..N, only for known-hot ads), aggregate per salted key, and strip the suffix when writing. Upserts with SUM merge correctly, or Flink's two-phase aggregation does it automatically.
  • Not losing clicks. Kafka/Kinesis replication plus retention (for example 7 days) means a failed Flink job can replay. Checkpoints add exact resume points, which are essential for long windows and nice-to-have for minute windows (see above).
  • Reconciliation. Stream results can drift because of bugs, late data beyond allowed lateness, or bad deploys. Archive raw events to S3 (Kafka Connect S3 sink or Kinesis Firehose), run a daily Spark job that re-aggregates, compare, and correct the OLAP data. A fast streaming layer plus a correct batch layer is the Lambda architecture. The alternative, the Kappa architecture, uses only the stream, and fixes errors by replaying the retained log through a corrected job.
  • Duplicate clicks. Deduplication by impression_id (a signed, unique id per ad render) belongs before or at the start of aggregation. If you dedupe per window, a duplicate pair straddling a minute boundary is counted twice. Two solutions:
    • The reference design dedupes in the click service against a Redis set of seen impression ids (about 100 M/day × 16 B ≈ 1.6 GB) before writing to the stream.
    • Flink can also dedupe across windows with keyed state on impression_id with a 24-hour TTL, upstream of the window operator. Flink SQL offers a built-in ROW_NUMBER() ... = 1 deduplication. That trades Redis for Flink state (tens of GB in RocksDB), and keeps deduplication inside the exactly-once boundary.
    • Either works. Say which and why.
  • Low-latency queries over long ranges. Pre-aggregate minute data into hourly and daily rollups in the OLAP store (materialised views or scheduled rollups), so a "last 90 days" query reads 90 daily rows, not 129,600 minute rows.

Other common uses

  • Streaming ETL: parse, clean, enrich and route events from Kafka into the lake (Iceberg, Hudi, Delta) or a warehouse, with exactly-once file commits.
  • Real-time joins and enrichment:
    • Interval joins: match clicks to the impressions that happened within 1 hour before them.
    • Temporal joins: join orders with the exchange rate as of the order time, from a versioned table.
    • Lookup joins: enrich from a database with caching.
  • Real-time features for ML: "transactions in the last 10 minutes per user" and "average session length today", computed in Flink and written to an online feature store (Redis, Cassandra, DynamoDB). The same logic runs in batch on the lake for training data, keeping training and serving consistent.
  • Top-K and trending: sliding-window counts per item, with a per-window Top-N (a native Flink SQL pattern). See Top-K / Trending.
  • Monitoring and alerting: metric aggregation and threshold or anomaly alerts with timers ("no heartbeat in 60 s").
  • Sessionisation and user analytics: session windows over click streams.
  • Event-driven applications: stateful business logic where the "database" is Flink state, such as order state machines and IoT device twins. These are often written with ProcessFunction or Stateful Functions.

Three engines dominate stream processing, and the differences matter in interviews:

AspectApache FlinkSpark Structured StreamingKafka Streams
ModelTrue streaming: record-at-a-time, pipelined operatorsMicro-batch by default (every few hundred ms to seconds); low-latency modes are newer and narrowerRecord-at-a-time library inside your app
DeploymentIts own cluster (JobManager plus TaskManagers), on K8s or YARN, or managedSpark cluster (Databricks, EMR, K8s)No cluster: a Java library in ordinary services; scale by running more instances
Typical latencyMilliseconds to sub-secondAbout 100 ms to several secondsMilliseconds
StateHeap or RocksDB, incremental checkpoints to S3; TB-scale; key-group rescalingState store (RocksDB option), checkpointed to storageLocal RocksDB stores backed by Kafka changelog topics; standby replicas for fast failover
Exactly-onceDistributed snapshots + 2PC or idempotent sinks; any replayable sourceCheckpointed offsets + idempotent or transactional sinksKafka transactions (EOS v2); exactly-once only within Kafka (Kafka in, Kafka out)
Event timeFirst-class: per-partition watermarks, idleness, alignment, allowed lateness, side outputsWatermarks with simpler semantics (one global watermark)Stream time per partition; grace periods for windows
Sources and sinksKafka, Kinesis, Pulsar, files, CDC, JDBC, many othersVery broad (Spark ecosystem, Delta Lake)Kafka only (use Kafka Connect for others)
Parallelism limitOperators can exceed the source partition count after a shufflePartitions per micro-batchBounded by input topic partitions
Best whenLarge, stateful, low-latency pipelines; complex event time; CEP; many sourcesYou already run Spark, batch and streaming share code, seconds of latency are fine, and the lakehouse is the main sinkMicroservices that transform Kafka topics into Kafka topics; modest state; no new cluster to operate

Rules of thumb:

  • Kafka Streams for "an application that reacts to Kafka events with some state". Examples: enriching orders, maintaining a materialised view in a compacted topic, a per-customer running total. It's operationally simple, because it's just your service, but it's tied to Kafka. Repartitioning creates internal topics, and state restoration from changelogs can be slow for big state.
  • Spark Structured Streaming when the team and data platform are on Spark or Databricks, results land in Delta tables, and latency in seconds is acceptable. It's the easiest path to unify batch and streaming code on the lakehouse.
  • Flink when latency, event-time correctness, very large state, or complex windows and joins matter. Also as a shared streaming platform running many jobs, often in Flink SQL.

Other names you may meet:

  • Apache Beam: a portable API. Pipelines run on Flink, Spark or Google Cloud Dataflow, Beam's managed runner, which is the Dataflow Model's own implementation.
  • ksqlDB: SQL over Kafka Streams.
  • Streaming databases, such as Materialize and RisingWave: SQL with incrementally maintained materialised views.
  • Apache Samza, from LinkedIn: Kafka-native, YARN-based.
  • Apache Storm and Twitter's Heron: the first-generation, at-least-once engines. They're largely superseded.
  • Amazon Kinesis Data Analytics, now the managed Flink service.

When to Use It#

Use Flink when all of these hold:

  • Latency matters. Results are needed in seconds or less, and the value of the data decays fast: fraud blocking, live dashboards, alerting, real-time pricing, ride dispatch signals, real-time features.
  • The computation is stateful. It involves aggregations over windows, joins between streams, deduplication, sessions, pattern detection, or per-key state machines. These are exactly what's hard to hand-roll correctly.
  • The volume justifies a cluster. You're processing thousands to millions of events per second, or state measured in GB to TB.
  • Correctness under failure and disorder matters. Exactly-once state, event-time correctness for out-of-order mobile or IoT data, and reproducible replays.

Good signals in an interview:

  • "Count/aggregate X per Y over the last N minutes, updated in real time"
  • "detect when…"
  • "alert if…"
  • "near real-time analytics"
  • "trending"
  • "join two event streams"
  • "stream CDC into a search index with enrichment".

Pick something else instead when:

  • Minutes to hours of latency are fine. Use batch: Spark, dbt or SQL in the warehouse, or Airflow schedules. It's cheaper, easier to test, easier to backfill. See Batch vs Stream Processing and Data Pipelines, Warehouses and Lakes.
  • The processing is stateless: per-event transforms, routing, fan-out to a notification service. Plain Kafka consumers, Lambda functions, or a Kafka Connect SMT (single message transform) suffice.
  • It's Kafka in, Kafka out, with modest state, owned by an application team. Use Kafka Streams: no cluster to operate.
  • The team already lives on Spark or Databricks and seconds of latency are fine. Use Spark Structured Streaming.
  • The real need is fast queries over fresh events, not continuous computation. Write the events straight into a real-time OLAP store (ClickHouse, Druid, Pinot, which ingest from Kafka directly) and aggregate at query time or with materialised views. That's often the simpler design for analytics dashboards.

When NOT to Use It#

  • Workflow orchestration and DAGs of long tasks. Video transcoding pipelines (split, transcode each segment in parallel, generate manifests), multi-step business processes, or anything with steps lasting minutes or hours. Use a workflow engine like Temporal, Step Functions or Airflow, plus a worker pool. Flink processes continuous streams of small records. It isn't a job scheduler for long-running, heavyweight tasks with retries and human-scale timeouts. See Temporal and Workflow Engines.
  • Request/response serving. A Flink job isn't an API. Results go to a store (Redis, OLAP, a DB) that serves queries.
  • Transactional systems of record. Flink state isn't a general-purpose queryable database. (The old "queryable state" feature was deprecated.) Keep bookings, balances and orders in a database. Use Flink to derive, detect and aggregate.
  • Tiny or bursty workloads with no state, such as a few events per second. The operational overhead of the JobManager, checkpoints, savepoints and upgrades outweighs any benefit. Use a function or a consumer.
  • When the team can't operate it. Without people who understand watermarks, checkpoints, backpressure and state evolution, a Flink job becomes a fragile black box. Prefer a managed service, or a simpler architecture.

How to Implement It#

The steps to take a streaming requirement to a production Flink job:

  1. Confirm the need for streaming. Write down the latency requirement ("dashboard ≤ 5 s behind", "decline fraud within 100 ms") and the cost of being late. If batch meets it, stop here.
  2. Model the events and keys.
    • Define each event's schema: Avro or Protobuf with a schema registry, an event-time timestamp, and a unique id for dedupe.
    • Choose the Kafka partition key, usually the same as the Flink keyBy key.
    • Set the partition count for peak parallelism, for example 2–3× today's.
  3. Choose event time and the watermark strategy. Measure real lateness. Set bounded out-of-orderness at about the p99.9 lateness, add idleness handling, and decide what happens to late data (allowed lateness, a side output to S3).
  4. Design the state. List each piece of keyed state, its key cardinality, its size per key and its TTL. Estimate the total, and pick RocksDB if it's more than a few GB per TaskManager. Set maxParallelism high once (for example 1,024). Give every stateful operator a stable uid.
  5. Write the job. Use Flink SQL for windowed aggregation, joins, dedupe and Top-N. Use the DataStream API and ProcessFunction for custom logic, timers and CEP.
  6. Choose the sink semantics. Prefer idempotent upserts keyed by (key, window). Use transactional sinks (Kafka EOS, FileSink) when downstream needs exactly-once without upsert support, and size the checkpoint interval and transaction timeouts to match.
  7. Configure fault tolerance.
    • Checkpoints every 30–60 s, with incremental RocksDB checkpoints to S3.
    • A minimum pause between checkpoints and a checkpoint timeout.
    • An exponential-delay restart strategy.
    • JobManager HA through Kubernetes or ZooKeeper.
  8. Size the cluster. Run a load test at 2× peak, and watch busy time, backpressure, checkpoint duration and state growth. Leave headroom for catch-up: after an outage, the job must process the backlog faster than real time.
  9. Plan operations:
    • upgrades via savepoint, then deploy the new version, then restore, with state schema evolution (Avro or POJO rules);
    • the autoscaler;
    • alerts on consumer lag, checkpoint failures, watermark lag and restarts;
    • a replay procedure ("restart from timestamp T");
    • reconciliation against a batch recomputation for money-related outputs.
  10. Test. Run unit tests with Flink's test harnesses, using controlled watermarks and timers. Run integration tests with embedded Kafka. Do failure drills: kill TaskManagers mid-checkpoint and verify that outputs match.

A per-card velocity rule with keyed state, a TTL and a timer, as pseudo-code close to the DataStream API:

// keyBy(tx => tx.cardId) then process(new VelocityRule())
class VelocityRule extends KeyedProcessFunction<string, Txn, Alert> {
  recent!: ListState<Txn>;        // per card, auto-scoped to current key
  open(ctx: RuntimeContext) {
    this.recent = ctx.getListState("recent", { ttl: hours(24) }); // bounded state
  }
  processElement(tx: Txn, ctx: Context, out: Collector<Alert>) {
    const windowStart = tx.eventTime - 60_000;                  // last 60 s, event time
    const kept = [...this.recent.get()].filter(t => t.eventTime >= windowStart);
    kept.push(tx);
    this.recent.update(kept);
    if (kept.length > 5) out.collect({ cardId: tx.cardId, rule: "velocity", count: kept.length });
    const last = kept[kept.length - 2];
    if (last && kmBetween(last, tx) / hoursBetween(last, tx) > 900)
      out.collect({ cardId: tx.cardId, rule: "impossible-travel", count: 2 });
    // cleanup timer: if the card goes quiet, drop its state 61 s after the last txn
    ctx.timerService().registerEventTimeTimer(tx.eventTime + 61_000);
  }
  onTimer(ts: number, ctx: OnTimerContext) {
    const kept = [...this.recent.get()].filter(t => t.eventTime >= ts - 61_000);
    kept.length ? this.recent.update(kept) : this.recent.clear();
  }
}

The state is partitioned by card automatically, it's checkpointed with the job, it's bounded by both a TTL and timers, and it's computed in event time, so a replay yields the same alerts.

TechnologyFits when
Apache Flink (self-managed on K8s with the Flink Kubernetes Operator)Large stateful pipelines, strict event-time semantics, CEP, many sources and sinks, and a team able to operate it
Amazon Managed Service for Apache Flink / Confluent Cloud Flink / VervericaYou want Flink semantics without running JobManagers, upgrades and checkpoint storage; Flink SQL-first pipelines
Kafka Streams / ksqlDBKafka-to-Kafka processing inside microservices, moderate state, no extra cluster
Spark Structured Streaming (Databricks, EMR)Spark-centric data platforms, lakehouse sinks (Delta), latency of seconds acceptable
Apache Beam on Google Cloud DataflowGCP-native, autoscaling, serverless streaming with the Dataflow Model; portable pipelines
Real-time OLAP (ClickHouse, Druid, Pinot) ingesting from KafkaDashboards over fresh events where query-time aggregation is enough and no continuous computation is required
Materialize / RisingWaveSQL-defined, incrementally maintained views over streams, queried like a database
Plain Kafka consumers / AWS LambdaStateless per-event processing, low volume, simple routing

Trade-offs#

OptionProsConsPick when
Batch (Spark / warehouse SQL on a schedule)Simple, cheap, easy backfills and testing; exactLatency = schedule (minutes to hours); frequent runs carry overheadReports, hourly or daily metrics, ML training data
Hand-rolled stateful Kafka consumerNo new framework; full controlYou rebuild state recovery, rescaling, event time and exactly-once yourself; subtle bugsVery simple counters with a tolerant sink; mid-level answer
Kafka StreamsLibrary, no cluster; exactly-once within Kafka; standby replicasKafka-only I/O; parallelism tied to partitions; big-state restore from changelog is slowMicroservice-owned Kafka-to-Kafka transforms
FlinkMillisecond latency; rich event time; TB-scale state; exactly-once; SQL and CEPIts own cluster and operational skill; state evolution and upgrade disciplineLarge or critical stateful streaming; platform for many jobs
Spark Structured StreamingOne engine for batch and stream; lakehouse integrationMicro-batch latency; simpler watermark semanticsSpark shops; seconds-latency pipelines into Delta
Heap state backendFastest accessState must fit in heap; GC; full snapshotsSmall state, latency-critical
RocksDB state backendTB-scale state; incremental checkpointsPer-access serialisation; needs local SSD and tuningMost production stateful jobs
Transactional (2PC) sinkExactly-once for append-only consumersOutput visible only at checkpoint; timeout tuningKafka-to-Kafka pipelines with read_committed consumers
Idempotent upsert sinkSimple; low latency; replay-safeNeeds a key and an upsert-capable store; readers may see a value briefly rewrittenAggregates into DB, OLAP or Redis

Common Pitfalls#

  • Using processing time when the business asks for event time. Results change on replay, and backlogs land in the wrong windows.
  • Idle partitions stalling watermarks. Windows never fire on a quiet topic or partition. Configure idleness.
  • Unbounded state. Keyed state on user ids, impression ids or sessions without a TTL or cleanup timers grows until checkpoints take minutes and recovery takes hours.
  • Changing maxParallelism, or dropping operator uids, between versions. The savepoint can no longer be mapped, so state is lost or the restore fails.
  • Too few Kafka partitions. Source parallelism is capped, and you can't add consumers to catch up after an outage.
  • Hot keys. One subtask backpressures the whole job. Salt the keys, use two-phase aggregation, or handle hot keys separately.
  • Checkpoint timeouts under backpressure. Barriers queue behind buffered records, so aligned checkpoints take longer and longer, then time out. That leads to repeated restarts and more backlog. Fix the bottleneck. Use unaligned checkpoints or buffer debloating as mitigations.
  • Kafka transaction timeout shorter than the recovery time. Pending exactly-once output is aborted by the broker, and data is lost.
  • Assuming "exactly-once" covers external side effects. Calls to external APIs from inside operators (sending emails, charging cards) are re-executed on replay. Make them idempotent, or move them downstream of a committed output.
  • Deduplicating only within windows. Duplicates that straddle boundaries are double-counted. Dedupe upstream, or with keyed state plus a TTL before windowing.
  • Using per-record synchronous calls to databases from a map function. Throughput collapses to 1/latency per subtask. Use async I/O with caching.
  • No reconciliation for money-related aggregates. Silent drift goes unnoticed for weeks.

Real-World Examples#

  • Alibaba ran a large internal Flink fork (Blink) for real-time search, recommendation and business analytics, including during its Singles' Day shopping festival. It acquired Flink's original company, data Artisans, in 2019, and contributed much of Blink back upstream, especially the SQL engine.
  • Uber described AthenaX (2017), a platform that lets teams write streaming analytics in SQL, compiled to Flink jobs, for use cases like real-time marketplace metrics.
  • Netflix has described its Keystone real-time data pipeline, which routes and processes event streams at very large scale, with Flink as the stream processing engine for routing and user-defined jobs.
  • LinkedIn created Apache Samza and Kafka for its own streaming needs. That's a reminder that Flink is one of several lineages, and that Kafka-native processing (Samza, Kafka Streams) grew up alongside it.
  • Google's MillWheel (Akidau et al., VLDB 2013) and Dataflow (VLDB 2015) papers introduced the low-watermark and windowing semantics that Flink, Beam and Spark adopted. They're worth reading for the theory.
  • Cloud vendors now offer managed Flink, which signals that it's become the industry's default open-source engine for stateful streaming: AWS's Managed Service for Apache Flink, Confluent Cloud for Apache Flink, Alibaba Cloud Realtime Compute, Aiven, and others.

Case studies that use this pattern#

In the Interview#

Flink appears whenever a design needs real-time aggregation or detection over a high-volume event stream. A strong answer has three layers:

  1. Justify streaming. Name the latency requirement, and acknowledge that batch would be simpler if it were enough.
  2. Place Flink correctly. Events go into Kafka, partitioned by the aggregation key. Flink does keyed, event-time windowed aggregation. Results go to an idempotent sink (OLAP, Redis), which serves the queries.
  3. Go deeper when probed. Cover watermarks and late data, checkpoints and exactly-once, hot keys, state size, and reconciliation.

Follow-up questions to expect:

  • "What happens if a click arrives two minutes late?" It's past the watermark, so it's dropped by default. With allowed lateness, the window re-fires and the upsert sink corrects the value. Otherwise, route it to a side output for the batch reconciliation. Explain the latency and completeness dial.
  • "How does Flink guarantee exactly-once?" Barrier-based asynchronous snapshots of all state, plus source offsets. On recovery, everything is restored to the snapshot and the sources rewind. End to end, it needs a replayable source and an idempotent or two-phase-commit sink.
  • "A single ad gets 40% of the traffic. What breaks?" One subtask is overloaded, backpressure reaches the source, lag grows, and checkpoints slow down. Fix it with key salting and two-phase (local-global) aggregation.
  • "Why not just Kafka consumers with in-memory counters?" Valid for a simple mid-level answer. But you then own state recovery, rescaling, out-of-order handling and window completeness. Flink provides all of these.
Deep Dive: Checkpointing internals: barriers, alignment, unaligned checkpoints and recovery timeShow

From Chandy–Lamport to Flink. Chandy and Lamport's 1985 algorithm records a consistent global state of a distributed system. Processes send markers along every channel. Each process records its local state when it first sees a marker, and records the messages that arrive on each other channel until that channel's marker arrives (the channel state).

Flink's 2015 adaptation, asynchronous barrier snapshotting (ABS), exploits the fact that a dataflow job is a DAG with FIFO channels, fed by replayable sources. With barrier alignment, an operator never needs to record channel state:

  • It blocks each input after that input's barrier until all barriers have arrived.
  • Every in-flight record is therefore either before the snapshot (already reflected in the state) or after it (it will be replayed from the source on recovery).

The snapshot is just the operator states plus the source offsets. That's why Flink checkpoints are small compared with logging every message, and why throughput barely drops while checkpointing. The paper reported overheads of a few percent. Cycles in the graph (iterations) need extra handling: records on the back-edge are logged as channel state.

The cost of alignment. While waiting for slower inputs, an operator stops reading from the inputs that have already delivered their barrier. Under backpressure, barriers sit behind full buffers. A barrier may take tens of seconds to traverse the job, so alignment time, checkpoint duration and end-to-end latency all grow. In the worst case checkpoints time out. Recovery then has to replay from an older checkpoint, which creates more backlog and more backpressure. That's a vicious cycle.

Two mitigations were introduced:

  • Unaligned checkpoints (Flink 1.11, 2020). A barrier overtakes the buffered records. As soon as it reaches the input queue, the operator forwards it to the output immediately, jumping ahead of the output buffers too. The operator then snapshots its state plus all the in-flight buffers it jumped over, as channel state, which is a return to full Chandy–Lamport. Checkpoint duration becomes independent of backpressure (barriers cross the job in about the time of one record hop). The costs are larger checkpoints, because they include buffered data, and more I/O. You can enable them only when alignment exceeds a timeout (aligned-checkpoint-timeout), which gives aligned checkpoints when healthy and unaligned ones under pressure. They aren't compatible with every partitioning type, and rescaling from them is supported with restrictions.
  • Buffer debloating (1.14). It shrinks the amount of in-flight data automatically. Each subtask sizes its buffers so they hold about one second of throughput (configurable), instead of a fixed count. Less buffered data means faster aligned barriers and smaller unaligned checkpoints.

Incremental checkpoints with RocksDB. RocksDB is an LSM tree, so its data lives in immutable SST files. On a checkpoint, Flink flushes the memtable, hard-links the current SST files into a local checkpoint directory (the fast synchronous part), and uploads to S3 only the SST files not already uploaded by previous checkpoints, with reference counting in the shared state registry. A job with 2 TB of state that changes 20 GB between checkpoints uploads about 20 GB, not 2 TB.

The trade-off is that compaction rewrites files, so the upload size depends on compaction activity, not just on the logical change. Old checkpoints can't be deleted while newer ones still reference their files.

Changelog state backend (generic log-based incremental checkpoints, 1.15). It continuously streams state changes to a durable log (the "DSTL" on S3), and materialises full state snapshots in the background much less often. A checkpoint then only has to persist the tail of the changelog. Checkpoint duration becomes short and stable (seconds), which allows very short intervals. That matters for transactional sinks, whose output visibility is tied to the checkpoint interval. The cost is extra write I/O and storage.

Recovery time, worked out. Suppose a job has 500 GB of RocksDB state across 50 TaskManagers (10 GB each), checkpoints every 60 s, and processes 200k events/s at a steady state. After a TaskManager failure, recovery takes:

  1. Detection. The heartbeat timeout is about 50 s by default. Lowering it, or fast detection by Kubernetes, gets this to about 10–30 s.
  2. Rescheduling and acquiring a slot. A new pod takes about 30–90 s on K8s. A spare TaskManager takes seconds.
  3. State download. 10 GB from S3 at about 500 MB/s per TaskManager is about 20 s. All failed-region tasks download in parallel.
    • Local recovery (state.backend.local-recovery) keeps a secondary copy on local disk. Restarted tasks on the same machine skip the download.
    • Flink 2.0's disaggregated state avoids most of the download, because state stays in object storage, with local caching.
  4. Replay. Up to 60 s of events since the last checkpoint, plus the backlog accumulated during the 1–2 minutes of downtime, is roughly 200k × 150 s = 30 M events. At a catch-up rate of 2× normal (400k/s), catching up takes about 150 s.

So the end-to-end impact is about 4–6 minutes of elevated latency, with no lost or double-counted state. Shorter checkpoint intervals reduce replay but increase overhead. More headroom raises the catch-up speed. Recovery time is set by detection + scheduling + state restore + catch-up, and it's worth estimating explicitly for latency-critical jobs.

How two-phase commit fails, and why it's still correct. Consider a Kafka EOS sink:

  • A failure after pre-commit but before the "checkpoint complete" notification. On recovery, the restored state contains the pending transaction ids. Since checkpoint n is complete in the metadata, Flink re-commits those transactions. Committing is idempotent, so they become visible once.
  • A failure before checkpoint n completes. Recovery restores n − 1, aborts or fences transactions newer than it (producers with the same transactional id fence older epochs), and replays.

The one real hole is the external transaction timeout. If the broker aborts a prepared transaction before Flink commits it, that output is lost while the source offsets have moved on. Hence the rule: the transaction timeout must exceed the maximum checkpoint interval plus the maximum recovery time.

Deep Dive: Event time theory, streaming SQL and changelogsShow

The Dataflow Model's four questions. Akidau et al. (VLDB 2015) framed every streaming computation as four questions:

  • What is computed: the aggregation, such as a sum or a count.
  • Where in event time: the windowing, whether tumbling, sliding or sessions.
  • When in processing time are results emitted: by triggers and watermarks.
  • How do refinements relate: the accumulation mode, where a later result discards the earlier one, accumulates into it, or accumulates and retracts it.

Flink's API maps directly onto these: aggregate functions, window assigners, triggers, and the retract or upsert semantics of its SQL engine. Thinking in these four questions is the fastest way to specify a streaming requirement precisely in an interview.

Watermarks are a heuristic, not a guarantee. A perfect watermark exists only when the source knows the complete ordering, such as a single log file with ordered timestamps. Real sources give heuristic watermarks: estimates from observed timestamps (bounded out-of-orderness), or from source metadata such as Kafka partition progress and producer-side clocks. Heuristic watermarks can be:

  • Too slow: results are delayed needlessly.
  • Too fast: events are declared late that a slower watermark would have included.

MillWheel (Akidau et al., VLDB 2013) introduced the low watermark, the minimum event timestamp of pending work across the system. Flink's "minimum over inputs" propagation is the same idea. Correctness therefore always relies on a policy for late data: drop it, update the result, or reconcile in batch. That's why mature designs pair streaming with a correction path.

Clock sources matter. Event timestamps come from producers, often phones with wrong clocks. A device whose clock is 3 hours ahead pushes the per-partition max timestamp forward, so the watermark jumps ahead and every honest event becomes late. Defences:

  • Clamp timestamps to [ingest_time − X, ingest_time + small skew].
  • Use a server-assigned timestamp at the edge, combined with the client's monotonic offset.
  • Compute watermarks from the ingest-time-adjusted timestamps.

This connects to the general clock-skew problems in Time, Clocks and Ordering.

Streams and tables: the duality. Flink SQL treats a stream as a dynamic table that changes over time, and a continuous query as a computation that maintains a result table incrementally. The result table is emitted as a changelog stream. Three kinds exist:

  • Append-only, when results never change: a windowed aggregate after its window closes.
  • Retract, with insert and delete pairs, when a non-windowed GROUP BY user updates its count. Each update retracts the old row and inserts the new one.
  • Upsert, keyed updates, when the sink has a primary key.

The planner infers the changelog mode of every operator and picks the cheapest one the sink supports. This is why an upsert sink (PRIMARY KEY ... NOT ENFORCED) is so useful: an unbounded GROUP BY becomes a stream of keyed overwrites rather than retract pairs.

Join state is the silent cost.

  • Regular join (a JOIN b ON a.id = b.id over unbounded streams): Flink must keep both sides forever, because a future row on either side might match a past one. State grows without limit unless you set table.exec.state.ttl, which makes results approximate for matches older than the TTL.
  • Interval join (b.ts BETWEEN a.ts - INTERVAL '1' HOUR AND a.ts): state is bounded by the interval, and the watermark tells Flink when old rows can be dropped. Prefer it whenever the domain has a natural time bound, such as clicks within 1 h of an impression, or payments within 24 h of an order.
  • Temporal join (FOR SYSTEM_TIME AS OF o.order_time) against a versioned table, such as exchange rates or product prices from a CDC stream. It keeps the versions needed for the watermark, which gives correct point-in-time enrichment.
  • Lookup join against an external database, with async I/O and caching. No join state is kept, but it's a point-in-time processing-time lookup, so replays may see different values.

Worked example of join state. Join 50k impressions/s with clicks within 1 hour. Each impression is about 200 bytes serialised. Interval-join state is 50,000 × 3,600 × 200 B ≈ 36 GB, kept in RocksDB across, say, 24 subtasks, so about 1.5 GB each. The same join written as a regular join with no TTL grows by about 860 GB per day until the job falls over. The SQL difference is one BETWEEN clause.

Deduplication and Top-N in SQL. Flink SQL recognises two idioms and plans them specially:

  • Deduplication: ROW_NUMBER() OVER (PARTITION BY impression_id ORDER BY proctime) = 1. It keeps the first row per id, using keyed state with a TTL.
  • Top-N: ROW_NUMBER() OVER (PARTITION BY category ORDER BY clicks DESC) <= 10, over windowed or unbounded input. It maintains a sorted buffer per partition and emits updates when the ranking changes.

Each is a few lines of SQL. Hand-rolling either correctly with state, retractions and recovery is a multi-week project. That gap is a large part of why Flink SQL became the default interface for many streaming platforms.

Deep Dive: Operating Flink at scale: sizing, rescaling, memory and state evolutionShow

Capacity estimate, worked. An ad-click job takes 100k events/s at peak, each about 500 bytes in Avro.

  1. Ingest bandwidth: 50 MB/s.
  2. Throughput per core: a simple keyed window aggregation on RocksDB handles about 10k–50k events/s per core. The cost is dominated by deserialisation, state access and serialisation. With a conservative 15k/s per core, the job needs about 7 cores at steady state.
  3. Catch-up headroom: after a 10-minute outage, the backlog is 60 M events. To clear it within 10 minutes while live traffic continues, the job must process 200k/s, or about 14 cores.
  4. Deployment: round to parallelism 16, on 4 TaskManagers × 4 slots (4 vCPU and 16 GB each). The Kafka topic needs at least 16 partitions. Choose 32 for future growth, and set maxParallelism to 512.
  5. State: a 24-hour dedupe on impression ids is about 100k/s × 86,400 s × about 60 B per entry ≈ 520 GB. That's the dominant sizing factor, far more than the counting. It argues for deduplicating in the click service against Redis (16 B ids, compact sets), or for a Bloom-filter-based approximate dedupe if exactness isn't required. This is a typical moment where state arithmetic changes the architecture.

The memory model. A TaskManager's memory has four parts:

  • JVM heap: user objects, and heap state with the HashMap backend.
  • Managed memory, off-heap: RocksDB block cache and write buffers, and batch sort buffers. It's sized by taskmanager.memory.managed.fraction, 0.4 by default.
  • Network memory: the network buffers.
  • JVM overhead and metaspace.

The common failure is RocksDB using more native memory than budgeted, which gets the container OOM-killed by Kubernetes. Flink bounds RocksDB to managed memory by default (state.backend.rocksdb.memory.managed: true). Keep it that way unless you know why not. Other RocksDB tuning:

  • predefined options for SSD;
  • the block cache size;
  • Bloom filters for point lookups;
  • the compaction style;
  • a limit on the number of column families, one per state descriptor.

Rescaling.

  • Manual: take a savepoint, then restart with a new parallelism. Key groups are reassigned, and operator state (Kafka offsets) is redistributed.
  • Reactive mode (1.13+, standalone and application mode): the job uses all available TaskManagers automatically. Add pods and the job scales up; remove them and it scales down. It pairs with Kubernetes HPA (Horizontal Pod Autoscaler).
  • The adaptive scheduler and the Flink Kubernetes Operator autoscaler. These compute per-vertex parallelism from observed busy time and target utilisation, and rescale with minimal downtime. They respect the limit set by the source partitions.

Rescaling costs a restart, and a state redistribution for RocksDB, since each new subtask must download the SST files for its key-group range. Flink 2.0's disaggregated state removes most of that cost. That's a big reason it was built.

State evolution and upgrades. Long-running jobs live through many code versions, so plan for these changes:

  • Changing a state's schema. POJO and Avro state types support adding and removing fields. Kryo-serialised state (the generic fallback) doesn't evolve safely. Register types, or use Avro or Protobuf for state.
  • Renaming or reordering operators. That's safe if their uids stay the same.
  • Removing a stateful operator. Allowed with --allowNonRestoredState.
  • Changing key types or maxParallelism. Not possible in place. Use the State Processor API to read a savepoint as a dataset, transform it, and write a new savepoint. Or bootstrap new state from batch data. The same API can bootstrap a job's state from historical data in the lake, so a new fraud job starts with 30 days of per-card history on day one.

Upgrade procedures for a critical job:

  1. Stop with savepoint (flink stop --savepointPath), which also drains in-flight data and commits transactions.
  2. Deploy the new version from the savepoint.
  3. Verify output metrics against the previous version.

For zero-downtime changes to outputs, run blue-green: start v2 from the same savepoint, writing to a new sink or topic, compare it with v1, then switch consumers.

Observability for streaming. The metrics that matter:

  • Consumer lag, in records and in seconds. Seconds is the user-facing freshness.
  • Watermark lag: now minus the current watermark, per operator.
  • Checkpoint metrics: duration, size, alignment time, and failures.
  • Busy and backpressured time per vertex.
  • Restart count and the uptime since the last restart.
  • State size growth: a slow leak shows up here first.
  • Late-records-dropped counters.

Alert on symptoms: freshness over the SLO, checkpoints failing N times in a row, restarts in a loop. General practice is in Observability.

Multi-tenancy and platforms. Companies running hundreds of Flink jobs usually standardise on:

  • application-mode clusters per job, for isolation;
  • Flink SQL as the user interface;
  • a central platform team that owns the Kubernetes operator, the connectors, checkpoint storage and upgrade tooling;
  • per-job resource quotas;
  • shared Kafka with schema registry enforcement.

This platform shape is the one described in public talks by companies like Uber (AthenaX) and Netflix (Keystone). It's also why managed Flink services have grown. The engine is powerful, but operating many stateful jobs is where the real work lies.

Lessons that generalise beyond Flink:

  • Co-locate state with computation, partitioned by key.
  • Make snapshots consistent without stopping the world, using barriers and immutable files.
  • Separate event time from processing time, and make completeness an explicit, tunable policy.
  • Make sinks idempotent wherever you can.
  • Pair a fast approximate path with a slow exact path when the numbers involve money.

Key Takeaways#

  • Flink runs stateful dataflow jobs. Operators are split into parallel subtasks in TaskManager slots, coordinated by a JobManager. keyBy routes each key to one subtask, using key groups that make rescaling possible.
  • State is managed and fault-tolerant. Use keyed state (Value, List, Map) with TTLs. Use the heap backend for small state and RocksDB for large state, with incremental checkpoints to S3.
  • Checkpoints use barrier-based asynchronous snapshots. Recovery restores the state and rewinds the sources, which gives exactly-once state. End-to-end exactly-once needs a replayable source plus an idempotent (upsert) or two-phase-commit sink. Prefer upserts.
  • Event time with watermarks puts out-of-order events in the right window. The out-of-orderness bound trades latency for completeness. Handle late data explicitly, with allowed lateness, side outputs or batch reconciliation.
  • Know the window types and their state cost. Tumbling windows are cheapest, sliding windows multiply state, and session windows merge. Triggers and early firing give fresh partial results. Interval joins bound join state, while regular joins grow forever.
  • Choose deliberately:
    • batch, if the latency allows;
    • Kafka Streams for Kafka-to-Kafka microservice logic;
    • Spark Structured Streaming in Spark shops with seconds of latency;
    • Flink for large, low-latency, event-time-correct stateful pipelines;
    • always Kafka (partitioned by the key) as the replayable input.