AlgoViz

Lambda architecture

medium 27 min

Lambda architecture sends every event down two roads.

Video lesson · Chapter 1 of 5

Two scorekeepers at the stadium

0:00 / 4:16

Lambda architecture in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Lambda architecture is a way to give answers that are both complete and fresh. The same events go into two pipelines. The batch layer stores every raw event and regularly computes its results again from all of them. The speed layer computes results for the events that came after the last batch run. The serving layer answers a question by adding both.

It has nothing to do with AWS Lambda, which runs functions, or with lambda expressions in a programming language. Only the Greek letter is the same.

Why it exists

Around 2011 the choice was hard. Batch systems gave exact results hours later. Streaming systems were quick, but could lose or double events. Using both, and letting the exact one correct the quick one, gave the advantages of each.

The second reason is people. Programs have bugs. If raw events are never changed, any wrong result can be computed again. Nathan Marz, who described the design, called this human fault-tolerance.

A short history

  1. October 2011

    Nathan Marz publishes the article How to beat the CAP theorem. It describes a batch layer on immutable data and a realtime layer that covers the last hours and is overridden by the batch layer.

  2. July 2014

    Jay Kreps publishes Questioning the Lambda Architecture. The article argues that keeping the same logic working in two complex systems is very hard, and proposes to use only the stream.

  3. 2014

    The Summingbird paper from Twitter at VLDB presents a framework for integrating batch and online MapReduce computations, so that one program can serve both layers.

  4. 2015

    The Dataflow Model paper at VLDB describes one model for bounded and unbounded data, which weakens the reason to keep two pipelines.

Words to know

Master data set
All raw events, appended and never changed.
Batch view
Results computed from the master data, ready to be read.
Live view
The speed layer's results for the newest events. Also called real-time view.
Cutoff
The moment up to which the batch view covers the data.
Recomputation
Building a view again from the start.
Human fault-tolerance
Being able to recover from mistakes that people make.
Mergeable
Two partial results can be combined into the right total.

How it works

Step through the idea, or press Play.

Step 1 of 3

Batch layer. All raw events, exact results, hours old

Understand it

Start here

The bake sale

Asha sells cupcakes at a school bake sale. Parents keep asking how many were sold so far. A quick answer is wanted now, and an exact one for the school's books.

A whiteboard and a ledger
Sold so farSat: 0Sale slips

If the board still showed Saturday's sales on Sunday, they would be counted twice. Wiping it at the right moment is the delicate part.

The idea

Three layers

Two roads, one answer

Events enter a Kafka log. From there they go two ways. In the batch layer they are stored as master data, recomputed by Spark and written to a batch view. In the speed layer a Flink job handles new events and writes a live view. The serving service reads both views and adds them.
The products are examples. What matters is that both roads start from the same events.
  • Batch layer

    Complete and exact views from all the data. Slow: nightly or hourly.

  • Speed layer

    Views of the newest events within seconds. Temporary, and may be approximate.

  • Immutable data

    The master data is only appended to. A correction is a new event.

  • Recomputation

    Views are thrown away and built again from the start.

Batch layer

All the data, again and again

PartWhat it doesProperties
Master dataStores all raw events ever received, on HDFS or object storageAppend only, the source of truth
Batch jobReads it with MapReduce or a dataflow engineSame code each time, can be repeated
Batch viewHolds totals and indexes ready to be readReplaced as a whole by each run

One batch run

  1. 1

    Read

    All events before the cutoff from the master data.

  2. 2

    Compute

    Filter, group and count in parallel.

  3. 3

    Write

    The new view next to the old one.

  4. 4

    Swap

    The view and its cutoff together, in one step.

What a full run costs

3 years×365×20 GB100 machines×100 MB/s=21.9 TB10 GB/s=2,190 s≈37 min\frac{3 \text{ years} \times 365 \times 20 \text{ GB}}{100 \text{ machines} \times 100 \text{ MB/s}} = \frac{21.9 \text{ TB}}{10 \text{ GB/s}} = 2{,}190\text{ s} \approx 37\text{ min}
Assumed sizes, reading only. Shuffling and writing come on top.

Speed layer

Only the gap

The speed layer covers the time from the last cutoff to now. It uses stream processing with windows and gives results within seconds. It may use approximate algorithms, because the batch layer overrides its results later. Marz calls this property eventual accuracy.

Who covers which time

When the next batch view arrives, the boundary moves one day, and the live view forgets that day.

How long is the gap?

gapmax=interval+delay of the run=24 h+3 h=27 h\text{gap}_{max} = \text{interval} + \text{delay of the run} = 24\text{ h} + 3\text{ h} = 27\text{ h}
A run for 00:00 that is ready at 03:00. If one run fails, the gap is 51 hours, so give the live view room for three days.

Serving layer

Adding the two

Python
def query(day_totals, cutoff, live_events):    """Batch before the cutoff, live from the cutoff on."""    return sum(day_totals.values()) + sum(n for t, n in live_events if t >= cutoff)print(query({"Mon": 800}, cutoff=24, live_events=[(23, 5), (25, 50), (30, 230)]))
Hours since Monday 00:00. The live event at hour 23 is before the cutoff and already in Monday's total, so it is left out: 800 + 50 + 230 = 1080.
Edit and run it in your browser
QuestionRead from
Last monthBatch view only
The last hourLive view only
All time until nowBoth, added

The batch run and the swap

Events between 00:00 and 02:00 are in the live view only. Cutting at 02:00 would lose them.

Mistakes

Repair by computing again

A wrong number was reported

Late events are handled in the same spirit. An event that arrives two days late is appended to the master data. If the job selects by event time and recomputes old days, it lands in the right place without special code.

Trade-offs

Strengths and weaknesses

Advantages

  • Accurate and fresh together
  • Raw data that cannot be damaged by a bug
  • Can recompute when an error is found
  • Late data is included by the next run
  • The speed layer may fail and be repaired

Challenges

  • The same logic in batch and in stream
  • Two systems to operate
  • A bug can be in either, or in the merge
  • The boundary must be exact
  • More machines and storage

The duplication problem

StepBatch codeStream code
Readfiles of a daya topic, for ever
Filtera filter on rowsa filter on events
Countmap to 1, reduce by keykey by, window, sum
Late datanot specialwatermark, corrections
Finishreplace the viewupdate rows
Same meaning, two frameworks. Every change of a rule must be made, tested and released twice.

Practice

Good habits

Do

  • Keep the master data unchanged
  • Design views so that they can be rebuilt
  • Be careful with expiry
  • Make operations idempotent
  • Monitor both pipelines

Do not

  • Let the two codes drift apart
  • Ignore late events
  • Leave merged queries untested
  • Assume the stream counts exactly once
  • Run it without alerts

Alternatives

Do you need two roads?

Today a stream processor with checkpoints and event time can be exact by itself. Then the second road has less to add. Kappa architecture drops the batch layer and replays the log when something must be recomputed.

ChoiceIdeaFits when
LambdaBatch and stream, mergedThe stream is approximate, or history is far too big to replay
KappaStream only, replay the logOne exact stream job, and the log is long enough
One engine, two modesThe same program over files and topicsBeam or Flink fits your logic
Micro-batch onlyA small batch every few minutesMinutes are fresh enough

Is Lambda worth it?

Numbers

A first estimate

100 million events a day, 200 bytes each (assumed)

QuestionArithmeticAnswer
Average and peak rate100,000,000 / 100,000, then x 31,000 and 3,000 a second
Master data a day100,000,000 x 200 bytes20 GB
Master data in 3 years20 GB x 1,09521.9 TB
Live view, 3 days of minutes, 10,000 keys4,320 x 10,000 x 50 bytes2.16 GB
Batch view, 3 years of days, 10,000 keys1,095 x 10,000 x 50 bytesabout 550 MB

Summary

The whole topic in one minute.

Lambda sends every event to a batch layer and a speed layer. The batch layer is slow and exact, because it starts from all raw events each time. The speed layer fills the gap since the last batch run. A query adds the batch view and the live view at a stored cutoff.

Its strength is that mistakes are repaired by computing again. Its weakness is two implementations of the same rules. Modern stream processors and engines that handle both modes often make one pipeline enough, but the immutable raw data remains a good idea everywhere.

  • Batch layer: all raw events, exact, late.
  • Speed layer: only since the cutoff, quick, temporary.
  • Serving layer: batch view plus live view.
  • The cutoff is the last time the batch run read, not when it ended.
  • Immutable raw data makes mistakes repairable.
  • The price is two codes and two systems.

Sources