Ch.79: Flink System Design: Turn Events Into Live Answers

Outline

Transcript

0:00 Apache Flink processes streams, flows of data arriving over time, to update results like a factory's energy totals while saving enough progress to recover from a computer failure. We'll design how it spreads that work across computers, recovers the right total after a crash, and publishes a result without counting the same update twice. Suppose the display shows 26 watt-hours of energy when one computer fails. If the input readings survive, why isn't processing them again enough? Because restarting partway through the readings needs the total already calculated and the exact place we stopped reading.

0:35 Follow a reading from machine M along the main route: keep the reading, update M's total, then publish that answer. So the display reads published results, not the working calculation itself. Can a reading be accepted before its effect becomes visible? Yes. An accepted reading can still be waiting to affect the display. Then a replacement must finish the accepted work and handle the next readings too. So the service must accept distinct increments, route them by machine, update each running total and publish an answer the display can request. That's its required work, the functional requirements.

1:10 It must also recover after a computer fails and redistribute existing totals when we add computers. Giving each new one an empty counter would change the answer. For instance, M's replacement needs its existing total before processing the next reading. While that worker is recovering, the caller may still see an older total. Show when the database first made that result visible; that time doesn't prove every earlier reading has been counted. And a crash doesn't stop new readings arriving. What limits do we need to design for while recovery catches up?

1:44 And those readings keep coming during recovery. We need limits and guarantees on that work, our non-functional requirements: keep up with arrivals, limit waiting space, preserve progress we can recover, and verify senders. Suppose 10,000 events arrive each second, each carrying 200 bytes of content. That leaves out the extra data used to move or copy those records. The arithmetic describes incoming content. The saved input positions determine where we start again; those figures don't tell us how many records recovery must read or how long recovery takes. First, give each machine one working total.

2:20 State is the information retained between events, such as M's accumulated value. A worker program runs tasks, separate copies of a processing step. If M's next reading reaches a different computer, how does it find the task holding M's total? The machine identifier is the key. Flink sends matching records to the task that already holds M's state. That's keyed processing. Our retained input history is a log, divided into ordered pieces called partitions. A piece can contain several machines, so input placement alone doesn't provide that ownership.

2:54 The network exchange, a record-routing step, sends each reading from those input partitions to the task responsible for its key. The workers can compute different machine totals at the same time. Flink's stateful-processing guide keeps each key's records and state together. We update the total inside its owning task, rather than calling a database for every increment. The guide is linked in the description. My first thought was to rely on keeping updates inside one worker, but that doesn't make the total survive its loss.

3:23 What exactly does Flink save for recovery? It saves managed state, the values Flink tracks for recovery, together with the input positions. The worker's temporary copy alone can't tell its replacement where to resume. Now test why we save those two pieces together. Replaying means processing retained records again. The log remembers those inputs while the worker remembers their contributions, so recovery must restore a total and input positions covering the same records. We could keep the full log and start reading from the beginning after a crash.

3:56 What does saving a total buy us? We could, if we retain the full history and can afford to recompute it. A checkpoint is a saved restart point: an intermediate total with its input positions, so we can continue instead of starting over. But a saved total alone still leaves the replacement guessing which records it includes. Where would it restart reading? At the next record not already counted, separately for each input. Starting too early repeats contributions; too late skips them. Let's test a total alongside its next records.

4:30 Now apply that pairing to machine M's two ordered inputs, L and R. 4 distinct records add 5, 7, 3 and 11 watt-hours. Checkpoint C includes L's 5 and 7, plus R's 3, so its saved total is 15. Which record on each input must recovery read next? L index 2 and R index 1. R's 11 hasn't contributed to this saved total. Exactly, and those indexes are our teaching notation, not a promise about how an input reader encodes its saved position. So 15 and those 2 positions are one recoverable package. How do the two moving inputs agree on which records belong in it?

5:11 Now build that checkpoint across moving inputs. Flink sends checkpoint barriers, markers separating the covered records from later ones, along the connections between tasks, or channels. For an aligned checkpoint, a task holds back input beyond an early barrier until its other input barriers arrive. Suppose L reaches its barrier while R's earlier 3 is still waiting. What does the task process next? It holds back L's later records, consumes R's queued reading and then receives R's barrier. We can now capture 15 without including L's newer work.

5:44 Right, both inputs now agree on what the saved total includes. Does every machine have to stop at exactly the same instant? No. Each task captures a snapshot, a saved copy of its relevant state, and those copies can be written to recovery storage while the tasks keep processing. The coordinator, the program organizing this checkpoint, declares completion only after all required tasks confirm successful storage. So we agree on a boundary in the records, rather than one instant shared by every computer.

6:15 Now suppose a worker processes R's 11 after checkpoint C. Its total rises from 15 to 26 before it crashes; restoring 15 and replaying that 11 gives 26 again. Hold on, if we keep the newer 26 but restart reading at the old R position, we get 37. Recovery has invented 11 extra watt-hours. Yeah, and the opposite mismatch is quieter: restore 15 with the newer position, skip 11, and we report a perfectly plausible 15. Both wrong totals look like answers. Flink's guide to handling failures allows processing to run again after recovery; the test is whether each distinct record contributes once to the restored total.

6:59 For distinct records, yes. Two records might describe one real measurement, and recognizing that duplicate is a separate problem. Correct replay doesn't identify it for us. But the recovered total still has to reach the display. The sink is our output-writing task. It groups writes in a transaction, a group that the database makes visible together when committed. Later checkpoint D records 26 and the information needed to finish that publication. Suppose the sink crashes after D completes. Its saved publication hasn't committed, so the app returns 15.

7:32 What does recovery do? It restores D's total and its unfinished publication. Readers keep the old answer until the compatible sink finishes that saved commit. That completed write makes 26 readable, with its first-publication time. So that first crash delays publication without discarding it. What if 26 was already visible, but the confirmation reply was lost? It retries that same commit, leaving 26 unchanged. Flink's sink contract requires idempotent commits: repeating a completed commit has the same effect.

8:03 The connector, the code joining Flink to the database, and the database itself must support that recovery. Suppose instead we increment a database counter whenever the processing code runs. Replay could add 11 twice. An email sent there also needs its own delivery design, because restoring saved state can't unsend it. For that end-to-end promise, from retained input to visible answer, the input readers must let us return to earlier records and output must be transactional or idempotent. We still check the calculation, whether its publication can recover, and what the app can actually read.

8:39 But publishing correct values doesn't ensure prompt updates. When a slow sink fills the buffers, temporary holding areas for records, earlier tasks must slow down too. Flink calls that backpressure. The input log can retain readings still waiting to be processed, but the display gets older. The checkpoint markers may also take longer to reach every task. Right, snapshot delays and stale answers can therefore come from the same restriction at the output. Adding more input workers won't make the database accept writes faster.

9:10 More workers, same waiting room. Can we complete a checkpoint without waiting for all the queued input to be processed first? So we can preserve the waiting records inside the checkpoint too. Flink engineers Arvid Heise and Stephan Ewen described this unaligned-checkpoint design in 2020. Try our same records: L has contributed 12, while R's 3 is in the channel buffer. What should that saved package contain? The 12, the buffered 3, and where to resume reading each input. Restore the state and process that captured record first, giving 15; the later 11 then brings the result to 26.

9:45 Ah, we've preserved work that was still waiting, rather than pretending it was already included. In the aligned case we'd process that 3 first and save 15. Exactly. These are teaching records, not a connector's storage format. Capturing waiting data can reduce time spent lining up input barriers, but it adds data to save and restore. My instinct was to call that a faster checkpoint, but the database stays slow and Flink still can't interrupt one long record-processing operation. There isn't a universal faster button.

10:18 We'd compare the time waiting for barriers with checkpoint size and recovery work. If writing the snapshot already limits progress, saving extra channel data can make that worse. Now use recovery to move M's total to a different worker. Flink collects keyed state into movable units called key groups. For example, group 2 holds M's 26 watt-hours. As we move from 2 workers to 4, what must happen before the next reading from M can change that total? Restoration loads 26 into the group's new owner, and the routing sends M's events there so the calculation carries on from its saved value.

10:54 So adding workers involves state transfer, actually moving saved values, as well as starting more processing tasks. The input reader must resume at positions consistent with those restored values. Yes. Moving the work doesn't change that agreement. Different groups can spread across workers, but one key still belongs to one owner. That owner creates a limit. If one machine generates most events, its single keyed task can stay overloaded while other workers sit idle. So we could pay for 4 workers and still leave M waiting.

11:27 We can sometimes have separate tasks sum different portions of the input, then add those totals. We have to design those steps; extra workers don't invent that second calculation for us. And the extra stages move more records and saved state between computers, with more checkpoint work. We'd inspect which machine identifiers dominate the input before treating the overall event rate as the whole problem. Before trusting this design in a running service, enable checkpointing at regular intervals; Flink leaves it disabled by default.

11:57 Keep the saved progress somewhere that survives the worker, set how long input stays available, make publication recoverable, and test a restore. The display's answer stays old while readings keep arriving. What would you check first? I'd first check whether processing is falling behind arrivals. If it is, I'd check the age and failures of checkpoints too; a blocked output could explain both delays. How would we tell that from slow recovery storage? Separate the wait for matching input markers from the time spent writing saved data.

12:27 Slow output can hold back the markers; slow storage lengthens the writes. We'd test those possibilities, not diagnose from one reading. Recovery still follows saved record positions, not the times measurements happened. Now follow the opening map again: retained events feed the per-machine tasks, and the checkpoint records their totals alongside each input's next record. The coordinator uses the recovery store to restart those calculations. The sink completes or safely retries a recorded publication, so the separate read interface exposes a committed result.

13:00 If the log survives but the restored answer is wrong, the service hasn't recovered. We need the right saved total, the right remaining records and a completed publication. Once those pieces agree, 26 survives the crash as the published answer. Thanks for listening to Learning Podcasts.