CComputer Science, Built

Act IX · Systems at Scale

Part 46 of 61

Logs, Streams and Warehouses

Degreestarts at this level52 min of film16 chaptersprerequisites: Part 20, Part 35, Part 39, Part 43

How do you compute answers over data that never stops arriving, and arrives late, out of order and twice?

The part opens with the log, the structure the series keeps meeting as the write-ahead log, the Raft log, git's history and the outbox: four sources and four consumers need sixteen pipelines pairwise and eight connections through a log. Kafka's partitioned log keeps order per key, shares partitions among a consumer group, and compacts 2,000 updates to the 50 records that rebuild the same state. Change data capture turns a database's own log into a stream, and state becomes a fold over events. The part turns on time. Events carry the time they happened and arrive when they arrive; windows are cut in event time, and a watermark guesses when a window is complete. On 3,000 events, no lag drops 530 of them and a minute's lag drops one but answers 65 seconds late, while allowed lateness keeps the early answer and refines it. Barrier snapshots make a crashed counter's state exact, and sketches bound the memory of top-k, distinct counts and quantiles. The second half is the warehouse: star schemas, Parquet's encodings measured on the novels' words, Dremel's repetition and definition levels, tables on object storage, and joins across a hundred workers. The Job ends as a live top twenty over thirty novels, equal to the batch answer exactly once.

What you need. SQL at the level of a join and a GROUP BY; the exponential distribution for the delay model.

Mathematics, ideas and history
the partitioned log, CDC and event sourcing, the dataflow model (windows, watermarks), exactly-once checkpoints, star schemas, Parquet and Dremel levels, lakehouses, MPP joins
What we build or compute
the Job as a live stream

What you will be able to do

Degree

  • Explain how keys, partitions and offsets give order per key and let each consumer read at its own pace.
  • Assign events to tumbling, sliding and session windows by event time, and say what a watermark claims.
  • Encode a small column with a dictionary, run lengths and deltas, and say why sorting helps.

Graduate

  • Trade completeness against latency with a watermark's lag, and use allowed lateness and refinements to escape the trade.
  • Explain how barrier snapshots give exactly-once state, and why the guarantee is end to end.
  • Compute Dremel's repetition and definition levels for a nested column and rebuild the records from them.

Research

  • Explain what incremental view maintenance by differential dataflow and DBSP computes, and at what cost in state.
  • State the space lower bounds for streaming summaries and where KLL sits against them.

Industry

  • Choose between a broadcast and a shuffle join from the table sizes, and repair a skewed key by salting.
  • Size batches, partitions and retention for a throughput target on sequential storage.
  • Write data tests and a contract for a stream with duplicates and late arrivals.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 23 min · Graduate 50 min · Research 52 min · Industry 33 min.

  1. 0The logDegree2 min
  2. 1The partitioned logDegree4 min
  3. 2Moving a gigabyte a secondIndustry4 min
  4. 3Changes as eventsDegree3 min
  5. 4Event time and processing timeDegree4 min
  6. 5Exactly-once stateGraduate4 min
  7. 6Streaming algorithms in productionGraduate4 min
  8. 7The warehouseDegree3 min
  9. 8Columnar filesDegree4 min
  10. 9Nested data in columnsGraduate4 min
  11. 10Tables on object storageIndustry3 min
  12. 11Queries on a thousand machinesGraduate3 min
  13. 12Data you can trustIndustry3 min
  14. 13The Job as a streamGraduate2 min
  15. 14Frontier: streams, tables and their limitsResearch2 min
  16. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

The logDegree2 min

A log, in the sense of this part, is the simplest data structure that remembers time: records appended one after another, each with a number, its offset, and never changed. We have met it again and again. A database writes every change to a log before it touches the data. Raft agrees on a log, and every replica applies it in order. Git's history is a log of snapshots. The outbox of Part 43 is a log of events. In 2013 Jay Kreps, who had built LinkedIn's data infrastructure, argued that the log is the unifying abstraction of real-time data: the right way to move data between all of a company's systems.

Here is the argument. A company has sources of data, databases and streams of clicks, and systems that need them: a search index, a cache, a warehouse, a fraud model. Connect each source to each consumer directly and you build sixteen pipelines, each with its own format and its own failures. Put a log in the middle instead. Every source appends to it, and every consumer reads from it: eight connections. Each consumer keeps its own position, reads at its own pace, and can go back and replay history. A new consumer starts at the beginning and catches up.

So every company's data ends up in two places. An append-only log, recording everything as it happens. A column-oriented warehouse, laid out to answer questions about all of it at once. And between them, stream processors that compute answers continuously, as the data flows. The hard part, we will see, is time: events arrive late, out of order, and more than once, and a correct answer has to survive all three.

1The partitioned logDegree4 min

Kafka was built at LinkedIn by Jay Kreps, Neha Narkhede and Jun Rao, and described in 2011. A topic, a named stream such as page views, is split into partitions, and each partition is a log: records appended at the end, numbered by offset, and never changed. On disk a partition is a run of segment files, each named by its first offset, with a sparse index into it. Only the last segment is written; by default a new one starts every gigabyte. A consumer's whole state is one number per partition, the next offset to read, which it commits back to the broker and resumes from after a crash.

Which partition does a record go to? The producer hashes the record's key. Here the keys are words, hashed with CRC thirty-two into four partitions. Every record with the same key lands in the same partition, so one key's records keep their order, and our simulator checks this for every key. Order per key is Kafka's guarantee, and usually what an application needs: all the changes to one customer, in order. Across partitions there is no order at all. And hot keys make hot partitions: the common words fill two partitions, while another holds a single ship.

Readers share the work through a consumer group. Each partition is read by exactly one member, so a group can grow to as many members as there are partitions, and another group reads the same log independently. Here three members hold four partitions each. A fourth member joins, and the group rebalances. Range assignment recuts four contiguous runs and moves six partitions. A sticky assignor moves only three, the fewest possible, since the newcomer needs three. Then member two leaves: range moves four partitions, sticky just the three that member two owned. Each moved partition pauses while its new owner resumes from the committed offset.

A log cannot grow for ever, and there are two ways to forget. By time: whole segments older than the retention period, seven days by default, are deleted, and the start offset moves forward. Deleting a file is cheap, which is one reason segments exist. By key: a compacted topic keeps only the latest record for each key, at its original offset, and a record with an empty value, a tombstone, deletes its key. What remains is the latest state, and it is enough: in our simulator, two thousand updates to fifty keys compact to fifty records, which rebuild exactly the same table.

Finally, a partition must survive losing a machine, so it is replicated. One broker leads each partition and takes every write; followers fetch from it as consumers do. A record is committed, and shown to consumers, once every replica in the in-sync set has it; that point is the high watermark. A follower that falls behind is dropped from the set, so one slow disk cannot stall the topic, and the watermark moves on. With acknowledgements from all and at least two in sync, every acknowledged write has two copies. This is Part 39's single-leader replication, not Raft's majority: f plus one replicas survive f failures, and a controller, itself now a Raft log, picks new leaders only from the in-sync set.

2Moving a gigabyte a secondIndustry4 min

Why a gigabyte a second? It is roughly what a ten-gigabit network link carries. In the Kafka paper's experiments a message was two hundred bytes, so a gigabyte a second means five million messages, two hundred nanoseconds each. Set that budget beside Part 34's storage model: one random read from flash costs four hundred budgets, and one from a spinning disk sixty-five thousand. So no single message may wait for anything: not a seek, not a round trip, not even a system call of its own. Everything that follows pays for many messages at once.

The first answer is Part 34's rule: write in long runs. A log does nothing else. The producer only appends, and each consumer only reads forward from its offset, so the disk sees long sequential runs, and the kernel's read-ahead fetches pages before anyone asks for them. On Part 34's model disk that is a hundred and fifty megabytes a second, against a third of one. There is no index to maintain either, so an append costs the same with a week of data as with none. And partitions on different disks and brokers add their bandwidth together: seven such disks make a gigabyte a second.

The second answer: never send one message alone. The producer collects messages for a partition into a batch and sends the batch in one request. The broker appends it exactly as it arrived, and consumers fetch it the same way. Every request has a fixed overhead, and a batch divides it among all its messages. In the Kafka paper, one producer sent fifty thousand messages a second one at a time, and four hundred thousand in batches of fifty. The price is a few milliseconds of latency while a batch fills. And a batch compresses far better than single messages, because neighbouring records repeat each other's fields.

The third answer is to stop touching the bytes. Served the obvious way, data is copied from disk into the kernel's page cache, then into the program's buffer, back into the kernel's socket buffer, and out to the network card: four copies and two system calls, as the Kafka paper counts them. The sendfile call asks the kernel to pass the file's pages straight to a socket, and the middle two copies, and one system call, disappear. This works only because the broker never looks inside a message: the bytes on disk are the bytes the producer sent and the consumer receives. Encrypting in the program, as TLS does, gives zero-copy up.

The last answer is to let the operating system do the caching. Kafka writes every batch to the file system and keeps no cache of its own. The kernel's page cache holds the recent tail, so a consumer that keeps up reads from memory, and the disk is never asked. A consumer replaying yesterday reads from disk, but sequentially. There is no second copy in the program's heap, no garbage collector sweeping millions of messages, and the cache stays warm when the broker restarts. Durability comes from the replicas of chapter one, not from forcing each write to disk. Together, these choices let Jay Kreps report in 2014 two million writes a second on three ordinary machines.

3Changes as eventsDegree3 min

A company's data lives first in databases, and other systems need copies of it: a search index, a cache, the warehouse. The tempting design is a dual write: the application writes the database, then the index. If it crashes between the two, the database says twelve and the index says ten, for ever, with no error anywhere. Worse, two writers can race, and the two systems apply their writes in opposite orders. The cure is to write once, to the database, and derive every other copy from the one authoritative order: the order in which the database committed.

And the database already writes that order down. Every committed change goes first into its write-ahead log, from Part 35. Change data capture reads that log and publishes each change as an event. An update, an insert and a delete become three events in a topic keyed by the row's id, so each row's changes stay in order, as in chapter one. An event carries the row before and after, and its position in the log. PostgreSQL exposes its log through logical decoding, MySQL through its binary log, and Debezium turns both into streams. To begin, the connector snapshots the table, then follows the log from exactly the position the snapshot saw.

Raw change capture has one drawback: it publishes the database's internal tables, and every reader comes to depend on their columns. Part 43's outbox fixes that. In the transaction that marks order forty-two as paid, the service also inserts a row into an outbox table, describing the event. Both commit, or neither does. Change data capture follows only the outbox, and publishes its rows to a topic. The event is a designed contract, order paid, not a copy of a table, and the table can now change shape freely. Delivery is still at least once: a connector that crashes before recording its position publishes again, so readers drop duplicates by the event's identifier.

Now turn the picture around. If every change is an event, the current state is a summary of the events so far. An account is opened, fifty is deposited, twenty withdrawn, ten deposited, and the balance runs zero, fifty, thirty, forty. The state is a fold: an apply function run over the events, starting from empty. The same events always give the same state. So streams and tables are two views of one thing. Folding a stream of changes gives a table; recording each change to a table gives a stream. Chapter one's compacted topic is exactly this: two thousand updates folded into fifty rows.

4Event time and processing timeDegree4 min

Every event in a stream carries two times. Its event time is when it happened, stamped by the phone that recorded the click. Its processing time is when the pipeline sees it, which is always later: a network delay, a queue, or a phone in a tunnel. Plot each event at its event time across and its arrival upwards. Here are 120 simulated events, 2 a second, appearing as the processing clock runs. With no delay they would lie on the diagonal; most land a little above it, the slowest about 18 seconds late. So a pipeline counting one minute's clicks cannot tell from its own clock when that minute's events have all arrived.

The Dataflow model of Tyler Akidau and his colleagues at Google, in 2015, first asks where in event time a result belongs. Tumbling windows cut time into fixed pieces, here 10 seconds, so every event falls in exactly one. Sliding windows have a size and a step, 10 seconds every 5, so each event belongs to two. Session windows are found in the data: one user's run of activity, ended by a gap of 4 seconds, so a late event can merge two sessions into one. All three are defined in event time: the answer depends on what happened, not on when the pipeline heard.

The second question is when, in processing time, a result can be given. A watermark is the pipeline's running claim that no older event is still on its way. With complete knowledge of the sources it can be exact; usually it is a guess. Ours is the largest event time seen so far, minus 3 seconds, climbing as a staircase behind the events. 11 of the 120 events arrive behind it: they are late. The window of the first ten seconds closes when the watermark passes ten, at about 13 seconds, with 19 of its 20 events. The last arrives 1.7 seconds later, and the answer already given is wrong.

How long should the watermark wait? We sent 3,000 simulated events through ten-second windows. With no lag, answers come 2 seconds after a window ends, and 530 events are dropped as too late. Waiting five seconds drops 182. Waiting a minute drops just 1, and 29 of the 30 windows are exact, but every answer is more than a minute late. The way out: answer at five seconds, keep each window's state a minute longer, and correct it whenever a late event arrives. Every window ends exact, and first answers come as quickly as before.

The last two questions are when to emit and how successive answers relate. A trigger decides when a window's result goes out: early, as a speculative answer; on time, when the watermark passes; and late, once for each late event. Accumulation decides what each firing means. Discarding mode emits only what is new. Accumulating mode emits the whole window each time: five, then nine, then ten. With retractions, each firing also withdraws the previous answer, so a consumer summing across windows counts nothing twice. Our run with a minute of allowed lateness fired 183 refinements. What, where, when and how: the Dataflow model asks these four questions of every pipeline.

5Exactly-once stateGraduate4 min

A stream processor keeps state: running counts, open windows, the buffers of a join. The state is partitioned by key, like the log it reads, so every key's count lives on exactly one worker, and each event updates it as it passes. Then a worker crashes, and its state is gone. The log still holds every event. The question is where to resume. Replay from too late, and events are missed; from too early, and they are counted twice.

Paris Carbone and his colleagues gave Apache Flink its answer in 2015, a descendant of Chandy and Lamport's snapshots from Part 38. Records flow from two sources, through two keyed counters, to a sink. To take a checkpoint, each source records its offset and injects a barrier, a marker that travels with the records. A counter with two inputs waits until the barrier has arrived on both, holding back the input that delivered it first, so that its state reflects every event before the barrier and none after. That is alignment. Then it copies its state to storage, in the background, and passes the barrier on. When the sink has every barrier, the checkpoint is complete: offsets and states that describe one consistent cut through the computation. With no cycles and aligned barriers, no records in flight need saving.

We crashed our keyed counter on purpose. 3,032 events, three workers, and checkpoints taken as the stream runs. At offset 1,700, every worker loses its state. Recovery loads the last complete checkpoint, from offset 1,500, and rewinds the source to the same place. 200 events are processed a second time. But they meet the state as it was before they first arrived, and the final counts equal those of a run that never failed. Rewind the source but keep the counts as they stood at the crash, and those 200 events are counted twice: that is at-least-once. Skip the replay, and they are lost: at-most-once. Exactly-once means state and position restored together.

Inside, the state is now exact; outside, some results may have been seen twice. One fix is an idempotent sink. Each result is written as an upsert, keyed by its window and key, so writing the same answer again leaves the table unchanged. The other is a transactional sink. Everything written since the last checkpoint goes into an open transaction that readers cannot see; when the checkpoint completes, it commits. After a crash the open transaction is aborted and its records are written again, so readers see each one once. This is two-phase commit from Part 39, with the checkpoint as coordinator; Kafka gained the transactions it needs in 2017.

So exactly-once is never the property of one component. It needs a source that can be rewound to an offset, which is why logs sit at the front of these pipelines; state checkpointed together with those offsets; and a sink that is idempotent or transactional. Remove any one and the guarantee falls: a source that cannot rewind loses events, and a sink that sends an email sends it twice. Even then, events may be processed more than once; what is exact is their effect. It is the end-to-end argument of Saltzer, Reed and Clark, from Part 36: a guarantee can only be made at the ends.

6Streaming algorithms in productionGraduate4 min

The first question asked of a stream is often what is most frequent. Part 20's Misra and Gries summary answers it in one pass, here with 99 counters over 4.6 million words. Every count it reports is low, but by at most the number of words divided by 100, about 46 thousand, so the true count lies in the dashed box above each estimate, and any word more frequent than that is certain to be kept. In production what matters is that such summaries merge: each worker summarizes its own partition of each window, and the summaries combine with the same guarantee, as Pankaj Agarwal and his colleagues proved in 2012.

Counting distinct items exactly needs memory for every item. HyperLogLog, from Part 20, keeps only small registers, each holding the longest run of leading zeros among the hashes that land in it. On the corpus's 57,895 distinct words, its error falls from about a quarter with 12 bytes to under one per cent with twelve kilobytes. Three kilobytes put the vocabulary within a fifth of a per cent, and count four and a half million distinct five-word phrases as well. Two sketches merge by keeping the larger register in each place, so hourly counts of distinct users roll up into daily ones. Warehouses store such sketches in tables, as BigQuery's HyperLogLog functions do.

Latency is judged by its median and its ninety-ninth percentile. A KLL sketch, by Zohar Karnin, Kevin Lang and Edo Liberty, keeps levels of samples, each level's items standing for twice as many values as the level below. Over 200,000 simulated latencies, keeping 95 items, its median is close. But at the far tail its ninety-nine point nine percentile is 164 against a true 427: less than one per cent wrong in rank, yet more than twice too low in value. Ted Dunning and Otmar Ertl's t-digest attacks the tail directly, with clusters that are large near the median and tiny near the extremes. KLL guarantees rank; t-digest is accurate where latency questions are asked.

Joining two streams is harder than joining two tables, because neither side is ever complete. Here orders and payments are joined on the order number, and a payment counts if it comes within ten minutes of its order. Each order is kept as state while a payment could still arrive. Once the watermark passes ten minutes after it, the order leaves the state, joined, or in an outer join emitted alone. A payment that comes after that finds nothing. So the state is the event rate times the window. A join of a stream with a table, kept current from its change log as in chapter three, holds the table instead.

These sketches share the property that matters most in production. Each can be built separately on every partition and every window, and two of them combine into one with the same guarantee: add the counters, keep the larger register, compact the combined samples. So a thousand workers each sketch their share, a tree of merges produces the answer, and the warehouse can store a sketch per hour and roll it up per day or per year. The warehouse is where chapter seven goes next.

7The warehouseDegree3 min

First, an argument about architecture. In 2011 Nathan Marz proposed what became the Lambda architecture: recompute every answer from the whole log in a batch job, and, because the batch is hours behind, run a stream job alongside for the recent part, merging the two at query time. Every answer is written twice, in two systems that must agree. In 2014 Jay Kreps asked why not once. In his Kappa architecture there is only the stream job. To change it, start a second version reading the log from offset zero, let it catch up, and switch the readers over. A batch is just a bounded stream: with event-time windows and replay, as Tyler Akidau argued in 2015, streaming is a superset of batch.

A warehouse exists because two kinds of question want different machines. An operational database, built for online transaction processing, answers many small requests: fetch order ten forty-two, change its quantity, commit, in milliseconds, touching a few rows found by key. Analysis asks the opposite: total sales by product, over every order ever placed. Edgar Codd named it online analytical processing in 1993. Each query reads a couple of columns of every row, and writes nothing. On one database the long scans would starve the short transactions. So the operational system keeps its rows together, in Part 35's B-trees, and a copy of its data, loaded in batches or streamed from its change log, goes to a warehouse built for scans.

Inside, the design Ralph Kimball set out in 1996 still dominates. At the centre is a fact table: one row per business event, here a sale, holding the numbers you add up, and keys. It is narrow, and billions of rows long. Around it are dimension tables, describing who, what, where and when: the date, the store, the product, the customer. They are wide and full of text, but small. Drawn out, the keys radiate from the centre like a star, which names the schema. Facts are what you measure; dimensions are what you filter and group by.

A typical question joins the facts to two dimensions: sales by month and category, for one year. The plan almost writes itself. Filter each small dimension and build a hash table from what survives, Part 35's hash join. Then stream the huge fact table past those tables once, keep the rows whose keys hit, and group them. Chapter 11 spreads exactly this over many machines. A snowflake schema normalizes the dimensions further: the product table points to a category table, which points to a department. Less repetition, more joins. But dimensions are small, so the repetition rarely matters, and most warehouses keep the simpler star.

8Columnar filesDegree4 min

A warehouse query reads a few columns of many rows, so store the table by column. A small table of sales. Written row by row, as an operational database stores it, each row's values sit together. Written column by column, each column's values sit together instead. Now ask for the total amount. The row layout reads every byte of every row; the column layout reads one contiguous run, a quarter of the file, read sequentially, as Part 34 showed disks prefer. And one column holds values of a single type, often repeating, which compress far better than a mixed row. C-Store made this argument in 2005.

Parquet, created at Twitter and Cloudera in 2013, is the columnar file most warehouses and data lakes now share. A file begins and ends with four magic bytes, P A R one. In between, rows are cut into row groups, large horizontal slices that can be read in parallel. Within a row group, each column is one contiguous column chunk. A chunk is split into pages, the unit of encoding and compression: often a dictionary page, then data pages, each holding a small header, levels and values. The footer holds the schema and, for every chunk, its place, its encodings and its statistics. A reader fetches the footer first, then seeks to just the chunks it needs.

Each chunk then picks its encodings. Here is a column of words, stored plainly, every string in full. Dictionary encoding stores each distinct word once, in a dictionary page, and replaces every value by its small integer index. The indices need only as many bits as the dictionary's size requires, here two, so they are bit-packed: eight values in two bytes. Sorted, equal indices sit together, and Part 21's run-length coding stores each run as a count and a value. And timestamps that creep forward store a first value and then small differences: delta encoding.

What do these save on real text? We took three hundred thousand words of the novels as one column. Plainly, with their lengths, it takes two point five eight megabytes. There are thirty thousand five hundred and fifteen distinct words, so indices need fifteen bits; with the dictionary page they come to zero point nine three megabytes, about a third. Gzip alone does a little better, zero point eight. In reading order a word almost never repeats eight times running, so run lengths add nothing. Sort the column, and they halve it, to zero point four seven, under a fifth of plain. A hundred thousand timestamps shrink from eight hundred kilobytes to a hundred and thirty-eight, eleven bits each. And both are undone by simple arithmetic, far cheaper to decode than gzip.

Statistics give the largest saving of all: not reading. Here are a million rows in ten row groups, and a query that wants x between four hundred and twenty thousand and four hundred and thirty thousand. If the table is sorted by x, each group's minimum and maximum are close together, and only one group overlaps the filter. The other nine are skipped unopened: the filter has been pushed down into the scan. In random order, every group spans nearly everything, and all ten must be read. So statistics pay only when data is sorted or clustered by the columns people filter on, which is why table layout matters so much.

9Nested data in columnsGraduate4 min

Real data is rarely flat: logs and documents are records nested inside records. Dremel, Google's interactive query engine, described by Sergey Melnik and colleagues in 2010, stored them in columns anyway. Here are three books, with repeated chapters, each with repeated keywords. One chapter has no keywords; one book has no chapters. The schema says which fields are required and which repeat. Take one column, chapters dot keywords, and write out its values: sea, whale, inn, Highbury. The structure is gone. Which keywords shared a chapter, or a book? And the empty chapter and the empty book have vanished. Two small numbers beside each value bring it all back.

The first number is the repetition level. For each value, in order, it says at which repeated field along the path this value repeats. Zero means a new record has begun. One means a new chapter, in the same book. Two means another keyword, in the same chapter. Walk the column. Sea starts the first book: zero. Whale follows it in the same chapter: two. Inn starts a new chapter: one. The empty chapter still needs a slot, a null with level one, and so does the book with no chapters, a null with level zero. Highbury starts a new book: zero. The path has two repeated fields, so the levels run from zero to two.

The second number, the definition level, says how much of the path exists. Count the fields along chapters dot keywords, optional or repeated, that are really present. A real keyword has its chapter and itself: two, the maximum. The empty chapter exists but holds no keyword: one. The book without chapters has neither: zero. So a null is never stored as a value, only as a level below the maximum, which says exactly where the missing part begins. A column of required fields needs no definition levels, and one outside any repeated field no repetition levels, so flat tables pay nothing.

A reader rebuilds the records from the levels alone, without ever seeing the tree. Read the pairs in order. A repetition level of zero starts a new record. A definition level of zero means that record has no chapters, and we move on. Otherwise, a repetition level of one or less opens a new chapter, and a definition level of two appends a keyword to it. Six pairs later the three books are back, exactly: two keywords and then one in the first two chapters, an empty third chapter, an empty book, and Highbury. And because every column carries its own levels, a query can rebuild just the parts of the records it reads, and never touch the rest.

Why is this worth the trouble? The levels are tiny integers, two bits each here, bit-packed and run-length coded like any other column; in regular data they are nearly constant, and almost free. A missing value costs only its levels. In return, nested records get every benefit of columns: a query about keywords reads keywords and their levels, and nothing else. Dremel's paper reported aggregations over trillion-row tables in seconds, and the system became the engine behind Google's BigQuery. Parquet adopted the same levels, in every data page. In memory, Apache Arrow stores the same trees another way, as offsets into child arrays with bitmaps that mark the nulls.

10Tables on object storageIndustry3 min

A data lake is a folder of chapter eight's files in object storage. Is that a table? A job writes its output as three files. A reader that lists the folder halfway through sees two, and silently computes half an answer. A crashed job leaves its files behind, and overwriting means deleting, then writing. Part 45's object store makes each object atomic, but nothing spans two. And listing a million files takes a thousand requests, one after another.

Apache Iceberg, begun at Netflix, and Delta Lake, from Databricks, give the same answer: keep the list of files in files. In Iceberg a table is a tree: data files; manifests listing them; a manifest list for each snapshot; and a metadata file with the schema and history. A commit writes new files, bottom up, and changes none. Then it swaps one pointer in a catalog, from the old metadata file to the new. That one atomic step is the commit: readers see all of it or none. The new snapshot reuses the old manifest, so a commit costs a few small files. Manifests also record column ranges, so planners prune files without listing anything.

Two jobs commit to the same table at once. Both read version forty-one and work without locks, checking only at commit: Kung and Robinson's optimistic control, from Part 35. Job A finishes first and creates version forty-two. Job B tries forty-two as well, and fails: the name is taken. B reads what A committed. If A touched nothing B read or rewrote, as when both only append, B retries as forty-three, writing just a new log entry. If A rewrote files that B read, B's work is stale and must be redone.

Because commits never change old files, every old version is still there. In Spark SQL, either format can be read as of a version or a timestamp, starting from an older snapshot. A bad write is undone by restoring an earlier version, itself a new commit. Audits can ask what a report saw last March, and models can retrain on the data they first saw. A vacuum later deletes the files that no recent snapshot needs. Armbrust and colleagues named the result in 2021: a lakehouse, a warehouse's guarantees over open files on cheap storage.

11Queries on a thousand machinesGraduate3 min

A warehouse query is too big for one machine, so it runs on many. The table's files are spread over the workers, and the coordinator cuts the plan into fragments that every worker runs on its own share. Each worker first counts its own rows per store, a partial aggregate, and so sends three numbers instead of its rows. An exchange operator then hashes each store to one worker, which adds up that store's partial counts: Part 39's MapReduce shuffle, inside a query. The coordinator gathers the answers. DeWitt's Gamma machine had this shape in 1986; Redshift, BigQuery, Snowflake and Trino have it today.

Joins are where the network bill comes from: a big table, B, meets a small one, S, on N workers. A broadcast join sends a whole copy of S to every worker. B never moves; each worker joins its share of B against the copy, with Part 35's hash join. The cost is S rows, N times over. A shuffle hash join repartitions both tables by the join key, so matching rows meet on one worker. A row stays put only if it already sits on the right worker, one time in N, so the cost is B plus S, times one minus one over N.

Which is cheaper? In our cost model B has a billion rows of a hundred bytes, there are a hundred workers, and S grows from ten thousand rows to a hundred million. Broadcasting grows tenfold with S. Shuffling costs about a hundred gigabytes whatever S is, because B dominates. Set the costs equal: broadcast wins while S is below about B over N, here ten million rows, one percent of B. Optimizers choose from estimated sizes, and cautiously, since every worker must hold the copy in memory: Spark broadcasts only tables it estimates under ten megabytes, by default. A wrong estimate, Part 35's guessing of sizes, makes either choice a disaster.

Hashing spreads keys evenly, not rows. If one key is hot, all its rows go to one worker. We measured it: two hundred thousand rows on sixteen workers, one key holding a fifth. The busiest worker gets almost four times its fair share, and a query finishes only when its slowest worker does. Part 39's backup tasks cannot help: that worker is not slow, its share is large. The fix is salting: split the hot key into eight random sub-keys, and copy its matches on the small side eight times. The slowest worker now carries 1.2 times the ideal. Chapter 6's heavy-hitter sketches find hot keys cheaply, and Spark's adaptive execution splits skewed partitions as the query runs.

12Data you can trustIndustry3 min

The first threat to a pipeline is its input changing shape. An order record gains a currency field; last year's records lack it. Backward compatibility asks whether new readers can read old data: yes, because the new field has a default, which the reader fills in. Forward compatibility asks whether old readers can read new data: yes again; they skip fields they do not know. Avro's rules settle every change. A field without a default breaks backward compatibility, widening an integer breaks forward, and a rename breaks both. A schema registry checks each new version against its topic's rule, backward by default, before producers use it. And Iceberg names columns by number, so renames are safe there: Part 43's API evolution, for data.

Most pipelines begin in a database that another team owns. The orders service writes its tables and publishes changes, through chapter three's outbox, to a topic. A data contract makes that interface explicit, like an API: fields and types, meanings, such as amount in pence including tax, freshness, ownership, and which changes are allowed. Consumers build on the contract, never on the service's internal tables. Now a developer renames amount to total. The contract is checked in the producer's continuous integration, so the change fails there, before deployment, not in a dashboard three days later. A breaking change needs a new version, run beside the old.

Contracts say what data should be; tests check what it is. In dbt, which builds warehouse tables from SQL, tests sit beside each table: this key is unique and never empty, this status takes only these values, every customer exists in the customers table. Each test compiles to a query for the rows that break it, and passes when the query returns nothing. Run such tests on chapter thirteen's stream of novels. Uniqueness finds two books sent twice. Reconciling word totals with the source catches the pipeline without deduplication, nearly seven percent high, and the early watermark, ten percent low. Volume and freshness checks catch the failures nobody wrote a rule for.

Tests help most before anyone reads the data. Chapter ten's tables make that cheap: a job writes its new snapshot but does not publish it, and readers still see version forty-one. The tests run on the staged snapshot. If they pass, publishing is one atomic pointer swap, and every reader moves to forty-two at once. If they fail, the snapshot is never published, and readers keep the last good version. This is write, audit, publish, which Iceberg supports with branches of a table. Trust, then, is engineered: contracts where data is made, tests at every step, lineage to trace failures, and atomic publishing.

13The Job as a streamGraduate2 min

The Job, one last time in a new shape. The thirty novels arrive as a stream, one event per book, each carrying its words and its place in a publishing schedule as its event time. Most arrive a second or two after they are due. Three arrive twenty seconds late, as if from a phone that was offline. And two are sent twice, by a producer that retried. The task is a top twenty that is correct at every moment, and in the end equal to the batch answer of every earlier part.

We ran three pipelines over the same stream. The first deduplicates by book and keeps its counts as state: it counts 4,498,120 words, and its top twenty is identical to the batch answer. The second does not deduplicate. The two books sent twice are counted twice, 4,797,994 words, and the counts are wrong. The third uses a watermark that waits five seconds and drops anything later, so the three late books are missing: 4,048,309 words. The state of a stream is a fold over its events, applied once per key and checkpointed with the source's offset. And because this top twenty is over all time, it needs no watermark at all; a windowed answer would face chapter four's choice between waiting and being wrong.

The ledger gets row seventeen. The Job as a stream on one machine: about 4 seconds for all thirty books, deduplicated and exact. It is slower than the best batch rows, because it does the bookkeeping a stream needs. What it buys is an answer that is current after every book, rather than after the last one.

14Frontier: streams, tables and their limitsResearch2 min

Can every query be kept up to date, cheaply? Streams and tables are converging. Take a query over a table, joins, filters, counts, and ask that its answer stay current as rows arrive. Rather than rerun it, push each change through the plan as a delta: one new order becomes one joined row, which passes the filter or not, and changes one count by one. That is incremental view maintenance, and its promise is work in proportion to the change, not the data. Differential dataflow, from Frank McSherry and colleagues in 2013, extended it to iterative and recursive computations, and DBSP, by Mihai Budiu and colleagues in 2023, gave an algebra that makes any streaming query incremental. Which queries can be maintained cheaply, and with how much state, is open; for some joins, provably, they cannot.

The deepest limit is time. A watermark is a guess that no older events will arrive, and every choice of how long to wait trades completeness for latency: from four fifths of the events within two seconds to all but one of them after a minute. Answering early and then correcting escapes the trade: a five-second watermark with a minute of allowed lateness fired 183 refinements and ended with every window exact. The price is state, and consumers that must accept corrections. Watermarks with guarantees, derived from measured delays, and a semantics of streaming SQL that every engine agrees on, are open problems.

Recap, problems, and where this comes backAll tracks3 min

What we built in this part. A partitioned log, where order holds per key and consumer groups share the partitions, and a compacted log that rebuilds the same state from fifty records instead of two thousand. State as a fold over events. Windows over event time, and watermarks that trade completeness for latency, unless an answer may be corrected later. Barrier snapshots that let a computation crash and recover with exactly-once state. Columnar files, whose dictionaries and run lengths make a column of words a fraction of its size, and Dremel's two levels that put nested records into flat columns. One idea runs through it: record what happened, in order, once, and every answer can be derived, and derived again.

Where this comes back. Part 47 builds a search index from a log of documents and keeps it current. Parts 48 and 49 design feeds, timelines and analytics systems from these pieces. Part 50 turns logs, metrics and traces on the running system itself. Part 57 asks what can be learned from data at this scale, and Part 55 what it takes to trust the pipeline that delivered it.

In practice. Key a log by whatever must stay in order, give it enough partitions for the future, and compact the logs that hold state. Window streams by event time, choose their lateness on purpose, and write results to sinks that tolerate repeats. Capture changes from the database's log or an outbox, never by writing twice. Store tables as columnar files, sorted or clustered by the filter people use most. And broadcast the small side of a join, and look for hot keys before they find you.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: give our stream processor sliding windows and allowed lateness, and measure how much state it has to keep. The last, marked with a star, is a research problem: which joins over windows of a stream can be maintained exactly with less memory than the window itself.

Next time, Part 47: search engines. How do you find the ten most relevant pages among billions in a fifth of a second? An inverted index turns search into merging sorted lists, compression keeps them in memory, a probabilistic model of relevance gives BM25, and a random surfer gives PageRank.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 47 builds a search index from a log of documents and keeps it current. Parts 48 and 49 design feeds, timelines and analytics systems from these pieces, and Part 50 turns logs, metrics and traces on the running system itself. Part 57 asks what can be learned from data at this scale, and Part 55 what it takes to trust the pipeline that delivered it.

Key results

The part's results in one place, for revision.

Why a log\(\displaystyle m\text{ sources},\ n\text{ consumers}:\quad\allowbreak mn\ \text{pipelines }\allowbreak \text{pairwise},\quad\allowbreak m+n\ \text{through }\allowbreak \text{a }\allowbreak \text{log}\)
State is a fold\(\displaystyle s_n=\operatorname{apply}(s_{n-1},e_n),\qquad\allowbreak \text{compaction }\allowbreak \text{keeps }\allowbreak \text{the }\allowbreak \text{last }\allowbreak \text{record }\allowbreak \text{of }\allowbreak \text{each }\allowbreak \text{key}\)
Watermark\(\displaystyle W(t)=\max\{\text{event }\allowbreak \text{time }\allowbreak \text{seen }\allowbreak \text{by } t\}-\text{lag};\quad\allowbreak [a,b)\ \text{fires }\allowbreak \text{when } W(t)\ge b\)
Misra-Gries\(\displaystyle f_x-\tfrac{n}{k}\ \le\ \hat f_x\ \le\ f_x\qquad\allowbreak \text{with } k-1 \text{ counters}\)
Dremel levels\(\displaystyle r=\text{depth }\allowbreak \text{at }\allowbreak \text{which }\allowbreak \text{the }\allowbreak \text{value }\allowbreak \text{repeats},\quad\allowbreak d=\#\text{optional }\allowbreak \text{or }\allowbreak \text{repeated }\allowbreak \text{fields }\allowbreak \text{present}\)
Join crossover\(\displaystyle SN=(B+S)\bigl(1-\tfrac1N\bigr)\ \Rightarrow\ S^*=\frac{B(N-1)}{N^2-N+1}\approx\frac{B}{N}\)

Try it

Lab 46 · Watermarks, checkpoints and repetition levels

Run the series' stream processor over 3,000 events that arrive late, out of order and sometimes twice: trade completeness against latency with the watermark's lag, escape the trade with allowed lateness, recover a keyed counter from a crash with exactly-once state, and rebuild nested records from Dremel's levels alone.

Figure produced by Lab 46: Watermarks, checkpoints and repetition levels
Produced by the lab below, seed 0, in 0.2 s.
python -m videos.cs.labs 46 needs numpy, scipy, matplotlib · download lab46.py · source on GitHub
watermark lag 0 s                  551 of 3,000 events dropped, 1 of 30 windows exact, answers 2.2 s after the window ends
watermark lag 5 s                  183 of 3,000 events dropped, 1 of 30 windows exact, answers 7.0 s after the window ends
watermark lag 60 s                 1 of 3,000 events dropped, 29 of 30 windows exact, answers 65.3 s after the window ends
lag 5 s, 90 s of allowed lateness  0 dropped, 30 of 30 windows exact, first answers after 7.0 s, 183 refinements
crash at offset 2,556              restored from 2,500, 56 events replayed, counts exact; without the snapshot, 56 over-counted
Dremel, 300 random books           874 slots for 691 values; every record rebuilt from 2-bit levels
broadcast = shuffle at             9,998,990 small rows (B/N = 10,000,000); 2,000 updates compact to 50 records, same state

A watermark is a guess about time: a short lag answers early and drops late events, a long one is complete and slow, and allowed lateness keeps the early answer and corrects it. Checkpoints make the state exact after a crash only because state and source offset are restored together.
The code (106 lines; it asserts its own result)
"""Lab 46: count a late, out-of-order stream in event-time windows, crash a checkpointed counter, and round-trip nested records through Dremel's levels."""

from videos.coursekit import labs  # noqa: I001  (must stay first: it lets explainer.cs import without manim)

import numpy as np

from explainer.cs.data import columnar as col
from explainer.cs.data import log as plog
from explainer.cs.data import stream as st

TITLE = "Watermarks, checkpoints and repetition levels"
GOAL = ("Run the series' stream processor over 3,000 events that arrive late, out of order and sometimes twice: trade "
        "completeness against latency with the watermark's lag, escape the trade with allowed lateness, recover a "
        "keyed counter from a crash with exactly-once state, and rebuild nested records from Dremel's levels alone.")
TASKS = [
    "Raise late_share in st.make_events from 0.05 to 0.2 and rerun the trade-off. Which lag now gives 99% completeness, and what does it cost in latency?",
    "Call st.run_windows with dedup=False and a 60 s lag. How many windows are still exact, and by how much is the total over-counted?",
    "Append a book whose only chapter has no keywords and a book with no chapters to the records, write their (r, d) levels by hand, and check them against col.dremel.",
]

PATH = [("chapters", "repeated"), ("keywords", "repeated")]


def random_books(rng, n):
    books = []
    for _ in range(n):
        chapters = [{"keywords": [f"w{int(rng.integers(100))}" for _ in range(int(rng.integers(0, 4)))]}
                    for _ in range(int(rng.integers(0, 4)))]
        books.append({"chapters": chapters})
    return books


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. the watermark's lag: completeness against latency
    events = st.make_events(n=3000, seed=seed)
    lags = [0.0, 1.0, 2.0, 5.0, 10.0, 20.0, 60.0]
    runs = [st.run_windows(events, watermark_lag=lag) for lag in lags]
    dropped = [r["dropped"] for r in runs]
    latency = [r["mean_latency"] for r in runs]
    assert all(a >= b for a, b in zip(dropped, dropped[1:])), "waiting longer never drops more"
    assert all(a < b for a, b in zip(latency, latency[1:])), "and always answers later"
    assert dropped[0] > 300 and dropped[-1] <= 5 and latency[-1] > 55
    for lag, r in zip(lags, runs):
        if lag in (0.0, 5.0, 60.0):
            lab.row(f"watermark lag {lag:g} s", f"{r['dropped']} of 3,000 events dropped, {r['exact']} of "
                                                f"{r['windows']} windows exact, answers {r['mean_latency']:.1f} s after the window ends")
    late = st.run_windows(events, watermark_lag=5.0, allowed_late=90.0)
    assert late["dropped"] == 0 and late["exact"] == late["windows"] and late["refinements"] > 0
    assert abs(late["mean_latency"] - runs[3]["mean_latency"]) < 1e-9, "the first answer is as early as before"
    lab.row("lag 5 s, 90 s of allowed lateness", f"0 dropped, {late['exact']} of {late['windows']} windows exact, "
                                                 f"first answers after {late['mean_latency']:.1f} s, {late['refinements']} refinements")

    # 2. a keyed counter crashed between checkpoints
    crash = int(rng.integers(600, 2900))
    snap = st.barrier_snapshot(events, checkpoint_every=500, crash_at=crash)
    assert snap["exact_with_snapshots"], "restore the snapshot, replay from its offset: the counts are exact"
    assert snap["restored_from"] == (crash - 1) // 500 * 500 and snap["replayed"] == crash - snap["restored_from"]
    assert snap["naive_overcount"] == snap["replayed"] > 0, "replaying without restoring state counts those twice"
    lab.row(f"crash at offset {crash:,}", f"restored from {snap['restored_from']:,}, {snap['replayed']} events replayed, "
                                         f"counts exact; without the snapshot, {snap['naive_overcount']} over-counted")

    # 3. Dremel: nested records to (value, r, d) and back
    books = random_books(rng, 300)
    levels = col.dremel(books, PATH)
    assert col.reassemble(levels) == [[c["keywords"] for c in b["chapters"]] for b in books], "rebuilt from levels alone"
    values = sum(len(c["keywords"]) for b in books for c in b["chapters"])
    assert sum(1 for _, _, d in levels if d == 2) == values and sum(1 for _, r, _ in levels if r == 0) == len(books)
    assert all(0 <= r <= 2 and 0 <= d <= 2 for _, r, d in levels)
    lab.row("Dremel, 300 random books", f"{len(levels)} slots for {values} values; every record rebuilt from 2-bit levels")

    # 4. the join crossover and a compacted log
    cost = col.join_cost(big_rows=1e9, small_rows=1e6, workers=100)
    at = col.join_cost(big_rows=1e9, small_rows=cost["crossover_small_rows"], workers=100)
    assert abs(at["broadcast_bytes"] / at["shuffle_bytes"] - 1) < 1e-9 and cost["broadcast_bytes"] < cost["shuffle_bytes"]
    assert abs(cost["crossover_small_rows"] / (1e9 / 100) - 1) < 0.01, "about B / N"
    comp = plog.compaction_demo(seed=seed)
    assert comp["same_state"] and comp["after_compaction"] == comp["keys"]
    lab.row("broadcast = shuffle at", f"{cost['crossover_small_rows']:,.0f} small rows (B/N = 10,000,000); "
                                      f"{comp['events']:,} updates compact to {comp['after_compaction']} records, same state")
    lab.note = ("A watermark is a guess about time: a short lag answers early and drops late events, a long one "
                "is complete and slow, and allowed lateness keeps the early answer and corrects it. Checkpoints "
                "make the state exact after a crash only because state and source offset are restored together.")

    fig, ax = labs.figure(2, size=(11, 4.4))
    pts = st.plot_points(seed=seed + 1)
    et, at = np.array(pts["points"]).T
    ax[0].plot([0, 60], [0, 60], color=labs.MUTED, ls="--", lw=1, label="no delay")
    ax[0].scatter(et, at, s=12, color=labs.BLUE, label="event")
    wm = np.array(pts["watermark"])
    ax[0].step(wm[:, 1], wm[:, 0], where="post", color=labs.GOLD, label="watermark: newest event time - 3 s")
    ax[0].set(title="120 events: when they happened and when they arrived", xlabel="event time (s)",
              ylabel="arrival time (s)")
    ax[0].legend(loc="upper left")
    share = [100 * d / 3000 for d in dropped]
    ax[1].plot(latency, share, "o-", color=labs.RED, label="watermark lag only")
    for lag, x, y in zip(lags, latency, share):
        ax[1].annotate(f"{lag:g} s", (x, y), textcoords="offset points", xytext=(6, 6), color=labs.MUTED, fontsize=9)
    ax[1].plot([late["mean_latency"]], [0], "*", ms=14, color=labs.GREEN, label="lag 5 s + 90 s allowed lateness")
    ax[1].set(title="Completeness against latency (labels: the lag)", xlabel="mean delay of a window's first answer (s)",
              ylabel="events dropped (%)")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Raise late_share in st.make_events from 0.05 to 0.2 and rerun the trade-off. Which lag now gives 99% completeness, and what does it cost in latency?
  2. Call st.run_windows with dedup=False and a 60 s lag. How many windows are still exact, and by how much is the total over-counted?
  3. Append a book whose only chapter has no keywords and a book with no chapters to the records, write their (r, d) levels by hand, and check them against col.dremel.

Problems, with solutions

Try each problem before opening its solution.

  1. Per-key order. Show that a consumer of one partition sees each key's events in order, and give an example where a consumer of two partitions sees two keys' events in an order no producer wrote.

    Solution

    A record's partition is hash(key) mod n, a function of the key alone, so every record of one key goes to the same partition. A partition is an append-only log: each append takes the next offset, and no record is ever changed or moved, so offsets order the records in the order the broker appended them. A consumer reads a partition by increasing offset, from its committed position. Hence, if the producer's records for a key are appended in the order it sent them (one producer, and retries that do not reorder its batches), the consumer sees that key's records in that order, and after a crash it resumes from a committed offset without reordering anything. Across partitions nothing is promised: a consumer of several partitions interleaves its fetches as timing dictates. In our run of "the whale and the sea and the ship and the whale" over four partitions, "the" (positions 0, 3, 6, 9) lands in partition 2 and "whale" (1, 10) with "and" (2, 5, 8) in partition 1. A consumer that fetches partition 1 first sees whale(1), and(2), …, whale(10) before the(0), so "whale" precedes "the", an order the single producer never wrote; within each key the order is still correct.

  2. Watermark lag. Prove that a watermark lag of L drops exactly the events whose delay exceeds L plus the window's slack, and compute the share dropped for exponential delays.

    Solution

    Take a tumbling window [s, s + T), an event in it with event time e and delay D (it arrives at e + D), and call σ = s + T − e ∈ (0, T] the event's slack, how far it lies before its window's end. Idealize the watermark as W(t) = t − L, as when the sources' newest event times keep pace with the clock. The window fires when W reaches s + T, at processing time s + T + L, and an event arriving after that is dropped. So the event is dropped if and only if e + D > s + T + L, that is D > L + σ. (With allowed lateness A the window accepts events until s + T + L + A, and L is replaced by L + A.) For exponential delays of mean μ and events spread evenly over the window, σ is uniform on (0, T], and the share dropped is (1/T)∫₀ᵀ e^(−(L+σ)/μ) dσ = (μ/T) e^(−L/μ) (1 − e^(−T/μ)). For μ = 2 s and T = 10 s this is 0.1987 e^(−L/2): 19.9% at L = 0, 7.3% at L = 2, 1.6% at L = 5 and 0.13% at L = 10. Our simulation also delays 5% of events by a further 20 to 60 s; for L ≤ 10 all of these are dropped, since D ≥ 20 > L + σ. The heuristic watermark, largest event time seen minus L, trails the clock by the age γ of the freshest event seen (0.48 s on average here), and the window fires at the first arrival after W passes its end, so the effective lag is a little more than L. Fitting an extra 0.7 s, 0.05 + 0.95 · 0.1987 e^(−(L+0.7)/2) gives 18.3%, 13.1%, 9.9% and 6.1% for L = 0, 1, 2 and 5 s, against the measured 17.7%, 13.2%, 10.0% and 6.1% (530, 397, 301 and 182 of 3,000 events).

  3. Barrier snapshots. Show that asynchronous barrier snapshots give a consistent cut (Part 38), and hence exactly-once state after recovery.

    Solution

    Assume an acyclic dataflow graph with FIFO channels and replayable sources. Checkpoint n consists of each source's offset at the moment it emits barrier n, and each operator's state at the moment it has received barrier n on every input (holding back inputs whose barrier came first, which is alignment) and before it processes anything after the barriers. By induction in topological order, an operator's snapshot reflects exactly the records that precede barrier n on its inputs: alignment stops it from processing any record behind a barrier, and FIFO channels deliver everything ahead of the barrier before it. Each of those input records was emitted by its upstream operator before that operator forwarded barrier n, hence derives only from source records before the recorded offsets; so every snapshot is a function of the same prefix of each source. The cut is consistent: if an operator's state reflects a received record, the sender's snapshot reflects having sent it, and because every record ahead of a barrier has been consumed when the snapshot is taken, no channel holds a record that crosses the cut, so there is no channel state to save. (For cyclic graphs Carbone et al. also log the records in flight on back edges.) Recovery restores every operator's state and rewinds every source to its offset: each source record before the offset has affected the state exactly once, through the snapshot, and each record after it affects the state exactly once, in the replay, so the restored run is a failure-free run of the same input (the same run, if the operators are deterministic). In our instrument, 3,032 events with a crash at offset 1,700 restore from the checkpoint at 1,500, replay 200 events, and end with counts equal to a run that never failed; keeping the crashed state while rewinding the source counts those 200 events twice.

  4. Dremel levels. Compute the repetition and definition levels of a three-level nested column by hand, and rebuild the records from them.

    Solution

    Take records with repeated shelves, each with repeated books, each with repeated tags, and the column shelves.books.tags (three repeated fields, so r and d both run from 0 to 3): record 1 has shelf 1 with books [sea, whale] and [ ], and shelf 2 with book [inn]; record 2 has no shelves; record 3 has shelf 1 with no books and shelf 2 with book [York]. The repetition level says at which repeated field a value repeats (0 a new record, 1 a new shelf, 2 a new book, 3 another tag in the same book), and the definition level how many of the three fields are present. Walking the records in order gives seven slots: (sea, 0, 3), (whale, 3, 3), (null, 2, 2) for the empty book, (inn, 1, 3), (null, 0, 0) for the record without shelves, (null, 0, 1) for the shelf without books, and (York, 1, 3). To rebuild, read the triples in order: r = 0 starts a new record; if d ≥ 1 and r ≤ 1, open a new shelf; if d ≥ 2 and r ≤ 2, open a new book in the current shelf; if d = 3, append the value to the current book. The seven triples give back [[[sea, whale], [ ]], [[inn]]], [ ] and [[ ], [[York]]], the three records exactly, as our dremel function and this reader confirm.

  5. Build. Add sliding windows and allowed lateness to our stream processor, and measure the state it must keep.

    Solution

    Solution notes. In run_windows, assign each event to every window sliding(et, size, step) returns rather than the one from tumbling, keep counts per (window, key), fire a window when the watermark reaches its end, and accept late events (as refinements) until the watermark passes end + allowed lateness; at that moment emit the final count and delete the window's state, which the present instrument never does. Track the number of open windows and of (window, key) entries after each event, and their maximum. A window is open from its first event until about end + L + A in processing time, so roughly (size + L + A)/step windows are open at once, each with up to one counter per key. A sketch along these lines on the instrument's 3,000 events (three keys, 10 s windows, L = 5 s) reproduces the cached tumbling results (182 dropped without lateness; all 30 windows exact with 60 s of lateness) and measures a peak of 2 open windows (6 entries) without lateness and 8 (24) with it, against (10 + 5 + 60)/10 = 7.5; sliding windows every 5 s need 4 (10) and 16 (46), against 15, and with 60 s of lateness 60 of their 61 windows end exact. State grows linearly in the window size plus the lateness, and divided by the step.

  6. ★ Research. Which windowed stream joins can be maintained exactly in space sublinear in the window?

    Discussion. Open. For an equi-join of two streams over a window of w events with keys from a large domain, an exact answer needs Ω(w) words in the worst case: whether a new event joins depends on whether its key appeared among the last w events of the other stream, and a standard communication argument (the INDEX problem) shows that remembering a set of that kind takes space linear in it. Sublinear space is possible under extra structure: a small key domain (keep a count per key), constraints on the data such as ordering or bounded disorder that let state be discarded early (Babu, Srivastava and Widom studied such "k-constraints"), or an output that is only an aggregate of the join; Arasu et al. (PODS 2002) characterized the select–project–join queries over unbounded streams that need only bounded memory. A good answer would fix a model (time- or count-based windows, join predicates, whether the output is every match or an aggregate), prove lower bounds for the hard classes, give algorithms meeting them for the rest, and draw the line between them; a characterization for equi-joins with bounded disorder, or for band joins on ordered keys, would already be new.

Notes and sources

Glossary

  • log, topic, partition, segment, offset — an append-only sequence of records; a named stream split into partitions; the files a partition is stored in; a record's position.
  • consumer group, rebalance, range and sticky assignment — members sharing a topic's partitions; reassigning them when a member joins or leaves; recutting contiguous runs, or moving only what must move.
  • retention, log compaction, tombstone — forgetting by age; keeping the latest record per key; a record that deletes its key.
  • in-sync replicas (ISR), high watermark — the followers caught up with the leader; the offset up to which every one of them has the data, and consumers may read.
  • batching, zero-copy (sendfile), page cache — one request for many messages; sending file pages to a socket without copying them through the program; the kernel's cache of file pages.
  • dual write, change data capture (CDC), outbox — writing two systems without a shared transaction; publishing a database's committed changes from its log; a table of events committed with the state they describe.
  • event sourcing, CQRS, read model — an application whose system of record is a log of events; separating the write model from the read models; a fold over the events for one question.
  • event time, processing time — when an event happened; when the pipeline sees it.
  • tumbling, sliding and session windows — fixed pieces of event time; overlapping windows with a size and a step; runs of activity ended by a gap.
  • watermark, late event, allowed lateness — a claim that no older events are still coming; an event behind it; how long a fired window still accepts corrections.
  • trigger, accumulation (discarding, accumulating, retracting) — when a window's result is emitted; how successive results relate.
  • keyed state, barrier, alignment, checkpoint (asynchronous barrier snapshot) — an operator's state partitioned by key; a marker flowing with the records; waiting for a barrier on every input; a consistent cut of offsets and states.
  • at-most-once, at-least-once, exactly-once, idempotent and transactional sinks — delivery guarantees, and the sinks that make a repeated write harmless or invisible until committed.
  • mergeable summary, HyperLogLog, KLL, t-digest — a sketch that combines across partitions with the same guarantee; distinct counts; quantiles with rank error; quantiles accurate at the tails.
  • Lambda and Kappa architectures — a batch and a stream path merged at query time; one stream path, replayed to change it.
  • OLTP, OLAP, fact, dimension, star and snowflake schemas, slowly changing dimension — transactions against analysis; the events measured and what describes them; their layouts; dimensions with history.
  • columnar file, row group, column chunk, page, footer — a table stored by column; its horizontal slices; one column of a slice; the unit of encoding; the schema and statistics at the end.
  • dictionary encoding, bit-packing, run-length and delta encoding, predicate pushdown — integers for repeated values; packing them in as few bits as needed; runs and differences; skipping data by statistics.
  • repetition level, definition level — at which repeated field a value repeats; how much of its path exists.
  • table format, snapshot, manifest, optimistic commit, time travel, lakehouse — a table kept as files on object storage; a version of it; a list of its files; commit by compare-and-swap, retrying on conflict; reading an old version; a warehouse's guarantees over open files.
  • MPP, exchange, broadcast join, shuffle hash join, skew, salting — a query spread over many machines; the operator that repartitions; sending the small table everywhere; repartitioning both by key; one key with too many rows; splitting it into sub-keys.
  • vectorized execution, selection vector — operators that pass batches of column values; the positions in a batch that passed a filter.
  • schema evolution, backward and forward compatibility, schema registry, data contract — changing a record's shape; new readers of old data and old readers of new; the service that checks changes; an explicit, versioned interface between teams.
  • data test, lineage, write–audit–publish — a query for the rows that break a rule; the graph of what is built from what; staging a snapshot and publishing it only after its tests pass.
  • incremental view maintenance, differential dataflow, DBSP — keeping a query's answer current by pushing changes through it.

Sources

  • M. Kleppmann, Designing Data-Intensive Applications (2017), ch. 3, 10–12; T. Akidau, S. Chernyak and R. Lax, Streaming Systems (2018); R. Kimball and M. Ross, The Data Warehouse Toolkit (3rd edn, 2013).
  • J. Kreps, "The Log: what every software engineer should know about real-time data's unifying abstraction", LinkedIn Engineering (2013); J. Kreps, N. Narkhede and J. Rao, "Kafka: a distributed messaging system for log processing", NetDB 2011.
  • T. Akidau et al., "MillWheel: fault-tolerant stream processing at internet scale", VLDB 2013; T. Akidau et al., "The Dataflow model: a practical approach to balancing correctness, latency, and cost in massive-scale, unbounded, out-of-order data processing", VLDB 2015.
  • K. M. Chandy and L. Lamport, "Distributed snapshots: determining global states of distributed systems", ACM TOCS 1985; P. Carbone, G. Fóra, S. Ewen, S. Haridi and K. Tzoumas, "Lightweight asynchronous snapshots for distributed dataflows" (2015); J. Saltzer, D. Reed and D. Clark, "End-to-end arguments in system design", ACM TOCS 1984.
  • Z. Karnin, K. Lang and E. Liberty, "Optimal quantile approximation in streams", FOCS 2016; T. Dunning and O. Ertl, "Computing extremely accurate quantiles using t-digests" (2019); P. Agarwal et al., "Mergeable summaries", PODS 2012; N. Alon, Y. Matias and M. Szegedy, "The space complexity of approximating the frequency moments", STOC 1996.
  • M. Stonebraker et al., "C-Store: a column-oriented DBMS", VLDB 2005; D. Abadi, P. Boncz, S. Harizopoulos, S. Idreos and S. Madden, "The design and implementation of modern column-oriented database systems", Foundations and Trends in Databases 2013; the Apache Parquet format specification.
  • S. Melnik, A. Gubarev, J. J. Long, G. Romer, S. Shivakumar, M. Tolton and T. Vassilakis, "Dremel: interactive analysis of web-scale datasets", VLDB 2010.
  • M. Armbrust et al., "Delta Lake: high-performance ACID table storage over cloud object stores", VLDB 2020; M. Armbrust, A. Ghodsi, R. Xin and M. Zaharia, "Lakehouse: a new generation of open platforms that unify data warehousing and advanced analytics", CIDR 2021; the Apache Iceberg table specification.
  • D. DeWitt et al., "GAMMA: a high performance dataflow database machine", VLDB 1986; G. Graefe, "Volcano: an extensible and parallel query evaluation system", IEEE TKDE 1994; P. Boncz, M. Zukowski and N. Nes, "MonetDB/X100: hyper-pipelining query execution", CIDR 2005; T. Neumann, "Efficiently compiling efficient query plans for modern hardware", VLDB 2011.
  • F. McSherry, D. Murray, R. Isaacs and M. Isard, "Differential dataflow", CIDR 2013; M. Budiu, T. Chajed, F. McSherry, L. Ryzhyk and V. Tannen, "DBSP: automatic incremental view maintenance for rich query languages", VLDB 2023; A. Arasu, B. Babcock, S. Babu, J. McAlister and J. Widom, "Characterizing memory requirements for queries over continuous data streams", PODS 2002.
About this partfrom its README

Part 46 of a sixty-one-part course in computer science (see the series plan and the syllabus), the second part of Act IX, Systems at Scale. Every company's data ends up in two places: an append-only log that records everything as it happens, and a column-oriented warehouse that answers questions about all of it, with stream processors between them computing answers continuously. The hard part is time: events arrive late, out of order and more than once. We build a partitioned log, a stream processor with watermarks and checkpoints, and a columnar encoder, and the Job becomes a live top twenty over a stream of novels.

The instruments are in explainer/cs/data/ (tested in tests/test_cs46_data.py):

  • log.py: a topic of partitions, each an append-only list of (offset, key, value, time) records cut into segments; keys hashed to partitions with CRC-32; range assignment and a sticky rebalance for consumer groups, with the number of partitions each moves; retention by whole segments and compaction to the last record per key; demonstrations of per-key order, rebalancing and compaction.
  • stream.py: a generator of events with event times, exponential network delays, a few much later arrivals and some duplicates; tumbling, sliding and session windows; a windowed keyed counter with a heuristic watermark (largest event time seen minus a lag), allowed lateness, deduplication and refinements; a keyed counter checkpointed by barrier snapshots and crashed on purpose; and the Job as a stream of thirty novels in three pipelines.
  • columnar.py: Parquet-style encodings (plain strings with lengths, dictionary with bit-packed indices, the RLE/bit-packing hybrid, delta for integers) with sizes measured; row groups with min/max statistics and the groups a filter must read; Dremel's repetition and definition levels for a nested column, and the records rebuilt from them; the bytes moved by broadcast and shuffle joins and their crossover; a hot key over hashed workers, with salting; a simplified KLL quantile sketch; and optimistic commits to a table by compare-and-swap, conflicting or appending.
Chapter notes
  • Hook. The log as the structure we keep meeting: Part 35's write-ahead log, Part 38's Raft log, Part 41's git history, Part 43's outbox; Kreps's "The Log" (2013). Four sources and four consumers joined pairwise need 4 × 4 = 16 pipelines, through a log 4 + 4 = 8 connections, each consumer at its own offset. Two places for every company's data, and the stream processors between them.
  • 1. The partitioned log. Kafka (Kreps, Narkhede and Rao, 2011): topics, partitions, segment files named by their base offset, a consumer's state as one offset per partition. "the whale and the sea and the ship and the whale" hashed into four partitions: every key's records in order (checked: true), the common words filling two partitions and one holding a single "ship". Twelve partitions and a consumer group: a fourth member joins and range assignment moves 6 partitions against the sticky assignor's 3; member two leaves and range moves 4, sticky 3. Retention by time and compaction by key: 2,000 updates to 50 keys compact to 50 records that rebuild the same state. In-sync replicas and the high watermark, Part 39's single-leader replication.
  • 2. Moving a gigabyte a second. At 200-byte messages a gigabyte a second is 5 million messages, 200 ns each; against Part 34's model a random flash read costs 400 budgets and a random disk read 64,803. Sequential appends and forward scans: 150 MB/s against 0.32 MB/s, 475× apart, so seven disks make the target. Batching (the Kafka paper's producer: 50,000 messages a second one at a time, 400,000 in batches of 50), linger.ms and compression; sendfile instead of four copies and two system calls; the page cache as the broker's only cache.
  • 3. Changes as events. Dual writes that crash or race and leave two answers; change data capture from the write-ahead log (logical decoding, the binary log, Debezium), keyed by primary key, starting from a snapshot; the outbox, a designed contract delivered at least once; state as a fold over events (balances 0, 50, 30, 40), and the compacted topic as exactly that fold; event sourcing and CQRS, with their costs.
  • 4. Event time and processing time. 120 simulated events, 2 a second, plotted at event time across and arrival upwards, the slowest 18.5 s late. Tumbling (10 s), sliding (10 s every 5 s) and session windows (a 4 s gap) over eight events. A heuristic watermark, the largest event time seen minus 3 s: 11 of the 120 events arrive behind it, and the window [0, 10) closes at 13.1 s with 19 of its 20 events, the last arriving at 14.8 s. How long to wait, on 3,000 events in 10 s windows: no lag drops 530 events and answers 2.2 s after a window ends; 5 s drops 182 (7.0 s); a minute drops 1, with 29 of 30 windows exact but answers 65.3 s late; a 5 s watermark with 60 s of allowed lateness drops none, ends with all 30 windows exact, and fires 183 refinements. Triggers (early, on time, late) and accumulation (discarding, accumulating, retracting); what, where, when and how.
  • 5. Exactly-once state. Keyed state on workers, and the replay question after a crash. Barriers through a dataflow graph (Carbone et al., 2015, after Chandy and Lamport): alignment, asynchronous snapshots, a complete checkpoint. Our keyed counter crashed on purpose: 3,032 events, three workers, a crash at offset 1,700, recovery from the checkpoint at 1,500, 200 events processed a second time and final counts equal to a failure-free run; rewinding the source but keeping the counts overcounts those 200 events (at-least-once). Idempotent and transactional sinks; exactly-once as an end-to-end property (Saltzer, Reed and Clark).
  • 6. Streaming algorithms in production. Part 20's Misra–Gries summary with 99 counters over the corpus's 4,609,954 words: every count low by at most n/k, about 46,100 ("the": true 230,878, estimate 192,188). HyperLogLog on 57,895 distinct words: 26% error with 12 bytes, 0.7% with 12,288; with 3,072 bytes, 58,012 estimated, and 4,483,876 for 4,506,123 distinct five-word phrases; merging by the larger register. A KLL sketch of 200,000 simulated latencies keeping 95 items: p99.9 off by 0.6% in rank yet 164 against 427 in value; t-digest's clusters. Windowed stream joins and the state they hold; mergeable summaries.
  • 7. The warehouse. Lambda (Marz, 2011) against Kappa (Kreps, 2014); streaming as a superset of batch. OLTP against OLAP (Codd, 1993). The star schema of facts and dimensions (Kimball, 1996), a star join planned as hash joins, snowflakes, and slowly changing dimensions (type 1 overwrites, type 2 adds a version).
  • 8. Columnar files. Rows against columns (C-Store, 2005); a Parquet file's row groups, column chunks, pages and footer. Dictionary, bit-packing, run lengths and deltas on a small example, then measured on 300,000 words of the novels (30,515 distinct, so 15-bit indices): plain 2.58 MB, gzip 0.80 MB, dictionary page plus indices 0.93 MB (0.37 + 0.56), run lengths in reading order 0.93 MB, sorted 0.47 MB (18% of plain); 100,000 timestamps from 0.80 MB plain to 0.14 MB delta-encoded, 8 bytes each against 11 bits. Predicate pushdown on a million rows in ten row groups: 1 of 10 read when sorted by x, 10 of 10 in random order.
  • 9. Nested data in columns. Dremel (Melnik et al., 2010): three books with repeated chapters and repeated keywords, the column chapters.keywords flattened to sea, whale, inn, Highbury; repetition levels 0, 2, 1, 1, 0, 0 and definition levels 2, 2, 2, 1, 0, 2 for its six slots (four values, an empty chapter, an empty book); the records rebuilt exactly from the levels alone; 2-bit levels, nulls costing only their levels; Parquet and Arrow.
  • 10. Tables on object storage. Why a folder is not a table; Iceberg's snapshots, manifest lists and manifests with one atomic pointer swap; Delta Lake's log of numbered commits, checkpoints every ten commits and conditional writes; optimistic commits, measured with fifty commits per writer: when every commit conflicts, sixteen writers retry 3.85 times per commit and reach 2.6× one writer's rate, while appends that only renumber reach 11.1×; time travel, restore and vacuum; the lakehouse (Armbrust et al., 2021).
  • 11. Queries on a thousand machines. Partitioned execution with partial aggregates and an exchange (Gamma, 1986). Broadcast (S × N rows) against shuffle ((B + S)(1 − 1/N) rows) for B a billion 100-byte rows and N = 100: broadcast grows from 100 MB to 1 TB, shuffle stays near 100 GB, and they cross at S* ≈ 10.0 million rows, 1% of B. One hot key with a fifth of 200,000 rows on 16 workers: the slowest worker carries 49,757 rows, 3.98× the ideal 12,500; salting into eight sub-keys brings it to 15,061, 1.20×. Vectorized execution (MonetDB/X100, DuckDB's 2,048) against Volcano's row at a time, and compiled queries (HyPer).
  • 12. Data you can trust. Schema evolution by Avro's rules (backward, forward), a schema registry, Iceberg's column IDs; data contracts checked where the change is made; tests on data (dbt), run on chapter 13's stream: books 5 and 13 arrive twice, the word total is +6.7% without deduplication and −10.0% with a 5 s watermark (3 late books dropped), equal exactly once; lineage graphs; write, audit, publish.
  • 13. The Job as a stream. Thirty novels, 4,498,120 words, one event per book: books 8, 18 and 19 arrive twenty seconds late, books 5 and 13 are sent twice. Three pipelines: exactly once counts 4,498,120 words ("the" 227,474) and equals the batch answer; no deduplication counts 4,797,994 ("the" 241,278); a 5 s watermark counts 4,048,309 ("the" 202,443). A top twenty over all time needs no watermark. Ledger row 17: 3.7 s on one machine, exact, and current after every book.
  • 14. Frontier: streams, tables and their limits. Incremental view maintenance, differential dataflow (McSherry et al., 2013) and DBSP (Budiu et al., 2023). How small a summary can be: KLL with 95, 309 and 1,326 items kept, rank errors at p50 of 0.83%, 0.61% and 0.02%, at p99 of 0.32%, 0.10% and 0.06%, at p99.9 of 0.58%, 0.22% and 0.07%; optimality and lower bounds (Alon, Matias and Szegedy, 1996). Time as a guess: completeness against latency across watermark lags, and allowed lateness escaping the trade. Four open problems and the ★ research problem.
  • Outro. Recap, payoffs, practice, problems, next part.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: "The Log" (Kreps 2013), the log as the unifying abstraction (callbacks to Part 35's WAL and Part 38's Raft log).
  2. The partitioned log (Kafka 2011): segments, offsets, keys and partitions; consumer groups and rebalancing; retention and compaction; in-sync replicas (callback to Part 39).
  3. Throughput engineering: sequential I/O (callback to Part 34), batching, zero-copy, the page cache.
  4. Change data capture (the database's WAL as a stream, callback to Part 35); the outbox (callback to Part 43); event sourcing and CQRS, with state as a fold over events.
  5. The dataflow model (Akidau et al. 2015):
    • event time against processing time;
    • tumbling, sliding and session windows;
    • watermarks and lateness; triggers and accumulation;
    • the event-time/processing-time plot, animated.
  6. Exactly-once state: keyed state and checkpoints by asynchronous barrier snapshots (Carbone et al. 2015, a Chandy–Lamport descendant, callback to Part 38); idempotent and transactional sinks; exactly-once only ever holds end to end.
  7. Streaming algorithms in production: top-k, distinct counts, quantiles with t-digest and KLL (callback to Part 20); windowed stream joins.
  8. Lambda against Kappa; streaming as a superset of batch.
  9. The warehouse: OLTP against OLAP; star and snowflake schemas; facts, dimensions and slowly changing dimensions.
  10. Columnar files:
    • Parquet: row groups, column chunks, pages;
    • dictionary, RLE/bit-packing and delta encodings (callbacks to Parts 21 and 28);
    • statistics and predicate pushdown;
    • Dremel's repetition and definition levels for nested data, derived on an example.
  11. Lakehouses: table formats (Iceberg, Delta) with snapshots, manifests and optimistic commits, giving ACID on object storage (callbacks to Parts 35 and 45); time travel.
  12. MPP query engines: partitioned execution and shuffles (callback to Part 39); broadcast against shuffle hash joins (cost model derived); skew and salting; vectorized execution (callback to Part 35).
  13. Data quality: schema evolution (callback to Part 43), data contracts, validation tests, lineage graphs.
  14. Approximate and private analytics: sampling with confidence intervals, sketches in SQL, differentially private counts.
  15. The Job as a stream: novels arriving as events, some late and some duplicated; a continuously updated top-20 with event-time windows and exactly-once state. Ledger row 17. Outro.

Computed: a partitioned-log simulator with consumer groups; a stream processor with watermarks and late data (correctness against latency); checkpoint-and-recover with an exactly-once check; a Parquet-style encoder on the novels' words (sizes by encoding); Dremel levels; join costs; t-digest accuracy. Visuals: the event-time/processing-time plot with its watermark curve; windows sliding; barriers flowing through a dataflow graph; a Parquet file exploded into row groups and pages; a shuffle with one hot key overloading a worker. In practice: Kafka, Flink, Spark Structured Streaming, Debezium; Snowflake, BigQuery, Redshift; Parquet, Iceberg, Delta; dbt; data engineering. Reading: Kleppmann ch. 3, 10–12; Akidau, Chernyak & Lax, Streaming Systems; Kimball & Ross, The Data Warehouse Toolkit; Kreps 2013; Kreps, Narkhede & Rao 2011; Akidau et al. 2015; Carbone et al. 2015; Melnik et al. 2010; Armbrust et al. 2020, 2021; Abadi et al. 2013 (the design of column stores); Dunning & Ertl 2019; Karnin, Lang & Liberty 2016.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 按键的顺序。 证明一个分区的消费者按顺序看到每个键的事件,并举例说明一个消费两个分区的消费者看到的两个键的事件顺序, 是任何生产者都没有写过的。

    解答

    记录的分区是 hash(key) mod n,只取决于键,所以同一个键的所有记录都进入同一个分区。分区是只追加的日志:每次追加取下一个 偏移量,记录从不改动也不移动,所以偏移量按代理追加的顺序给记录排序。消费者从它提交的位置起,按偏移量递增读一个分区。因此,只要 生产者对一个键的记录按发送顺序被追加(一个生产者,而且重试不会打乱它的批次),消费者就按这个顺序看到该键的记录;崩溃后它从已提交 的偏移量继续,也不会打乱任何东西。跨分区则没有任何保证:消费多个分区的消费者按时机交错地拉取。在我们把“the whale and the sea and the ship and the whale”写入四个分区的例子里,“the”(位置 0、3、6、9)落在分区 2,“whale”(1、10)和“and”(2、5、8)落在分区 1。 先拉取分区 1 的消费者会在 the(0) 之前看到 whale(1)、and(2)、……、whale(10),于是“whale”排在“the”前面,这是唯一的生产者从未写过的 顺序;而每个键内部的顺序仍然正确。

  2. 水位线的延迟。 证明延迟为 L 的水位线恰好丢弃那些延迟超过 L 加上窗口余量的事件,并计算延迟服从指数分布时被丢弃的比例。

    解答

    取一个滚动窗口 [s, s + T),其中一个事件的事件时间为 e、延迟为 D(在 e + D 到达),称 σ = s + T − e ∈ (0, T] 为它的余量, 即它离窗口结束还有多远。把水位线理想化为 W(t) = t − L,就像数据源最新的事件时间与时钟同步前进时那样。窗口在 W 到达 s + T 时、也就 是处理时间 s + T + L 时触发,之后到达的事件被丢弃。所以事件被丢弃当且仅当 e + D > s + T + L,即 D > L + σ。(若允许延迟 A,窗口接受 事件直到 s + T + L + A,把 L 换成 L + A 即可。)若延迟服从均值为 μ 的指数分布,事件在窗口内均匀分布,则 σ 在 (0, T] 上均匀,丢弃的 比例为 (1/T)∫₀ᵀ e^(−(L+σ)/μ) dσ = (μ/T) e^(−L/μ) (1 − e^(−T/μ))。μ = 2 秒、T = 10 秒时为 0.1987 e^(−L/2):L = 0 时 19.9%,L = 2 时 7.3%,L = 5 时 1.6%,L = 10 时 0.13%。我们的模拟还让 5% 的事件再多延迟 20 到 60 秒;L ≤ 10 时它们全部被丢弃,因为 D ≥ 20 > L + σ。启发式水位线是“见过的最大事件时间减 L”,它比时钟落后一段时间 γ,即所见最新事件的“年龄”(这里平均 0.48 秒),而且 窗口在 W 越过窗口结束后的第一个到达时才触发,所以实际的延迟比 L 略大。拟合出额外的 0.7 秒,0.05 + 0.95 · 0.1987 e^(−(L+0.7)/2) 在 L = 0、1、2、5 秒时给出 18.3%、13.1%、9.9% 和 6.1%,实测为 17.7%、13.2%、10.0% 和 6.1%(3,000 个事件中的 530、397、301 和 182 个)。

  3. 屏障快照。 证明异步屏障快照给出一个一致割(第38部分),从而恢复后得到恰好一次的状态。

    解答

    设数据流图无环,通道先进先出,数据源可以重放。第 n 个检查点由两部分组成:每个数据源发出屏障 n 时的偏移量;每个算子在所有 输入上都收到屏障 n 之后(屏障先到的输入被暂时扣住,这就是对齐)、处理屏障之后的任何记录之前的状态。按拓扑顺序归纳:一个算子的快照 恰好反映它的输入上排在屏障 n 之前的记录,因为对齐使它不处理任何屏障之后的记录,而先进先出的通道会在屏障之前送达屏障前的一切。这些 输入记录中的每一条,都是上游算子在转发屏障 n 之前发出的,所以只来自记录下的偏移量之前的源记录;因此每个快照都是每个数据源同一个前缀 的函数。这个割是一致的:如果一个算子的状态反映了它收到的一条记录,发送者的快照就反映了已经发出它;而且拍快照时屏障之前的记录都已被 消费,没有通道里留着跨越这个割的记录,所以不需要保存通道状态。(对有环的图,Carbone 等人还记录回边上正在传输的记录。)恢复时,恢复 每个算子的状态,并把每个数据源倒回它的偏移量:偏移量之前的每条源记录通过快照恰好影响状态一次,之后的每条记录在重放中恰好影响状态 一次,所以恢复后的运行是同一输入的一次无故障运行(如果算子是确定性的,就是同一次运行)。在我们的工具里,3,032 个事件在偏移量 1,700 处崩溃,从 1,500 处的检查点恢复,重放 200 个事件,最终计数与从未出故障的运行相同;若倒回数据源却保留崩溃时的状态,这 200 个 事件就被计了两次。

  4. Dremel 的级别。 手工计算一个三层嵌套列的重复级别和定义级别,并由它们重建记录。

    解答

    取这样的记录:重复的 shelves,每个含重复的 books,每本书含重复的 tags;列为 shelves.books.tags(路径上有三个重复 字段,所以 r 和 d 都从 0 到 3)。记录 1 的书架 1 上有书 [sea, whale] 和 [ ],书架 2 上有书 [inn];记录 2 没有书架;记录 3 的书架 1 上没有书,书架 2 上有书 [York]。重复级别说明一个值在哪个重复字段上重复(0 为新记录,1 为新书架,2 为新书,3 为同一本书里的另一个 标签),定义级别说明三个字段中有几个存在。按顺序走遍这些记录,得到七个位置:(sea, 0, 3),(whale, 3, 3),空书 (null, 2, 2), (inn, 1, 3),没有书架的记录 (null, 0, 0),没有书的书架 (null, 0, 1),以及 (York, 1, 3)。重建时按顺序读这些三元组:r = 0 开始一条 新记录;若 d ≥ 1 且 r ≤ 1,打开一个新书架;若 d ≥ 2 且 r ≤ 2,在当前书架里打开一本新书;若 d = 3,把值追加到当前这本书。七个三元组 还原出 [[[sea, whale], [ ]], [[inn]]]、[ ] 和 [[ ], [[York]]],正是原来的三条记录,我们的 dremel 函数和这个读取过程都验证了这一点。

  5. 动手。 给我们的流处理器加上滑动窗口和允许延迟,并测量它必须保存的状态。

    解答

    解答要点。 在 run_windows 中,把每个事件分配给 sliding(et, size, step) 返回的每个窗口,而不是 tumbling 给出的那一个;按 (窗口,键)保存计数;水位线到达窗口结束时触发;在水位线越过“结束 + 允许延迟”之前,接受迟到事件(作为修正);到那一刻输出最终计数并 删除这个窗口的状态,而现在的工具从不删除。每个事件之后记录打开的窗口数和(窗口,键)条目数,并取最大值。一个窗口从它的第一个事件起 打开,直到处理时间大约为“结束 + L + A”,所以同时打开的窗口约为 (size + L + A)/step 个,每个至多每个键一个计数器。按这个思路在工具的 3,000 个事件上(三个键,10 秒窗口,L = 5 秒)写的草稿,重现了缓存中的滚动窗口结果(不允许延迟时丢弃 182 个;允许 60 秒延迟时 30 个 窗口全部精确),测得峰值为:不允许延迟时 2 个打开的窗口(6 个条目),允许时 8 个(24 个),对照 (10 + 5 + 60)/10 = 7.5;每 5 秒滑动 的窗口需要 4 个(10 个)和 16 个(46 个),对照 15,而且允许 60 秒延迟时 61 个窗口中有 60 个最终精确。状态随窗口大小加上允许延迟线性 增长,再除以步长。

  6. ★ 研究。 哪些窗口化的流连接能用低于窗口大小的线性空间(亚线性空间)精确维护?

    讨论。 尚未解决。对键取自很大值域、窗口为 w 个事件的两个流的等值连接,最坏情况下精确答案需要 Ω(w) 个字:一个新事件是否能连接, 取决于它的键是否出现在另一个流最近的 w 个事件中,而一个标准的通信复杂度论证(INDEX 问题)表明,记住这样一个集合需要与它成线性的空间。 在额外的结构下亚线性空间是可能的:键的值域很小(每个键保存一个计数);数据上的约束,例如有序或乱序有界,使状态可以提前丢弃(Babu、 Srivastava 和 Widom 研究过这类“k 约束”);或者输出只是连接的一个聚合。Arasu 等人(PODS 2002)刻画了在无界流上只需有界内存的 选择–投影–连接查询。好的答案应确定一个模型(基于时间还是基于计数的窗口,连接谓词,输出是每一个匹配还是一个聚合),对困难的类证明下界, 对其余的给出达到下界的算法,并划清两者的界线;仅对乱序有界的等值连接,或对有序键上的带状连接给出刻画,就已经是新的。

Build the film

python -m videos.cs.cs46.compute        # the part's numbers, into .cache/cs46
python tools/build.py cs46                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs46 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs46. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs46.compute
python -m unittest tests.test_cs46_data
python tools/build.py cs46