The Cloud
What is under a computer rented by the second, and what decides how much of it to rent?
The part opens with McCarthy's 1961 forecast of computing as a public utility, which S3 and EC2 made real in 2006, and with the Job's bill: $0.00160 on one on-demand server, $0.00003 on sixteen functions. It then descends the hierarchy, where every layer is a scheduling problem and a failure domain. A warehouse-scale computer is limited by watts and fails about 1.8 servers a day in a fleet of 2,000; virtual machines shrink to Firecracker's microVMs, and containers are namespaces, cgroups and content-addressed layers. Kubernetes is a reconciliation loop, and a level-triggered controller recovers from lost events that leave an edge-triggered one a replica short for good. Scheduling is bin packing, NP-hard by way of partition, with first fit decreasing within 1% of the exact optimum on random instances and next fit provably within a factor of 2. The part turns on autoscaling as control: a proportional controller acting on a delayed measurement is stable only below a gain of 2 cos(d pi / (2d + 1)), and Erlang C gives the square-root staffing behind the cloud's economy of scale. Object storage earns its nines from erasure coding and a Markov chain of failure and repair, and the part ends with networking, infrastructure as code, noisy neighbours, the price of spot capacity, and a frontier where correlated rack failures cut 13.3 nines to 7.
What you need. Exponential and Poisson distributions for the queueing and durability chapters; no cloud account or vendor knowledge is assumed.
- Mathematics, ideas and history
- warehouse-scale computers, microVMs, containers, Kubernetes reconciliation, bin-packing schedulers, autoscaling as control, Erlang C, object-storage durability (MTTDL), IaC, cost
- What we build or compute
- the Job's bill in dollars
What you will be able to do
Degree
- Name the layers from region to container and say what fails together at each.
- Pack a list of containers by next fit, first fit and first fit decreasing, and compare each with the lower bound from the total size.
- Explain why a reconciliation loop that compares desired with observed state survives lost events.
Graduate
- Prove that next fit uses at most 2 OPT - 1 bins, and show by reduction from partition that bin packing is NP-hard.
- Derive the stability limit of a proportional autoscaler with a measurement delay.
- Derive Erlang C from the M/M/c chain, and the mean time to data loss from the chain of failure and repair.
Research
- Compute how correlated rack failures change an erasure code's durability, and say which independence assumption fails.
- State what learning-augmented algorithms promise for online scheduling with predicted sizes and lifetimes, and what is open.
Industry
- Choose between functions and servers from a request rate, and find the break-even rate.
- Set a checkpoint interval for a job on spot capacity from the interruption rate and the checkpoint's cost.
- Read an infrastructure plan as a diff, and decide whether to apply or adopt a drifted resource.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 20 min · Graduate 50 min · Research 52 min · Industry 39 min.
- 0Computing as a utilityDegree2 min
- 1The warehouse-scale computerDegree4 min
- 2Virtual machines, shrunkGraduate3 min
- 3ContainersDegree3 min
- 4Orchestration and reconciliationDegree4 min
- 5Scheduling as bin packingDegree4 min
- 6Autoscaling as controlGraduate4 min
- 7ServerlessIndustry4 min
- 8Object storage and eleven ninesGraduate4 min
- 9Cloud networkingIndustry4 min
- 10Infrastructure as codeIndustry5 min
- 11Neighbours, regions and failure domainsIndustry3 min
- 12Cost, carbon, and the Job's billIndustry3 min
- 13Frontier: scheduling, isolation and energyResearch2 min
- 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.
Computing as a utilityDegree2 min
In 1961, at a celebration of MIT's centennial, John McCarthy predicted that computing might one day be organized as a public utility, like the telephone system. Time-sharing came first, many terminals on one mainframe. Then decades in which a company bought its servers, or rented space for them in someone else's building. In 2006 Amazon began selling storage by the gigabyte-month, with S3, and computers by the hour, with EC2. Today a computer can be rented by the second, and a function can be billed per request.
Under the word cloud is a physical hierarchy. A region is a few buildings some distance apart. A building draws tens of megawatts and holds tens of thousands of servers. A rack holds a few dozen of them, sharing a switch and a power feed. A server is sliced into virtual machines, and a virtual machine runs containers, which are processes with walls around them. Every layer is a scheduling problem and a failure domain, and this part goes down through all of them.
And the Job gets a price. Counting the words of our thirty novels takes 1.4 seconds on one core of the machine that renders this video. Rented as a server at Amazon's list price, billed by the second with a one-minute minimum, that costs about 0.16 cents. At a typical spot discount, about a third of that. Split across sixteen functions billed by the gigabyte-second, it costs about three thousandths of a cent. The prices are list prices for one region, dated, and they leave things out. But the shape is the point: in the cloud, every design decision in this series has a bill attached.
1The warehouse-scale computerDegree4 min
In 2009 Luiz Barroso and Urs Hölzle gave the modern datacentre its name: a warehouse-scale computer. The building is one computer: tens of thousands of servers, one owner, a few very large services programmed as a whole. Its unit is the rack, a few dozen servers under a switch, sharing a power feed, and racks stand in long rows. The rows face each other in pairs. Cold air is delivered between their fronts; the servers' fans pull it through, and hot air leaves from the backs into a separate, contained aisle that returns it to the cooling units.
Under the floor plan is a power plan. Electricity from the grid is stepped down by transformers, then passes through an uninterruptible power supply, power distribution units, the rack, and each server's own supply. Every conversion loses a little as heat. If the grid fails, batteries carry the load for the seconds until diesel generators start. A building is designed for a fixed power, and its transformers, generators and cooling all scale with it, so the scarce resource is watts, not floor space. And because thousands of servers almost never peak at once, as Xiaobo Fan, Wolf-Dietrich Weber and Luiz Barroso measured in 2007, operators install more servers than the ratings allow, and cap power when the total comes too close.
Power also explains a quieter waste. In 2007 Barroso and Hölzle observed that servers spend most of their time between ten and fifty percent busy, yet an idle server drew about half its peak power. Draw it as a straight line, from half power idle to full power flat out. At thirty percent busy the server draws 65 percent of its peak, and does less than half the work per watt it manages flat out. Their remedy was energy proportionality, power that falls with load, like the dashed line. Servers have improved, but idle is still far from free.
The building has an overhead too. Power usage effectiveness, defined by The Green Grid in 2007, is the power entering the building divided by the power reaching the computing equipment; one would be perfect. The Uptime Institute's surveys put the industry average at about two and a half in 2007, and about one point six in 2023. Google reported one point one for its fleet in 2023. At two and a half, sixty percent of the electricity never reached a computer; at one point one, nine percent. But the ratio measures the building, not the work: an idle server in an efficient building is still idle.
At this scale, failure stops being an event and becomes a rate. Here are two thousand servers in fifty racks, each failing on average once in three years: nearly two failures a day. Watch a month go by; the software around each red server has already moved on. Failures also come in groups. When a rack's switch or power feed fails, all forty servers vanish at once, and likewise for a power unit, a cooling zone, a building. These nested failure domains decide where copies may live. Part 34 met disks replaced at two to four percent a year, and Part 39 a cluster's first year. So recovery is designed in: chapter eight spreads storage across failure domains, and chapter eleven spreads services across zones.
2Virtual machines, shrunkGraduate3 min
Part 32 built a hypervisor by trap and emulate. On Linux today the work is split in two. KVM, in the kernel since 2007, uses the processor's virtualization mode: a guest's code runs directly on the processor, and only its exits come to the kernel. Everything else a guest expects of a machine, disks, network cards, clock, firmware, is pretended by an ordinary user process, the virtual machine monitor; the classic one is QEMU, begun by Fabrice Bellard in 2003. When the guest touches a device, it exits to KVM, KVM hands the access to the monitor, and the monitor emulates the device and resumes the guest.
That monitor is where the weight is. A general-purpose monitor can pretend to be almost any PC: firmware, a PCI bus, graphics, USB, sound, many disk controllers and network cards, even a floppy drive. Each is code that reads values a hostile guest controls. In 2015 the bug called VENOM, in QEMU's emulated floppy controller, let a guest break out to the host, on servers that had never seen a floppy. Amazon's Firecracker, open source since 2018 and described by Alexandru Agache and colleagues in 2020, keeps five devices: a virtio network card and disk, a socket to the host, a serial console, and a scrap of keyboard controller, used only to stop the machine. It began from Google's crosvm, and is written in Rust.
A general-purpose virtual machine runs firmware, a boot loader, a kernel that probes a whole PC's worth of hardware, and an init system, and takes seconds. On that scale a microVM is a sliver. Magnify it: the monitor loads the kernel straight into memory, with no firmware; the kernel finds a handful of virtio devices; and a minimal init starts the user's code. The Firecracker project reports as little as a hundred and twenty-five milliseconds to user code, under five mebibytes of memory overhead each, and up to a hundred and fifty new microVMs a second on one host. Faster still: since 2022, Lambda's SnapStart skips booting, restoring a snapshot of a machine that booted earlier.
Why give a function a whole virtual machine? When Lambda launched, it isolated customers from each other with virtualization, and one customer's functions from each other with containers, so every customer needed virtual machines of their own. With Firecracker, every function gets its own microVM, and functions of different customers share a host safely, densely packed, a bin-packing problem for chapter five. The walls are layered. Code that escapes a function must still break the guest kernel; then KVM or the small device model; and then the Firecracker process itself, which a jailer starts in an empty file tree, in its own namespaces and control groups, behind a filter that allows only the few system calls it needs.
3ContainersDegree3 min
Part 32 took a container apart. It is a group of ordinary processes on one kernel. Namespaces decide what they can see: their own process numbers, so that the first is number one, their own host name, network interfaces and file tree. Outside, the host sees the same process as number four thousand two hundred and forty-two. Control groups decide how much the processes may use, and an image provides the files they run.
Control groups turn limits into arithmetic. This group may use fifty thousand microseconds of processor time in every period of a hundred thousand: half a processor. A busy process inside runs for fifty milliseconds, and then the scheduler stops it until the next period begins. A request that arrives just then waits, for no reason visible inside the container: a limit has become a tail latency, as in Part 39. Memory is harsher. The group may hold two hundred and fifty-six mebibytes. When it needs more and the kernel cannot reclaim enough, the out-of-memory killer ends a process in the group, and chapter four's orchestrator restarts it. The same files limit the number of processes and the rate of disk traffic.
The files come from an image, and an image is content-addressed, like Part 41's git objects. Each Dockerfile step that writes files makes a layer: an archive of exactly what it added or changed, named by the SHA-256 hash of its bytes. A manifest lists the layers' names in order, and the image is named by the manifest's hash, so one name vouches for every byte: a Merkle tree again. Change one line of the application and rebuild. Only the last layer has new contents, so only it and the manifest get new names; the layers below come from the build cache. That is why a Dockerfile copies the code last: a step reruns only when its inputs change, as in Part 41's build graphs.
How do the layers become one file tree? Linux's overlay file system, merged in 2014, stacks them, and the container sees their union. Where two layers hold the same path, the higher one wins. Reading a file falls through to the highest layer that has it. On top sits one writable layer for each container. The first write to a file copies it up from below, and changes the copy: Part 32's copy-on-write, applied to files. Deleting a file cannot change a read-only layer, so the upper layer records a whiteout that hides it. A hundred containers from one image share the read-only layers, on disk and in the page cache, and each pays only for what it writes.
4Orchestration and reconciliationDegree4 min
Google ran its services on a cluster manager called Borg for more than a decade before Abhishek Verma and his colleagues described it in 2015. A Borg cell is a set of machines managed as one, about ten thousand in the median cell. A Borgmaster, replicated five times and kept consistent with Paxos, decides where tasks run, and an agent on every machine, the Borglet, starts them and reports back. Kubernetes, open-sourced by Google in 2014, was built by people who had worked on Borg, and its pieces map onto Borg's almost one for one: a pod is a task, and a kubelet is a Borglet.
The idea that makes this work is to say what you want, not how to get it. An imperative script says: start the web server on machine three, then seven, then two. If machine seven dies halfway, the script cannot tell what state the world is in. A declarative specification says only: there should be five replicas of this image. The system stores that goal, observes what is running, and acts on the difference. Because the goal is written down, and not the steps, any controller, after any crash, can look again and work out what remains.
Each kind of object has a controller, and each controller is the same small loop. Read what is wanted. Observe what is there. Too few pods: start one. Too many: stop one. Sleep, and repeat. Here five replicas are running, and two crash. On its next pass the loop sees three where five are wanted, and starts replacements until the counts agree. The loop never asks what happened, only what is different now. That makes it idempotent: running it twice, or restarting it after a crash, does no harm.
There are two ways to write a controller, and the difference shows when messages go astray. We simulated five replicas whose pods crash two at a time, at steps twelve and twenty-five. An edge-triggered controller reacts to events: each pod died message starts a replacement. But some messages are dropped. At the second crash one is lost, and the controller stays at four replicas forever, because nothing makes it look again. A level-triggered controller compares the goal with the world on every pass. It starts slowly, one pod per step, but after each crash it is short for a single step, whatever was lost. Kubernetes' controllers work this way: an event is only a hint to look sooner.
All of this rests on one durable record of what is wanted. You write the goal to the API server, the only component that talks to storage. It keeps every object in etcd, a key-value store replicated by Raft, from Part 38, so every write is committed by a majority: three members survive one failure, five survive two. Controllers and node agents never talk to one another; each watches the API server for the objects it cares about. Every object carries a version, so an update based on a stale read is refused, like a compare-and-swap. Even the scheduler is a controller: it watches for pods with no machine, and binds each to a node. How it chooses is the next chapter.
5Scheduling as bin packingDegree4 min
Once a pod has no machine, the scheduler must choose one. This is bin packing: items of sizes between zero and one, bins of size one, and as few bins as possible. The simplest sensible rule is first fit: each item goes into the first machine with room. Here it fills three machines exactly, and the fourth can be switched off. A real scheduler filters out the machines that cannot take the container, then scores the rest: one rule spreads work out, another packs machines full.
Recall partition, from Part 26: can some numbers be split into two halves with equal sums? Divide each by half the total, and ask whether the items fit in two bins. Three, one, one, two, two and one total ten; three, one and one make five, and so do two, two and one. Three, three, three and one also total ten, but nothing makes five: a third bin is needed. So a fast packer would solve partition, and bin packing is NP-hard. Telling two bins from three is already hard, so no fast algorithm can promise better than one and a half times the optimum, unless P equals NP.
We packed random instances with four classic rules, and compared each with the exact optimum, found by branch and bound. Next fit, which keeps only one machine open, used about a quarter more machines than needed on average, and half as many again at worst. First fit and best fit, which look back at every machine, came within about eight percent. First fit decreasing, which sorts the work largest first, came within one percent. Sorting wins, because large items placed early leave gaps that small ones can fill.
A proof says how badly a rule can do. Give next fit halves alternating with tiny items. Each half closes the machine before it, so sixteen items take eight machines; the optimum pairs the halves and gathers the tiny items, in five. As the family grows, the ratio climbs towards two. It can never pass two: any two neighbouring machines hold more than one machine's worth, or the second's first item would have fitted. For first fit decreasing, David Johnson proved in 1973 a bound of eleven ninths of the optimum plus four; in 2007 György Dósa found the tight constant, six ninths.
Real containers ask for more than one thing. Our two hundred containers each need some processor and some memory, and a machine is full when either runs out: this is vector bin packing. The total demand says at least thirty-nine machines. First fit, sorting by each job's larger demand, used forty-three, about nine-tenths busy in both resources. Sorted by processor alone, it used sixty-three, about sixty percent busy: the memory-hungry jobs came last, when machines had memory but no processor to spare. Packing well means mixing the two kinds.
The other half of scheduling is deciding who gives way. Borg gives every job a priority: production work that serves users, and batch work that can wait. Here a full machine of batch tasks meets a production task. The scheduler preempts the lowest-priority task, which goes back into the queue to be placed elsewhere; Kubernetes' priority classes do the same. Batch work also fills capacity that production reserved but is not using. The payoff: in the Borg paper, keeping the two kinds on separate machines would have needed twenty to thirty percent more of them.
6Autoscaling as controlGraduate4 min
An autoscaler watches how busy the servers are, and adds or removes some: a feedback loop. Load arrives; the servers share it, which sets their utilization; the controller measures that, and starts or stops servers. But the measurement is late, and a new server takes time to boot, so the controller acts on the past. Kubernetes' horizontal pod autoscaler multiplies the replicas by measured over target utilization, rounded up. Ours moves a fraction K of the way, from a measurement d steps old. K equal to one is Kubernetes' rule.
We gave it a load that jumps from forty to a hundred requests a second. At sixty percent utilization, the right size is about seventeen servers. With a delay of one step and a gain of three tenths, it overshoots to eighteen, and settles. With a three-step delay, a gain of two tenths still settles, after overshooting to twenty-five. At one half, it never settles, swinging between about five servers and a hundred. At a gain of one, Kubernetes' rule, it slams between one server and the quota of two hundred. Only the gain changed.
Here is why. Near the right size, each step corrects the error by K times the error as it was d steps ago. So once the fleet is big enough, the controller keeps adding, because it acts on old measurements. The error dies away only while K stays below twice the cosine of d pi over two d plus one: below two with no delay, below one with one step, and below about forty-five hundredths with three. Our four runs land exactly where the curve predicts. As Maxwell found for steam-engine governors in 1868, the more a loop lags, the gentler it must be.
Queueing theory supplies the target. Model the pool as Part 31's queue, now with c servers. Requests arrive at rate lambda; with k servers busy they finish at k times mu. Balancing the flow across each step gives a to the k over k factorial up to c, then a geometric tail with ratio rho, the load per server. Summing the tail gives Agner Erlang's formula of 1917 for the chance of waiting, and the mean wait follows. Two servers with one erlang of load: a request waits a third of the time.
Now size pools of very different scales with one promise: a short mean wait, and at most one request in five waiting at all. Ten erlangs of load need fourteen servers, only seventy-one percent busy. A thousand erlangs need one thousand and thirty-four, ninety-seven percent busy. The spare capacity grows like the square root of the load: Halfin and Whitt's square-root staffing, from 1981. So one big shared pool needs far fewer idle servers, in proportion, than many small ones. That is the economy of scale behind the cloud itself.
Even a well-tuned reactive loop is late. It sees the load after a measurement window, and its servers arrive a boot time after that, so every rising morning it runs short. But most load repeats, by the day and by the week. Predictive scaling, which the big clouds now offer, forecasts the next hours from past weeks and starts machines a boot time ahead. The reactive loop stays as a backstop for surprises. The next chapter shrinks the boot itself, and Part 50 returns to planning for the peaks.
7ServerlessIndustry4 min
In 2014 Amazon launched Lambda, and with it a new contract. You do not rent a machine at all. You upload a function and name the events that should run it: a web request, a file arriving in storage, a message on a queue, a timer. For each event the platform finds or starts an instance, runs the function, and bills the milliseconds it ran. With no events there are no instances and no bill: it scales to zero. The price of that freedom is statelessness. An instance may vanish at any moment, so anything that must last goes to storage or a database, and functions talk to each other through them. Jonas and colleagues at Berkeley, in 2019, predicted that this style would come to dominate cloud computing, and catalogued these limits.
What does the per-millisecond bill buy? A server is billed for every second it exists, busy or idle. A function is billed only while it runs. At Amazon's 2024 list prices, a hundred milliseconds at half a gigabyte costs eighty-three cents per million calls in compute, plus twenty cents per million in request fees. Now keep a small server completely busy, two hundred requests every second. Its hourly price is spread over seven hundred and twenty thousand requests: about thirteen cents per million. So a function costs nearly eight times as much per request as a busy server. It wins whenever the server would be idle more than about eighty-seven percent of the time, below about twenty-six requests a second, the break-even chapter twelve plots. Serverless is a bet on low utilization.
The catch is the first request. When an event arrives and no instance is warm, the platform must start one: boot a micro-VM, as in chapter two, start the language runtime, and run the function's own initialization, loading its libraries. That is a cold start, and it can take far longer than the request itself. So platforms keep an instance alive for a while after each request. With a short keep-alive, six of these twelve requests start cold. With a longer one, only two do, but memory sits reserved and idle almost all hour, and somebody pays for it. Shahrad and colleagues, studying Azure Functions in 2020, found that invocation rates differ between applications by many orders of magnitude, so no single timeout suits them all; their policy learns each application's typical idle times. Users fight back, paying to keep instances warm, or restoring them from snapshots.
How many instances does a function need? Part 31's law of John Little answers: the number in flight is the arrival rate times the time each request spends. At the break-even rate of about twenty-six requests a second, each lasting a tenth of a second, that is between two and three instances on average, and more in a burst. At a thousand requests a second it is a hundred. Platforms cap this. Amazon's default is a thousand concurrent executions per account in each region, so a hundred-millisecond function tops out near ten thousand requests a second, and requests beyond the cap are throttled, refused for the caller to retry. An invocation runs fifteen minutes at most. And the limit that bites first is often behind the function: a thousand instances, each with its own connection, can swamp a database that expected a few dozen.
8Object storage and eleven ninesGraduate4 min
Clouds sell storage in three shapes. Block storage is a disk: numbered blocks, read and written in place, attached to one machine; Part 34's disk, over the network. File storage adds names in a hierarchy, and lets programs open a file, seek and overwrite bytes in the middle, with locking for sharing. Object storage gives most of that up. A bucket maps keys to whole objects, which you put, get or delete over HTTP. Nothing is edited in place, and the slashes in a key are just characters. In return it scales almost without limit, and it is cheap: about two point three cents a gigabyte a month, at Amazon's 2024 list price.
What does a read see? A writer's put succeeds, and then a reader asks for the object. For its first fourteen years, S3 showed a brand-new key at once in most cases, but an overwrite or delete could take a while to appear: eventual consistency, from Part 39. In December 2020, Amazon made every read strongly consistent: once a put or delete succeeds, every later get and listing reflects it. Each update to a key is atomic, the later of two racing writers wins, and there are no transactions across keys. Part 46 builds whole tables on exactly these guarantees.
How can an object outlive its disks? Cut it into ten data fragments and compute four of parity with a Reed–Solomon code, from Part 28: any ten of the fourteen rebuild it. Then scatter the fragments across failure domains, here two to a rack in seven racks, so that no disk, rack or power feed holds too many. A disk fails; the system rebuilds its fragment elsewhere from ten survivors. Even a whole rack lost, with two more disks, leaves ten, and the object survives. Three full copies tolerate only two losses and store three times the data; this code tolerates four, at one point four times.
How long until data is lost? Model it as a Markov chain whose state counts the failed fragments. Each live one fails at rate lambda, two percent a year here, independently; a failed one is repaired at rate mu, in about a day. For three copies, the chain moves right at three lambda, then two lambda, then lambda, and the last state loses the data. From each damaged state, repair pulls it back. The expected time to climb each step, allowing for repairs that send us back, obeys this recurrence, and the mean time to data loss is the sum of the steps. For three copies: about 2.7 billion years. A simulation of the same chain, with exaggerated rates, agrees within two percent.
Now compare schemes. One copy is lost with a two percent chance a year: under two nines. Each failure a scheme can absorb multiplies the mean time by thousands, because a repair takes a day and a disk lasts decades: two copies give about five point seven nines, three about nine point four. Erasure codes do better for less: six data fragments plus three of parity reach eleven nines, at one and a half times the data. Amazon designs S3 for eleven nines: store ten million objects, and expect to lose one about every ten thousand years. But all of this assumes independent failures. Chapter thirteen shows what happens when they are not.
9Cloud networkingIndustry4 min
Every tenant in the warehouse wants what looks like its own private network. A virtual private cloud gives it one: an address range of its choosing, here ten dot zero dot zero dot zero slash sixteen in Part 36's notation, cut into subnets, one in each zone. A route table decides where packets go: anything inside the range stays local, and everything else goes to a gateway to the internet. Security groups are firewalls attached to each machine's virtual network card. They are stateful, so the reply to an allowed connection is allowed back. None of these wires exists. Two tenants can both choose ten dot zero dot one dot five, on the same physical network, and never see each other's packets. How?
The answer is encapsulation, Part 36's idea of a packet carried inside another. A virtual machine sends an ordinary packet, from ten dot zero dot one dot five to ten dot zero dot two dot seven. Those addresses mean nothing to the physical network. The host's virtual switch looks up where that destination lives: for this tenant, it is a virtual machine on another physical host. So it wraps the packet in a new one, addressed to that host, with a small header naming the tenant's network. In the VXLAN standard of 2014 that header is eight bytes, with a twenty-four-bit network number, room for about sixteen million networks. The receiving host unwraps it and hands it to the right tenant's machine. Every packet carries about fifty extra bytes, which is why such networks often allow slightly smaller packets. The mapping is the control plane, kept true by controllers like chapter four's. Amazon runs the data path on its own network cards; Google in software on every host.
A service needs one address in front of many machines. A managed load balancer is that address. It spreads connections across healthy backends, checks each one's health, and stops sending new work to any that fail. It can balance by connection, at layer four, or read each HTTP request, at layer seven. Google's Maglev, described in 2016, does this in software on ordinary machines, hashing each connection so that its packets keep reaching the same backend even as balancers come and go. To go global, clouds use anycast. The same address is announced, through BGP, from many sites at once, and the internet's routers carry each client to whichever is nearest by their routing. The DNS root servers and content delivery networks work this way, and Part 48 builds the rest.
Finally, the line on the bill that surprises people. Moving data into a cloud is free. Moving it out to the internet, at Amazon's 2024 list price, costs nine cents a gigabyte, about ninety dollars a terabyte before volume discounts. Traffic between zones is billed too. Compare storing it, at two point three cents a gigabyte a month. Sending an object out once costs as much as keeping it for nearly four months. Our thirty novels, twenty-five megabytes, would cost about a fifth of a cent to download: harmless for one reader, not for millions. So data has gravity. Computation moves to where the data is, caches near the users absorb repeated downloads, as Part 48 will show, and the cost of leaving is one reason customers stay.
10Infrastructure as codeIndustry5 min
Cloud resources can be made by hand, by clicking through a web console. A network, then a subnet inside it, then a database. It works once. But nobody can say afterwards who clicked what, and nobody can build the same thing again in another region. Infrastructure as code writes the desired state down instead: every network, database and service, with its settings and the other resources it uses, in a file. The file lives in version control, so a change to production is a commit: it gets a plan, a review and an apply, like any other change to code. Mark Burgess's CFEngine did this for the configuration of machines in 1993; CloudFormation in 2011 and Terraform in 2014 did it for whole clouds.
How does a tool turn that file into a cloud? It compares two descriptions. On one side, what exists: Terraform keeps a state file of everything it has made, and refreshes it from the cloud's own interface. On the other, what the code declares. Match them by name. The network and the subnet agree, so nothing happens to them. The database exists but is too small, so it is updated. The queue and the service are declared but missing, so they are created. And the old cache exists but is no longer declared, so it is destroyed. That diff is the plan: two to add, one to change, one to destroy. It is printed and reviewed before anything is touched, and a line that says destroy next to a database is exactly what reviewers look for.
The plan says what to do, but not in what order. The references in the code say that: the service uses the subnet, the database and the queue; the database lives in the subnet; the subnet in the network. They form a directed acyclic graph. The tool applies changes in topological order, the algorithm of Part 18, so that nothing is created before what it needs. First the database grows; then the queue appears; only then the service, which uses both. Destroys go the other way, each resource before what it uses, and our planner runs them after everything else, so the old cache goes last. And because the database and the queue do not depend on each other, they can be changed at the same time. It is Part 41's build system again, with machines and networks where the files were.
Code and cloud agree only until someone changes the cloud directly. After apply, all three agree: the code, the state file and the real database. Then, during an incident, someone makes the database bigger by hand, in the console. The cloud has drifted from the code, and nothing says so. The next plan refreshes its state from the cloud, finds the difference, and proposes to undo it: a change nobody wrote. Someone must decide: apply, and put it back, or edit the code to keep it. Teams run the plan on a schedule and alert on any difference. A Kubernetes controller, from chapter four, is the same idea run without stopping: it reconciles the level, again and again, and drift lasts seconds.
Drift has a deeper cure: never change a running machine at all. A server that is patched in place collects history. One got patch seven and an edit by hand; its twin got patch eight and a hotfix. Both are called web servers, and no two are the same: snowflakes, that nobody could build again. Immutable infrastructure bakes everything into an image, and every machine starts from it unchanged. To change anything, build a new image, start new machines from it, and retire the old ones, one at a time. To roll back, point at the old image again. Because images are content-addressed, as in chapter three and Part 41, a name means exactly one set of bytes, and every machine started from it is the same.
11Neighbours, regions and failure domainsIndustry3 min
A virtual machine gets its own cores and memory, but not everything on the chip is divided. Here two tenants share one processor. Each has two cores with private caches; the last-level cache and the memory bus are shared, and tenant A's working set fits. Then tenant B streams through gigabytes. Its lines push A's out of the shared cache, Part 9's misses return, and A slows down although A changed nothing: a noisy neighbour. Newer processors can divide these too. Intel's cache allocation technology gives each tenant its own ways of the cache, and memory bandwidth allocation limits its share of the bus.
A shared cache also leaks. In prime and probe, the attacker fills every set of the cache with its own lines. Then the victim runs. A table lookup at an address that depends on a secret evicts one of the attacker's lines. The attacker times reading its lines again: one set is slow, so it knows where the victim looked. In 2006 Dag Arne Osvik, Adi Shamir and Eran Tromer recovered AES keys this way, and in 2009 Thomas Ristenpart and colleagues showed how to place a virtual machine beside a chosen target in Amazon's cloud. Defences keep tenants off shared cores, partition caches, and use code whose memory accesses do not depend on secrets.
Clouds are built around failures that come together. A region is a metropolitan area with several availability zones. Amazon describes its zones as separate buildings with their own power and networking, many kilometres apart but within a hundred kilometres of each other: far enough not to fail together, near enough to replicate synchronously. Each level is a failure domain, a set of things that fail together. A host loses a disk, or panics. A rack shares a power feed and a switch. A zone can lose power or cooling. And in February 2017 a mistyped command took Amazon S3 in Northern Virginia down for about four hours.
Placement turns failure domains into availability. Chapter eight's code cuts an object into fourteen fragments, any ten of which rebuild it. Put two in each of seven racks. One rack fails: twelve remain. A second: ten, still enough. Only a third rack down at once loses the object; with all fourteen in one rack, the first would. The same rule protects Part 38's Raft. Five replicas spread two, two and one across three zones survive the loss of any zone: three of five is still a majority. Spread three and two across two zones, and losing the larger leaves two: no majority. Schedulers call this a spread constraint; it pulls against chapter five's packing.
12Cost, carbon, and the Job's billIndustry3 min
When is paying per request cheaper than renting a machine? Take a function that runs for 100 milliseconds with half a gigabyte of memory. At Amazon's list prices, a million calls cost about 1.03 dollars, so its monthly bill grows in proportion to the traffic. A server costs the same every month whether it is busy or idle, here one small instance able to handle two hundred requests a second. The lines cross near 26 requests a second of steady traffic. Below that, and for anything bursty or rare, functions win; above it, a machine kept busy is cheaper, often by a wide margin. The answer depends on utilization, which is chapter five's bin packing again.
Providers sell their spare capacity cheaply, as spot instances, on the condition that they can take it back at short notice. We modelled a ten-hour batch job on spot machines priced at a typical discount, interrupted on average once every ten hours. Without checkpoints, every interruption sends the job back to the start: it takes 17 hours on average, and costs more than half of the on-demand price anyway. With a checkpoint every half hour or so, it finishes in under eleven hours for just over a third of the on-demand cost. The best interval balances the cost of checkpointing against the work lost on interruption; John Young's rule of 1974, the square root of twice the checkpoint cost over the failure rate, gives 38 minutes, close to what the simulation finds.
The ledger gets row sixteen. The Job split across sixteen functions in the cloud: less than a tenth of a second of wall-clock time, if the text is already waiting in storage and the functions are warm, and a bill of about three thousandths of a cent. For the first time the ledger needs a second column. A design is now judged by what it costs to run, as well as how fast it runs.
Behind every bill is energy. The International Energy Agency estimated that datacentres used roughly one to one and a half percent of the world's electricity in 2022, and the growth of AI is pushing that up. Efficiency starts with the building: power usage effectiveness is total power divided by the power that reaches the computers, and the best fleets report about one point one. The grid's carbon intensity changes through the day, so flexible work, a nightly batch job, can be moved to the hours or the regions where the grid is cleanest. And the cheapest energy is the computation you never run: every row of the ledger that made the Job faster also made it smaller.
13Frontier: scheduling, isolation and energyResearch2 min
How close to optimal can a cloud run? Chapter eight derived durability from independent failures. The frontier is what that assumption hides. A ten-plus-four Reed–Solomon code, with fragments failing independently, gives about 13 nines a year. Now let whole racks fail instead, each about once in twenty years, taking a day to repair. With two fragments in each of seven racks, the data is lost only when three racks are down at once, and durability falls to about 7 nines. Put every fragment in one rack, and a single rack failure loses the data: barely more than one nine. Real durability is decided by correlated failures, a power feed, a firmware update pushed everywhere, a bug in every replica at once. Measuring and modelling those is still an open problem.
Isolation is the cloud's other frontier. Confidential computing has the processor encrypt a virtual machine's memory with keys the hypervisor never sees, so that a tenant need not trust the provider's own software, and can check by remote attestation what it is running on. Against that stand side channels: tenants sharing a core, a cache or memory bandwidth can measure each other, as Parts 8 and 9 showed, and every defence costs speed. And hardware is coming apart: memory and accelerators pooled across a rack, which wastes less but adds new latencies and new ways to fail. Isolation that is provable, cheap and complete at the same time remains open. Verified kernels exist, which Part 54 will meet, and fast hypervisors exist, but not yet both at once at the scale of a cloud.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Control loops that compare what should be with what is and close the gap, and stay correct when events are lost. Scheduling as bin packing, NP-hard, with heuristics that come within a few percent of optimal when they can sort the work first. Autoscalers as feedback controllers, which settle or oscillate depending on their gain and their delay, and Erlang's formula for how many servers a queue needs. Durability derived from a Markov chain, and the correlated failures that decide it in practice. And a bill for everything. One idea runs through it: the cloud is the series' ideas at the scale of buildings, with a price on every decision.
Where this comes back. Part 46 builds logs, streams and warehouses on this infrastructure. Part 47 runs a search engine across thousands of machines. Parts 48 and 49 design whole systems from load balancers, caches and queues. Part 50 keeps them running, with service-level objectives and capacity plans. And Part 60 opens the accelerators that now fill the datacentre.
In practice. Declare the state you want in code, let controllers converge on it, and never fix production by hand. Size containers from measurements, and pack them by every resource, not just processor time. Scale with modest gain and short measurement delays, quickly up and slowly down. Spread replicas across zones and racks, and test restoring your data, not just backing it up. And tag every resource with its owner, run batch work on spot capacity with checkpoints, and watch the cost of moving data out.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: give our reconciler a second kind of resource that depends on the first, and show that it converges in the right order after random deletions. The last, marked with a star, is a research problem: packing jobs whose lifetimes are unknown, helped by predictions that may be wrong.
Next time, Part 46: logs, streams and warehouses. Every company's data ends up in an append-only log and a column-oriented warehouse, with stream processors in between computing answers continuously, and the hard part is time: events that arrive late, out of order and more than once. The Job becomes a live top twenty over a stream of novels.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 46 builds logs, streams and warehouses on this infrastructure, and tables on its object store. Part 47 runs a search engine across thousands of machines. Parts 48 and 49 design whole systems from load balancers, caches and queues, Part 50 keeps them running with service-level objectives and capacity plans, and Part 60 opens the accelerators that now fill the datacentre.
Key results
The part's results in one place, for revision.
Try it
Lab 45 · Bin packing bounds, a delayed control loop, and the nines
Run the series' four packing heuristics against its exact branch-and-bound optimum and check the proved bounds; drive its autoscaler on both sides of the stability limit K < 2 cos(d pi / (2d + 1)); and compare Erlang C and the mean time to data loss with a direct sum and a Monte Carlo run.
python -m videos.cs.labs 45
needs numpy, scipy, matplotlib · download lab45.py ·
source on GitHubbins above the optimum, mean (worst) next fit +20% (+50%) first fit +7% (+33%) best fit +6% (+33%) first fit decreasing +1% (+20%)
halves alternating with tiny items next fit 200 bins, optimum 102 (ratio 1.96; the bound is 2)
largest stable gain, delay 0, 1, 3 2.00 1.00 0.45 (the simulator settles at 0.6x and oscillates at 1.3x for every delay 0..5)
servers for 10, 100, 1,000 erlangs 14 (71% busy) 111 (90% busy) 1034 (97% busy) (c - a)/sqrt(a) between 1.08 and 1.26
three copies, exaggerated rates simulated 182 years to loss, exact 181
nines a year at 2% and a day's repair three copies 9.4, RS(10, 4) 13.3
Sorting before packing comes within a few percent of the optimum, a control loop acting on old measurements has a hard gain limit that shrinks with the delay, and pooled servers need only a square-root safety margin.
The code (119 lines; it asserts its own result)
"""Lab 45: pack containers against the exact optimum, find where a delayed autoscaler goes unstable, and check Erlang C and the mean time to data loss."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import math
import numpy as np
from explainer.cs.cloud import control as ct
from explainer.cs.cloud import durability as du
from explainer.cs.cloud import packing as pk
TITLE = "Bin packing bounds, a delayed control loop, and the nines"
GOAL = ("Run the series' four packing heuristics against its exact branch-and-bound optimum and check the proved "
"bounds; drive its autoscaler on both sides of the stability limit K < 2 cos(d pi / (2d + 1)); and compare "
"Erlang C and the mean time to data loss with a direct sum and a Monte Carlo run.")
TASKS = [
"Draw the item sizes from uniform(0.34, 0.5) instead of (0.05, 0.7). Which heuristic is now furthest from the optimum, and why can no bin hold three items?",
"Set delay=2 in ct.autoscale and find by bisection the largest gain for which the last 100 steps swing by less than half the ideal size. Compare it with 2 cos(2 pi / 5) = 0.618.",
"Compute du.mttdl(14, 10) with repair_hours of 24, 72 and 240. By what factor do the mean years to loss fall each time, and which power of the repair time is that?",
]
def boundary(delay):
"""The largest stable gain of e[t+1] = e[t] - K e[t-d]."""
return 2 * math.cos(delay * math.pi / (2 * delay + 1))
def swing(gain, delay, seed):
"""How far the autoscaler's server count still moves in the last 100 of 300 steps, in units of the ideal size."""
r = ct.autoscale(gain=gain, delay=delay, steps=300, seed=seed)
tail = [s["servers"] for s in r["series"][-100:]]
return (max(tail) - min(tail)) / r["ideal"], r
def linear_tail(gain, delay, steps=4000):
e = [1.0] * (delay + 1)
for _ in range(steps):
e.append(e[-1] - gain * e[-1 - delay])
return max(abs(x) for x in e[-50:])
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. four heuristics against the exact optimum on 80 random instances of 16 containers
rules = {"next fit": pk.next_fit, "first fit": pk.first_fit, "best fit": pk.best_fit, "first fit decreasing": pk.ffd}
excess = {name: [] for name in rules}
for _ in range(80):
items = [round(float(x), 3) for x in rng.uniform(0.05, 0.7, 16)]
opt = pk.optimum(items)
assert opt >= math.ceil(sum(items) - 1e-9), "the optimum cannot beat the total size"
for name, rule in rules.items():
bins = rule(items)
assert all(sum(b) <= 1 + 1e-9 for b in bins) and sorted(x for b in bins for x in b) == sorted(items)
assert len(bins) >= opt, "no heuristic beats the optimum"
excess[name].append(len(bins) / opt - 1)
assert len(pk.next_fit(items)) <= 2 * opt - 1, "next fit: at most 2 OPT - 1"
assert len(pk.ffd(items)) <= 11 / 9 * opt + 6 / 9 + 1e-9, "first fit decreasing: at most 11/9 OPT + 6/9"
mean = {name: float(np.mean(v)) for name, v in excess.items()}
assert mean["first fit decreasing"] < mean["first fit"] < mean["next fit"]
lab.row("bins above the optimum, mean (worst)", " ".join(
f"{name} +{mean[name]:.0%} (+{max(excess[name]):.0%})" for name in rules))
bad = pk.next_fit_bad(200)
assert bad["next_fit"] <= 2 * bad["optimum"] - 1 and bad["ratio"] > 1.9
lab.row("halves alternating with tiny items", f"next fit {bad['next_fit']} bins, optimum {bad['optimum']} "
f"(ratio {bad['ratio']:.2f}; the bound is 2)")
# 2. the autoscaler: stable below K = 2 cos(d pi / (2d + 1)), unstable above
delays = list(range(6))
for d in delays:
k = boundary(d)
assert linear_tail(0.98 * k, d) < 1e-3 < 1e3 < linear_tail(1.02 * k, d), "the linear loop's exact limit"
assert swing(0.6 * k, d, seed)[0] < 0.5 and swing(1.3 * k, d, seed)[0] > 1.5, "and the simulator agrees"
lab.row("largest stable gain, delay 0, 1, 3", " ".join(f"{boundary(d):.2f}" for d in (0, 1, 3))
+ " (the simulator settles at 0.6x and oscillates at 1.3x for every delay 0..5)")
# 3. Erlang C against the M/M/c sum, and square-root staffing
for c, a in ((2, 1.0), (14, 10.0), (58, 50.0)):
tail = a ** c / math.factorial(c) * c / (c - a)
direct = tail / (sum(a ** k / math.factorial(k) for k in range(c)) + tail)
assert abs(ct.erlang_c(c, a) - direct) < 1e-9
assert abs(ct.erlang_c(2, 1.0) - 1 / 3) < 1e-12
table = ct.erlang_table()
margins = [(r["servers"] - r["load"]) / math.sqrt(r["load"]) for r in table]
assert max(margins) < 1.5 and min(margins) > 0.9 and table[-1]["utilization"] > table[0]["utilization"]
lab.row("servers for 10, 100, 1,000 erlangs", " ".join(
f"{r['servers']} ({r['utilization']:.0%} busy)" for r in (table[0], table[2], table[4]))
+ f" (c - a)/sqrt(a) between {min(margins):.2f} and {max(margins):.2f}")
# 4. mean time to data loss: the birth-death chain against a Monte Carlo run with exaggerated rates
sim = du.simulate(n=3, k=1, afr=0.5, repair_hours=500.0, trials=3000, seed=seed)
assert abs(sim["simulated_years"] / sim["exact_years"] - 1) < 0.12
nines = {(n, k): du.mttdl(n, k)["nines"] for n, k in ((3, 1), (14, 10))}
assert nines[(14, 10)] > nines[(3, 1)] > 9, "RS(10, 4) stores 1.4x and beats three copies at 3x"
lab.row("three copies, exaggerated rates", f"simulated {sim['simulated_years']:.0f} years to loss, exact {sim['exact_years']:.0f}")
lab.row("nines a year at 2% and a day's repair", f"three copies {nines[(3, 1)]:.1f}, RS(10, 4) {nines[(14, 10)]:.1f}")
lab.note = ("Sorting before packing comes within a few percent of the optimum, a control loop acting on old "
"measurements has a hard gain limit that shrinks with the delay, and pooled servers need only a "
"square-root safety margin.")
fig, ax = labs.figure(2, size=(11, 4.4))
for gain, color in ((0.2, labs.GREEN), (0.6, labs.RED)):
r = ct.autoscale(gain=gain, delay=3, steps=80, seed=seed)
ax[0].plot([s["t"] for s in r["series"]], [s["servers"] for s in r["series"]], color=color,
label=f"gain {gain}: {'below' if gain < boundary(3) else 'above'} the limit 0.45")
ax[0].axhline(r["ideal"], color=labs.MUTED, ls="--", label="right size: 16.7 servers")
ax[0].set(title="Autoscaler on a measurement three steps old", xlabel="step (load jumps at step 10)",
ylabel="servers", yscale="log", ylim=(1, 5000))
ax[0].legend(loc="upper right")
dd = np.arange(0, 9)
ax[1].plot(dd, [boundary(int(d)) for d in dd], "o-", color=labs.GOLD, label="limit: 2 cos(dπ / (2d + 1))")
ax[1].plot(delays, [0.6 * boundary(d) for d in delays], "v", color=labs.GREEN, label="simulated: settles")
ax[1].plot(delays, [1.3 * boundary(d) for d in delays], "^", color=labs.RED, label="simulated: oscillates")
ax[1].set(title="Largest stable gain against delay", xlabel="delay d (steps)", ylabel="gain K")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Draw the item sizes from uniform(0.34, 0.5) instead of (0.05, 0.7). Which heuristic is now furthest from the optimum, and why can no bin hold three items?
- Set delay=2 in ct.autoscale and find by bisection the largest gain for which the last 100 steps swing by less than half the ideal size. Compare it with 2 cos(2 pi / 5) = 0.618.
- Compute du.mttdl(14, 10) with repair_hours of 24, 72 and 240. By what factor do the mean years to loss fall each time, and which power of the repair time is that?
Problems, with solutions
Try each problem before opening its solution.
-
Next fit. Prove that next fit uses at most twice the optimal number of bins, and give inputs on which it uses nearly twice.
Solution
Let next fit use m bins with loads L₁, …, L_m. It opens bin i + 1 only when the item that starts it does not fit in bin i, so L_i + L_{i+1} > 1 for every i < m. Pair the bins (1, 2), (3, 4), …: the ⌊m/2⌋ pairs hold total size S > ⌊m/2⌋. Every packing needs at least S bins, so OPT ≥ S > ⌊m/2⌋, and since OPT is an integer, OPT ≥ ⌊m/2⌋ + 1 ≥ (m + 1)/2, that is, m ≤ 2·OPT − 1. For the lower bound take 2k items (k even) alternating ½ and ε = 1/k. After a bin holding ½ + ε the next ½ overflows, so every bin holds exactly one half and one small item, and next fit uses k bins. The optimum pairs the halves in k/2 bins and puts the k small items, of total 1, in one more; k/2 + 1 is also the total size, so OPT = k/2 + 1 and NF = 2·OPT − 2, a ratio tending to 2. With the instrument's ε = 0.01: 16 items take 8 bins against 5, and 400 take 200 against 102, a ratio of 1.96.
-
NP-hardness. Show that bin packing is NP-hard by reducing partition to deciding whether two bins suffice.
Solution
Given positive integers a₁, …, a_n with sum S, form items x_i = a_i/(S/2); if some a_i > S/2 the answer is no, and we output any fixed no-instance (three items of 0.6). The items total 2, so two bins of size 1 suffice exactly when each is filled exactly, that is, when some subset has Σ x_i = 1, that is, Σ a_i = S/2: a partition. (An odd S needs no special case: integer subset sums cannot equal S/2.) The map takes polynomial time, and partition is NP-complete (Karp, 1972; Part 26), so deciding whether OPT ≤ 2 is NP-hard, and so is bin packing. On screen: 3, 1, 1, 2, 2, 1 gives 0.6, 0.2, 0.2, 0.4, 0.4, 0.2, which split as {3, 1, 1} and {2, 2, 1} into two bins; 3, 3, 3, 1 gives 0.6, 0.6, 0.6, 0.2, where no two 0.6 share a bin, so three are needed. Corollary: a polynomial algorithm that always used fewer than 3/2·OPT bins would return 2 whenever OPT = 2 (fewer than 3) and so decide partition; no such algorithm exists unless P = NP. The bound is for the absolute ratio: asymptotically, packings within (1 + ε)·OPT + 1 can be found in polynomial time (Fernandez de la Vega and Lueker, 1981).
-
Erlang C. Derive Erlang C from the birth–death chain of an M/M/c queue, and the mean wait from it.
Solution
Let the state k be the number of requests in the system. Arrivals move k to k + 1 at rate λ; with k requests, min(k, c) servers are busy, so departures move k to k − 1 at rate min(k, c)·μ. In equilibrium the flow across each cut balances, λπ_k = min(k + 1, c)·μ·π_{k+1}, which gives π_k = π₀·a^k/k! for k ≤ c, with a = λ/μ, and π_k = π_c·ρ^{k−c} for k ≥ c, with ρ = a/c < 1. Normalizing, 1/π₀ = Σ_{k<c} a^k/k! + (a^c/c!)/(1 − ρ). Poisson arrivals see time averages, so an arrival waits exactly when it finds k ≥ c: C(c, a) = Σ_{k≥c} π_k = π_c/(1 − ρ) = [a^c/(c!(1 − ρ))] / [Σ_{k<c} a^k/k! + a^c/(c!(1 − ρ))]. The mean queue length is L_q = Σ_{j≥0} j·π_{c+j} = π_c·ρ/(1 − ρ)² = C(c, a)·ρ/(1 − ρ), and Little's law gives W_q = L_q/λ = C(c, a)·ρ/(λ(1 − ρ)) = C(c, a)/(cμ − λ). (Given that it waits, a request waits an exponential time of rate cμ − λ.) Checks: c = 1 gives C = ρ, Part 31's M/M/1; c = 2, a = 1 gives C = 1/(2 + 1) = 1/3 and W_q = 1/3 of a service time. With 10 erlangs, 13 servers give C = 0.285, over the 0.2 target, and 14 give C = 0.174 and W_q = 0.174/4 = 0.044 service times, which is why the table's first row is 14.
-
Mean time to data loss. Derive the mean time to data loss for n fragments of which any k suffice, with failure rate λ per fragment and one repair at a time at rate μ.
Solution
Let the state i be the number of failed fragments; the data is lost on reaching i = n − k + 1. From state i ≤ n − k a failure occurs at rate λ_i = (n − i)λ and, for i ≥ 1, a repair at rate μ. Let T_i be the expected time to go from i to i + 1 for the first time. T₀ = 1/(nλ). For i ≥ 1, the chain leaves i after a mean 1/(λ_i + μ); with probability λ_i/(λ_i + μ) it moves up, and otherwise it drops to i − 1, needs T_{i−1} to return, and then T_i again: T_i = 1/(λ_i + μ) + μ/(λ_i + μ)·(T_{i−1} + T_i), that is, λ_i·T_i = 1 + μ·T_{i−1}, or T_i = (1 + μ·T_{i−1})/((n − i)λ). To be lost the chain must climb every level in turn, so MTTDL = Σ_{i=0}^{n−k} T_i. Unrolling, T_i = Σ_{j≤i} μ^{i−j}/(λ_j λ_{j+1} ⋯ λ_i), and when μ ≫ λ the term j = 0 of the last level dominates: MTTDL ≈ μ^{n−k} / (n(n − 1)⋯k · λ^{n−k+1}). For three copies (n = 3, k = 1) with λ = −ln(0.98) per year = 2.305 × 10⁻⁶ per hour and μ = 1/24 per hour, μ²/(6λ³) = 2.36 × 10¹³ hours, 2.7 billion years, within 0.03% of the exact sum. If the time to loss is close to exponential, the chance of loss in a year is p = 1 − e^{−1/MTTDL} ≈ 1/MTTDL in years, 3.7 × 10⁻¹⁰, or 9.4 nines. One more fragment, and one more tolerated loss, multiplies the mean by about μ/(nλ) for the new n, with μ/λ ≈ 1.8 × 10⁴ here (one copy to two: 49.5 to 447,521 years, a factor of 9,000). That is why the nines climb so fast, and why the result is only as good as the assumption that failures are independent.
-
Build. Add a reconciler for a second resource that depends on the first, and show it converges in dependency order after random deletions.
Solution
Solution sketch. Use
control.planas the compare step. Declare, say, three volumes and five pods, each pod naming a volume in its dependency list, as name → (kind, properties, dependencies). Each pass: with probability p delete a random resource fromactual, and with it everything that uses it (or mark those resources broken, so that the plan updates them); then callplan(desired, actual)and apply only its first step, one action per pass, likereconcile's one start per step. Because the plan lists creates and updates in topological order, its first step always has its dependencies present: a missing dependency would itself be an earlier step. That is the convergence proof: let Φ be the number of steps in the plan; with no deletions each pass applies an applicable step and lowers Φ by one, so the reconciler reaches the desired state within Φ passes of the last deletion, whatever was deleted before. Test it astests/test_cs45_cloud.pydoes: over many seeds, assert thatactual == desiredwithin |desired| passes after deletions stop, and that the log of applied steps never creates a pod before its volume. Running the same loop edge-triggered, acting on deletion events of which some are lost, shows it stuck short, as in chapter four. -
★ Research. Online vector bin packing of jobs with unknown lifetimes, with predictions: near optimal when accurate, robust when not.
Discussion. Open. Three difficulties compound. Even with sizes known on arrival and no departures, online vector packing in d resources has a competitive ratio that grows with d, and first fit's O(d) is nearly the best possible (Azar, Cohen, Kamara and Shepherd, 2013). With departures, the objective changes (the peak number of machines, or the machine-hours paid for), and an adversary can leave every machine holding one long-lived job. And lifetime predictions, learned from traces such as Azure's (Cortez et al., 2017), are noisy and heavy-tailed. A good answer would fix d (two is already interesting), an objective and a measure of prediction error η; give an algorithm whose cost is within a constant of the optimum when η = 0 and degrades smoothly in η to within a constant of the best prediction-free guarantee; and prove a matching trade-off between those two constants. Partial results, one dimension with lifetimes, or two dimensions with exact lifetimes, or a careful evaluation on public cluster traces, would already be useful.
Notes and sources
Glossary
- warehouse-scale computer, rack, top-of-rack switch, hot and cold aisles — a datacentre programmed as one machine; its unit of servers, switch and power feed; how air flows through the rows.
- UPS, PDU, power capping, oversubscription — the power chain's batteries and distribution; limiting power when installed servers could together exceed the building's budget.
- energy proportionality, PUE — power that falls with load; power entering the building over power reaching the computers.
- KVM, virtual machine monitor, virtio, microVM, jailer — the kernel half and the user-space half of a hypervisor; paravirtual devices; a VM with a minimal device model; the confinement around the monitor process.
- gVisor, Kata Containers — a user-space kernel answering a container's system calls; containers run in microVMs.
- namespace, cgroup, cpu.max, memory.max, OOM killer — what a process can see, and how much it may use.
- image, layer, manifest, registry, OverlayFS, copy-up, whiteout, OCI — content-addressed files for containers and how they are stored, merged, changed and standardized.
- cluster (cell), pod, kubelet, Deployment, controller, etcd — Kubernetes' (and Borg's) units and parts.
- desired and observed state, reconciliation loop, level- and edge-triggered — declaring a goal and closing the gap to it; acting on the current difference rather than on events.
- bin packing, next fit, first fit, best fit, first fit decreasing, vector bin packing — packing items into fewest bins; the classic heuristics; packing by several resources at once.
- filter and score, priority, preemption — how a scheduler picks a machine, and who gives way.
- autoscaler, Horizontal Pod Autoscaler, gain, delay, quota — a feedback controller on the number of servers.
- M/M/c queue, Erlang C, square-root staffing — c servers fed by Poisson arrivals; the chance of waiting; spare capacity growing like √a.
- predictive scaling — starting capacity ahead of forecast load.
- serverless, function as a service, cold start, keep-alive, concurrency limit, throttling — code run per event and billed per millisecond, and its costs.
- block, file and object storage; bucket, key; read-after-write consistency — three shapes of storage; what a read sees after a write.
- erasure code, Reed–Solomon, fragment, parity, overhead — storing data so that any k of n pieces rebuild it.
- MTTDL, nines of durability, failure domain, correlated failure — mean time to data loss; −log₁₀ of the yearly loss probability; what fails together.
- VPC, subnet, route table, security group, internet gateway — a tenant's private network and its rules.
- overlay network, encapsulation, VXLAN, virtual switch — tenant packets carried inside host packets.
- load balancer, health check, layer 4 and layer 7, Maglev, anycast — one address in front of many machines, near and far.
- egress, data gravity — the price of moving data out; why computation moves to data.
- infrastructure as code, state file, plan, apply, drift, immutable infrastructure, snowflake — the desired infrastructure in version control, and keeping the real one equal to it.
- noisy neighbour, Cache Allocation Technology, Memory Bandwidth Allocation, CPI², antagonist — interference between tenants, its partitioning and its detection.
- prime and probe, co-residence, constant-time code — a cache side channel, the placement it needs, a defence.
- region, availability zone, spread constraint (anti-affinity), data residency, adequacy decision — where things run, apart and within the law.
- on demand, spot, checkpoint, Young's rule — prices for capacity that can or cannot be taken back; saving progress at the right interval.
- carbon intensity, carbon-aware scheduling — emissions per kilowatt-hour; moving flexible work in time and space.
- confidential computing, remote attestation, disaggregation, CXL, learning-augmented algorithm — the frontier's encrypted VMs, pooled hardware and algorithms that use predictions.
Sources
- L. A. Barroso, U. Hölzle and P. Ranganathan, The Datacenter as a Computer: Designing Warehouse-Scale Machines (3rd edn, 2018); B. Burns, J. Beda and K. Hightower, Kubernetes: Up and Running (2nd edn, 2019); K. Morris, Infrastructure as Code (2nd edn, 2020); M. Harchol-Balter, Performance Modeling and Design of Computer Systems: Queueing Theory in Action (2013).
- J. McCarthy, remarks at the MIT centennial (1961); M. Armbrust et al., "A view of cloud computing", Communications of the ACM 2010.
- X. Fan, W.-D. Weber and L. A. Barroso, "Power provisioning for a warehouse-sized computer", ISCA 2007; L. A. Barroso and U. Hölzle, "The case for energy-proportional computing", IEEE Computer 2007; The Green Grid, PUE white paper (2007); Uptime Institute, annual global data center surveys; Google, environmental reports; J. Dean, "Designs, lessons and advice from building large distributed systems", LADIS 2009 keynote.
- G. Popek and R. Goldberg, "Formal requirements for virtualizable third generation architectures", Communications of the ACM 1974; A. Kivity et al., "kvm: the Linux virtual machine monitor", Ottawa Linux Symposium 2007; F. Bellard, "QEMU, a fast and portable dynamic translator", USENIX ATC 2005; A. Agache, M. Brooker, A. Florescu, A. Iordache, A. Liguori, R. Neugebauer, P. Piwonka and D.-M. Popa, "Firecracker: lightweight virtualization for serverless applications", NSDI 2020.
- A. Verma, L. Pedrosa, M. Korupolu, D. Oppenheimer, E. Tune and J. Wilkes, "Large-scale cluster management at Google with Borg", EuroSys 2015; B. Burns, B. Grant, D. Oppenheimer, E. Brewer and J. Wilkes, "Borg, Omega, and Kubernetes", ACM Queue 2016.
- E. G. Coffman Jr, M. R. Garey and D. S. Johnson, "Approximation algorithms for bin packing: a survey", in D. Hochbaum (ed.), Approximation Algorithms for NP-Hard Problems (1996); D. S. Johnson, Near-Optimal Bin Packing Algorithms (PhD thesis, MIT, 1973); G. Dósa, "The tight bound of first fit decreasing bin-packing algorithm is FFD(I) ≤ 11/9 OPT(I) + 6/9", ESCAPE 2007; R. Karp, "Reducibility among combinatorial problems" (1972); W. Fernandez de la Vega and G. Lueker, "Bin packing can be solved within 1 + ε in linear time", Combinatorica 1981; Y. Azar, I. R. Cohen, S. Kamara and B. Shepherd, "Tight bounds for online vector bin packing", STOC 2013.
- J. C. Maxwell, "On governors", Proceedings of the Royal Society 1868; A. K. Erlang, "Solution of some problems in the theory of probabilities of significance in automatic telephone exchanges" (1917); S. Halfin and W. Whitt, "Heavy-traffic limits for queues with many exponential servers", Operations Research 1981.
- E. Jonas et al., "Cloud programming simplified: a Berkeley view on serverless computing", UC Berkeley technical report, 2019; M. Shahrad et al., "Serverless in the wild: characterizing and optimizing the serverless workload at a large cloud provider", USENIX ATC 2020.
- M. Mahalingam et al., "Virtual eXtensible Local Area Network (VXLAN)", RFC 7348 (2014); M. Dalton et al., "Andromeda: performance, isolation, and velocity at scale in cloud network virtualization", NSDI 2018; D. E. Eisenbud et al., "Maglev: a fast and reliable software network load balancer", NSDI 2016.
- M. Burgess, "Cfengine: a site configuration engine", USENIX Computing Systems 1995.
- X. Zhang, E. Tune, R. Hagmann, R. Jnagal, V. Gokhale and J. Wilkes, "CPI²: CPU performance isolation for shared compute clusters", EuroSys 2013; J. Schad, J. Dittrich and J.-A. Quiané-Ruiz, "Runtime measurements in the cloud: observing, analyzing, and reducing variance", VLDB 2010; D. A. Osvik, A. Shamir and E. Tromer, "Cache attacks and countermeasures: the case of AES", CT-RSA 2006; T. Ristenpart, E. Tromer, H. Shacham and S. Savage, "Hey, you, get off of my cloud: exploring information leakage in third-party compute clouds", CCS 2009.
- Regulation (EU) 2016/679 (GDPR); Court of Justice of the European Union, Case C-311/18 (Schrems II), 2020.
- J. W. Young, "A first order approximation to the optimum checkpoint interval", Communications of the ACM 1974; T. Lykouris and S. Vassilvitskii, "Competitive caching with machine learned advice", ICML 2018; E. Cortez et al., "Resource Central: understanding and predicting workloads for improved resource management in large cloud platforms", SOSP 2017; International Energy Agency, Electricity 2024 (2024).
- AWS documentation and price lists for us-east-1 (2024): EC2, Lambda (pricing and quotas), S3 (pricing, durability, and strong read-after-write consistency since December 2020), data transfer.
About this partfrom its README
Part 45 of a sixty-one-part course in computer science (see the series plan and the syllabus), the first part of Act IX, Systems at Scale. A modern application rents its computer by the second from a building that draws tens of megawatts, and under the abstraction sit the series' own ideas at the scale of buildings: virtual machines shrunk to microVMs, containers placed by bin-packing heuristics, control loops that reconcile what is with what should be, and storage whose eleven nines we derive from a Markov chain. The Job gets a price in dollars.
The instruments are in explainer/cs/cloud/ (tested in tests/test_cs45_cloud.py):
packing.py: next fit, first fit, best fit and first fit decreasing; the exact optimum by branch and bound (items sorted, equal-load bins tried once, the size bound as a cut-off); the four heuristics against it on random and on clustered instances; the family of halves alternating with tiny items on which next fit uses nearly twice the optimum; vector packing of (CPU, memory) demands, sorted by the larger demand against by CPU alone; the reduction from partition.control.py: a reconciler for a replica count, level-triggered against edge-triggered with lost "pod died" events; an autoscaler as a proportional controller acting on a delayed utilization measurement, with a quota; Erlang C by the stable Erlang B recursion, and the fewest servers meeting a mean-wait and a P(wait) target; an infrastructure plan as a diff (create, update, destroy) applied in dependency order, destroys in reverse.durability.py: the mean time to data loss for n fragments of which any k suffice, from the birth–death chain of failure and one-at-a-time repair, solved exactly; the probability of loss in a year and its nines; a Monte Carlo check of the same chain; whole racks failing together against fragments spread across racks.cost.py: AWS us-east-1 list prices as published in 2024; Lambda against m5.large servers at a steady request rate, and the break-even rate; a batch job on spot capacity with Poisson interruptions and checkpoints; the Job's bill three ways from its measured single-core time.
Chapter notes
- Hook. John McCarthy at MIT's centennial (1961): computing may someday be organized as a public utility. Time-sharing, then owned servers and rented racks, then S3 (March 2006, storage by the gigabyte-month) and EC2 (August 2006, a computer by the hour), and today billing by the second or by the request. Under the word cloud, a hierarchy in which every layer is a scheduling problem and a failure domain: region, building (tens of megawatts, tens of thousands of servers), rack, server, virtual machine, container. The Job gets a price: counting 25.0 MB of novels takes 1.41 s on one core of this machine, which costs $0.00160 on one on-demand server billed per second with a one-minute minimum, $0.00056 at a typical spot discount, and $0.00003 (about three thousandths of a cent) on sixteen functions billed per gigabyte-second, at dated list prices that leave out cold starts and reading the text from storage.
- 1. The warehouse-scale computer. Barroso and Hölzle (2009): tens of thousands of servers, one owner, a few huge services programmed as one machine; the rack (a few dozen servers, a switch, a shared power feed) in rows with cold and hot aisles. The power chain from grid through transformers, UPS, PDU and rack to each server's supply, with diesel generators behind the batteries; the scarce resource is watts, and because thousands of servers never peak together operators install more than the ratings allow and cap power (Fan, Weber and Barroso, 2007). Idle is expensive: on a straight line from half power at idle, a server 30% busy draws 65% of its peak and does 46% of the work per watt it manages flat out; energy proportionality as the remedy. PUE (The Green Grid, 2007): about 2.5 for the industry average in 2007 (60% of the electricity never reaching a computer), 1.58 in 2023 (37%), 1.10 for Google's fleet in 2023 (9%). Failure as a rate: 2,000 servers in 50 racks, each failing once in three years (an assumption), 2000 / 1096 days ≈ 1.8 failures a day, 62 in a simulated month; failures that come in groups, and failure domains that nest from server to region.
- 2. Virtual machines, shrunk. KVM (in Linux since 2007) runs guest code on the processor and takes only its exits; a user-space monitor such as QEMU (Bellard, 2003) emulates the rest, and a device access is exit, hand-off, emulation. A general-purpose monitor's device zoo against Firecracker's whole device model (virtio-net, virtio-block, virtio-vsock, a serial console, a keyboard controller used only to stop the machine); VENOM (2015), a guest escape through QEMU's emulated floppy controller. Booting: a general-purpose VM takes about 9 s in illustrative stages; the Firecracker project reports user code in as little as 125 ms, under 5 MiB of overhead per microVM and up to 150 microVMs started per second per host; SnapStart (2022) restores a snapshot instead. One microVM per function, customers mixed on one host, behind layered walls (guest kernel, KVM or the device model, then the jailer's chroot, namespaces, cgroups and seccomp filter). Isolation in grades: process, container (one kernel, about 450 system calls), gVisor (2018), microVM (Kata Containers, 2017), full VM.
- 3. Containers. Namespaces decide what a process sees (pid 1 inside is 4242 to the host), cgroups how much it may
use:
cpu.max 50000 100000is half a processor, so a busy process runs 50 ms in every 100 ms and a request arriving while it is throttled waits about 45 ms (illustrative), andmemory.maxof 256 MiB ends in the out-of-memory killer. An image is a stack of layers, each named by the SHA-256 of its contents, and a manifest named by its own hash: a Merkle tree (Part 41); changing one line of the application renames only the top layer and the manifest, which is why a Dockerfile copies the code last. OverlayFS (2014): the higher layer wins, the first write copies a file up, a delete writes a whiteout, and a hundred containers share the read-only layers. A registry stores each blob once by hash, so a machine that ranweb:v1pullsweb:v2by downloading one layer; the Open Container Initiative (2015) and runc. - 4. Orchestration and reconciliation. Borg (Verma et al., 2015): cells of about ten thousand machines in the median, a Borgmaster replicated five times with Paxos, a Borglet on every machine; Kubernetes (2014) maps onto it almost one for one (pod and task, kubelet and Borglet, Deployment and job, etcd with Raft and the Paxos store). Declarative desired state against an imperative script; the reconciliation loop (observe, compare, act), which asks only what is different, so it is idempotent. Level- against edge-triggered, simulated: five replicas, two pods crashing at steps 12 and 25, 30% of "pod died" events lost; the edge-triggered controller loses one of the two events at step 25 and stays at 4 replicas for good; the level-triggered one climbs to 5 one pod per step and is short for 1 step after each crash. etcd replicated by Raft (Part 38), with every write committed by a majority (three members survive one failure, five survive two); versioned objects refuse updates based on stale reads, like compare-and-swap; the scheduler is a controller too.
- 5. Scheduling as bin packing. First fit puts eight containers (0.5, 0.3, 0.6, 0.2, 0.4, 0.3, 0.5, 0.2 of a processor) into 3 full machines, and the fourth can be switched off; real schedulers filter, then score. NP-hard by way of partition (Part 26): 3, 1, 1, 2, 2, 1 (total 10) fit in 2 bins, 3, 3, 3, 1 need 3, so no fast algorithm can promise better than 3/2 of the optimum unless P = NP. Four heuristics against the exact optimum, 20 items an instance, bins above the optimum as mean / worst: on 200 instances with uniformly random sizes, next fit +24% / +50%, first fit +8% / +29%, best fit +8% / +29%, first fit decreasing +1% / +14%; on 100 instances with clustered sizes, +18% / +33%, +6% / +17%, +6% / +17%, +4% / +17%. What can be guaranteed: next fit on halves alternating with tiny items uses 4 bins against 3 for 8 items, 8 against 5 for 16, 12 against 7, 40 against 21 and 200 against 102 for 400 (ratio 1.96); NF ≤ 2·OPT − 1 proved; FFD ≤ 11/9·OPT + 6/9 (Johnson 1973 with + 4, Dósa 2007 tight). Vector packing of 200 containers by CPU and memory: total demand says at least 38.4 machines; first fit sorted by each job's larger demand uses 43, 87% busy in CPU and 89% in memory; sorted by CPU alone, 63, 60% and 61%. Priorities and preemption; running production and batch on separate machines would need 20–30% more machines in the median Borg cell.
- 6. Autoscaling as control. The loop, with a late measurement and a boot time; Kubernetes' Horizontal Pod Autoscaler, n ← ⌈n·u/u*⌉, and ours, n_{t+1} = n_t + K(u_{t−d}/u* − 1)·n_t (K = 1 is Kubernetes' rule). Load jumps from 40 to 100 requests a second at step 10, a server handles 10 at full use and the target is 60%, so the right size is 16.7 servers: K = 0.3 with a one-step delay settles at 16.4 after a peak of 18.0; K = 0.2 with three steps settles at 16.8 after 25.4; K = 0.5 oscillates between 5 and 99; K = 1 slams between 1 and the quota of 200. Linearized, e_{t+1} = e_t − K·e_{t−d}, stable only while K < 2 cos(dπ/(2d + 1)): 2 with no delay, 1.00 with one step, 0.45 with three, and all four runs land on the predicted side (Maxwell, 1868). Erlang C from the M/M/c chain, with the check C(2, 1) = 0.333. The fewest servers keeping the mean wait under a twentieth of a service time and P(wait) under a fifth: 10 erlangs need 14 servers (71% busy), 50 need 58 (86%), 100 need 111 (90%), 500 need 525 (95%), 1,000 need 1,034 (97%); (c − a)/√a stays between 1.08 and 1.26, square-root staffing (Halfin and Whitt, 1981), the economy of scale behind the cloud. Predictive scaling against a reactive loop on two days of daily load (illustrative).
- 7. Serverless. Lambda (2014): a function run per event, an instance per concurrent event, billed by the millisecond, scaling to zero, with state kept outside (Jonas et al., 2019). The bill: 100 ms at 512 MB costs $0.83 per million requests in compute and $0.20 in request fees, $1.03 in all, against $0.13 per million for an m5.large kept busy at 200 requests a second; a function costs 7.8 times as much per request, so it wins while the server would be busy less than 13% of the time, below 25.8 of its 200 requests a second. Cold starts (boot the microVM, start the runtime, load libraries): of twelve requests in an illustrative hour, a 3-minute keep-alive starts 6 cold and keeps an instance warm 29 of 60 minutes; a 10-minute one starts 2 cold and keeps it 57; Shahrad et al. (2020) on Azure Functions. Concurrency by Little's law: at 25.8 requests a second of 100 ms each, 2.6 instances in flight (24 requests on 5 instances in one random second), 10 at 100 requests a second, 100 at 1,000; AWS's default cap of 1,000 concurrent executions per account and region is reached at 10,000 requests a second; throttling, the 15-minute limit, and databases swamped by a thousand connections (Part 43).
- 8. Object storage and eleven nines. Block, file and object storage; S3 Standard at $0.023 a gigabyte-month.
Read after write: until 2020 an overwrite could be read stale for a while; since December 2020 every later GET and
LIST sees the write; updates are atomic per key, the later writer wins, and there are no transactions across keys
(Part 46 builds tables on this). RS(10, 4) fragments, two to a rack across seven racks: a whole rack plus two more
disks leaves 10 of 14, still readable; 4 losses tolerated at 1.4× the data against 2 for three copies at 3×. The
Markov chain of failure and repair, with T_i = (1 + μ·T_{i−1})/((n − i)λ) and MTTDL = Σ T_i: with 2% a year and a
day's repair, three copies last about 2.7 billion years; a Monte Carlo with exaggerated rates gives 178 against 181
years exact, and 11.8 against 11.6 for any 4 of 6. The table (stored, losses survived, mean years to loss, nines a
year): one copy 1.0×, 0, 49.5, 1.7; two copies 2.0×, 1, 4.5×10⁵, 5.7; three copies 3.0×, 2, 2.7×10⁹, 9.4; 6 data
- 3 parity 1.5×, 3, 9.7×10¹⁰, 11.0; 10 + 4 1.4×, 4, 2.2×10¹³, 13.3; 10 + 6 1.6×, 6, 3.0×10¹⁹, 19.5. S3 is designed for eleven nines: ten million objects, one lost about every ten thousand years. Every row assumes independent failures.
- 9. Cloud networking. A VPC, 10.0.0.0/16 (Part 36), with a subnet in each zone, a route table (local, and 0.0.0.0/0 to the internet gateway) and stateful security groups. Packets inside packets: the host's virtual switch maps the tenant's 10.0.2.7 to host 192.168.9.40 and wraps the packet in UDP port 4789 and a VXLAN header (RFC 7348, 2014: 8 bytes, a 24-bit network number, about 16 million networks, 50 bytes a packet with the outer headers); Amazon's Nitro cards, Google's Andromeda (2018). Managed load balancers with health checks, at layer 4 or 7; Maglev (2016), hashing connections to backends in software; anycast through BGP. Egress: data in is free, out is $0.09 a gigabyte (about $90 a terabyte before discounts) and traffic between zones is billed too; one download costs 3.9 months of storage; our 25 MB of novels about 0.22 cents a download; data has gravity.
- 10. Infrastructure as code. Console clicks against a declared file, through commit, plan, review and apply
(CFEngine 1993, Puppet 2005, CloudFormation 2011, Terraform 2014; a simplified Terraform-like syntax). A plan is a
diff of the state file against the code: the network and subnet unchanged, the database updated from small to
large, the queue and service created, the old cache destroyed, "Plan: 2 to add, 1 to change, 1 to destroy." Applied
in topological order (Part 18): 1 update db, 2 create queue, 3 create service, 4 destroy old-cache; db and queue
share no path and can be applied together, Part 41's build graph with clouds for files. Drift: a database resized
to xlarge by hand during an incident; the next refresh finds it and the plan proposes
~ db update size: xlarge -> large, a change nobody wrote, to apply or to adopt in the code; scheduled plans, and the Kubernetes controller as the same idea run continuously. Immutable infrastructure: snowflakes patched in place against machines replaced from a content-addressed image, with rollback by pointing back. - 11. Neighbours, regions and failure domains. Noisy neighbours: the hypervisor divides cores and memory but not the last-level cache or the memory bus (Part 9); Intel's Cache Allocation Technology and Memory Bandwidth Allocation. CPI² (Zhang et al., 2013) flags a task whose cycles per instruction stray above its usual value plus 2σ and caps the neighbour whose CPU use rose with it; Schad et al. (2010) on the variance of EC2. Prime and probe on a shared cache; Osvik, Shamir and Tromer (2006) on AES, Ristenpart et al. (2009) on co-residence in EC2. Regions, zones (AWS: separate buildings within 100 km of each other), racks and hosts as nested failure domains, and S3 in Northern Virginia down for about four hours in February 2017 after a mistyped command. Placement: RS(10, 4) two to a rack in seven racks leaves 12 fragments with one rack down, 10 with two, 8 and the object lost with three; all 14 in one rack lose it at the first rack failure. Five Raft replicas split 2, 2, 1 across three zones survive any zone; split 3, 2 across two they do not. Spread constraints pull against packing. Data residency: GDPR (applied from 2018) and Schrems II (2020); light in fibre covers about 200 km a millisecond, so replication between regions is usually asynchronous.
- 12. Cost, carbon, and the Job's bill. Functions or servers for steady traffic from 0.1 to 1,000 requests a second: the function's monthly bill grows with the rate at $1.03 a million, one m5.large costs $69.12 a month, and the lines cross near 26 requests a second. Spot capacity: a ten-hour job, an interruption every 10 hours on average, checkpoints costing 1.2 minutes (and three minutes to restart, in the model), at a typical 65% discount: without checkpoints 17.4 hours and $0.58; every 120 minutes 11.3 h and $0.38; every 60, 10.8 h and $0.36; every 30, 10.7 h and $0.36, the cheapest; every 15, 11.0 h and $0.37; on demand 10.0 h and $0.96; Young's rule (1974), √(2C/λ) ≈ 38 minutes. Ledger row 16: the Job on sixteen functions, about 0.09 s of wall-clock time and $0.00003, and a second column, dollars. Energy and carbon: datacentres used roughly 1–1.5% of the world's electricity in 2022 (IEA); the best fleets report a PUE of about 1.1; carbon-aware scheduling moves a flexible job to the cleanest hours (illustrative); the cheapest energy is the computation not done.
- 13. Frontier: scheduling, isolation and energy. Where the nines go: RS(10, 4) with independent fragment failures gives 13.3 nines a year; with whole racks failing (each once in twenty years, a day to repair) and two fragments to each of seven racks, 7.0; with all fragments in one rack, 1.3. Scheduling with predictions: first fit decreasing comes within 1% of the optimum because it knows the sizes, next fit 24% above; online schedulers know neither sizes nor lifetimes; learning-augmented algorithms (Lykouris and Vassilvitskii, 2018); schedulers that predict VM lifetimes. Isolation: confidential computing (AMD SEV-SNP, Intel TDX, Arm CCA) with remote attestation; side channels (Parts 8 and 9); disaggregated memory and accelerators (CXL); verified kernels (seL4, Part 54) and fast hypervisors, but not yet both at cloud scale. 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
The Job gets a price in dollars.
- Hook: from owning servers to renting them; McCarthy's utility computing (1961), EC2 and S3 (2006).
- The warehouse-scale computer: racks, power, cooling; PUE defined (values cited); failure rates at scale (callbacks to Parts 34 and 39).
- Virtualization recap (callback to Part 32) and microVMs (Firecracker 2020): minimal devices, fast boots, isolation for serverless.
- Containers: namespaces and cgroups (callback to Part 32); images as content-addressed layers (callback to Part 41).
- Orchestration: Borg (Verma et al. 2015) and Kubernetes; declarative desired state and the reconciliation loop, level- against edge-triggered; etcd and Raft underneath (callback to Part 38).
- Scheduling as bin packing: NP-hard (from partition); first-fit decreasing's 11/9 OPT + 6/9 (Dósa 2007, cited) and next-fit's 2 (proved); vector packing over CPU and memory; priorities and preemption; utilization gains (cited).
- Autoscaling as control: a proportional controller with delay oscillates or settles (computed); capacity from queueing, with Erlang C derived for c servers (callback to Part 31); predictive scaling.
- Serverless: cold-start distributions; concurrency limits; per-request billing against reserved servers (break-even computed from cited, dated list prices).
- Object storage: S3's semantics (strong read-after-write since 2020, cited); durability from erasure coding across failure domains (callback to Part 28), with a Markov model of failure and repair and MTTDL derived; block against file against object.
- Cloud networking: VPCs and overlays (encapsulation, callback to Part 36); managed load balancers (Part 48); anycast; the cost of egress.
- Infrastructure as code: a plan is a diff between desired and actual state, applied in topological order (callbacks to Parts 18 and 41); drift; immutable infrastructure.
- Multi-tenancy: noisy neighbours in caches and memory bandwidth (callback to Part 9); performance variability (cited); side channels.
- Regions, zones and failure domains; placement for availability (Part 50); data residency.
- Cost engineering: on-demand, reserved and spot pricing (spot interruptions with checkpoints, expected cost computed); right-sizing. The Job on autoscaled containers, in dollars (at cited, dated prices). Ledger row 16.
- Energy and carbon: carbon-aware scheduling; the energy footprint of computing (cited). Outro.
Computed: a toy reconciler converging; packing heuristics against optimal solutions on small instances; autoscaler stability with delay; Erlang C capacity; MTTDL for replication against erasure coding; spot against on-demand costs; the Job's bill. Visuals: a zoom from building to rack to server to VM to container; bins filling; a control loop overshooting and settling; erasure-coded fragments scattered across racks surviving failures; a reconciliation diff. In practice: AWS, GCP and Azure; Kubernetes; Terraform; Lambda and Firecracker; S3; platform and infrastructure engineering; cloud cost reviews. Reading: Barroso, Hölzle & Ranganathan, The Datacenter as a Computer; Burns, Beda & Hightower, Kubernetes: Up and Running; Morris, Infrastructure as Code; Verma et al. 2015; Burns et al. 2016 ("Borg, Omega, and Kubernetes"); Agache et al. 2020; Armbrust et al. 2010; Jonas et al. 2019; Coffman, Garey & Johnson (the bin-packing survey); Dósa 2007; Harchol-Balter (Erlang C).
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
下次适应。 证明下次适应算法使用的箱子数至多是最优值的两倍,并给出使它用到接近两倍的输入。
解答
设下次适应用了 m 个箱子,装载量为 L₁, …, L_m。只有当开启第 i + 1 个箱子的那件物品放不进第 i 个箱子时,它才会开新箱, 所以对每个 i < m 都有 L_i + L_{i+1} > 1。把箱子两两配对 (1, 2)、(3, 4)、…:这 ⌊m/2⌋ 对的总尺寸 S > ⌊m/2⌋。任何装法都至少需要 S 个箱子,所以 OPT ≥ S > ⌊m/2⌋;OPT 是整数,于是 OPT ≥ ⌊m/2⌋ + 1 ≥ (m + 1)/2,即 m ≤ 2·OPT − 1。下界:取 2k 件物品(k 为偶数), ½ 与 ε = 1/k 交替出现。装着 ½ + ε 的箱子放不下下一个 ½,所以每个箱子恰好装一个 ½ 和一件小物品,下次适应用 k 个箱子。最优解把 两个 ½ 配成一箱,共 k/2 箱,再把总尺寸为 1 的 k 件小物品放进另一箱;k/2 + 1 也正是总尺寸,所以 OPT = k/2 + 1,NF = 2·OPT − 2, 比值趋于 2。按仪器里的 ε = 0.01:16 件物品用 8 箱对 5 箱,400 件用 200 箱对 102 箱,比值 1.96。
-
NP 难。 通过把划分问题归约为“两个箱子是否够用”的判定,证明装箱问题是 NP 难的。
解答
给定和为 S 的正整数 a₁, …, a_n,构造物品 x_i = a_i/(S/2);若某个 a_i > S/2,答案为否,输出任意一个固定的否实例(三件 0.6)。物品总尺寸为 2,所以两个容量为 1 的箱子够用,当且仅当两个箱子都恰好装满,即存在子集使 Σ x_i = 1,也就是 Σ a_i = S/2: 一个划分。(S 为奇数无须特殊处理:整数子集和不可能等于 S/2。)这个映射是多项式时间的,而划分问题是 NP 完全的(Karp,1972; 第 26 部分),所以判定 OPT ≤ 2 是 NP 难的,装箱问题也就是 NP 难的。屏幕上的例子:3、1、1、2、2、1 变成 0.6、0.2、0.2、0.4、0.4、 0.2,分成 {3, 1, 1} 和 {2, 2, 1} 两箱;3、3、3、1 变成 0.6、0.6、0.6、0.2,任意两个 0.6 都不能同箱,所以需要三箱。推论:若某个 多项式算法总是用少于 3/2·OPT 个箱子,那么在 OPT = 2 时它必然给出 2(少于 3),从而判定了划分问题;除非 P = NP,这样的算法不存在。 这个界针对绝对比值;渐近地看,多项式时间内可以找到 (1 + ε)·OPT + 1 以内的装法(Fernandez de la Vega 与 Lueker,1981)。
-
厄朗 C。 从 M/M/c 队列的生灭链推导厄朗 C 公式,并由它推出平均等待时间。
解答
设状态 k 为系统中的请求数。到达以速率 λ 把 k 变为 k + 1;有 k 个请求时,忙着的服务器有 min(k, c) 台,所以离开以速率 min(k, c)·μ 把 k 变为 k − 1。平衡时每道割上的流量相等,λπ_k = min(k + 1, c)·μ·π_{k+1},由此得到:k ≤ c 时 π_k = π₀·a^k/k!, 其中 a = λ/μ;k ≥ c 时 π_k = π_c·ρ^{k−c},其中 ρ = a/c < 1。归一化,1/π₀ = Σ_{k<c} a^k/k! + (a^c/c!)/(1 − ρ)。泊松到达看到的是 时间平均,所以一个到达者需要等待,当且仅当它看到 k ≥ c: C(c, a) = Σ_{k≥c} π_k = π_c/(1 − ρ) = [a^c/(c!(1 − ρ))] / [Σ_{k<c} a^k/k! + a^c/(c!(1 − ρ))]。 平均队长 L_q = Σ_{j≥0} j·π_{c+j} = π_c·ρ/(1 − ρ)² = C(c, a)·ρ/(1 − ρ),由利特尔定律得 W_q = L_q/λ = C(c, a)·ρ/(λ(1 − ρ)) = C(c, a)/(cμ − λ)。(在需要等待的条件下,等待时间服从速率为 cμ − λ 的指数分布。)验算:c = 1 时 C = ρ,即第 31 部分的 M/M/1; c = 2、a = 1 时 C = 1/(2 + 1) = 1/3,W_q 为三分之一个服务时间。负载 10 爱尔兰时,13 台服务器给出 C = 0.285,超过 0.2 的目标; 14 台给出 C = 0.174、W_q = 0.174/4 = 0.044 个服务时间,所以表的第一行是 14。
-
平均数据丢失时间。 对 n 个分片、任意 k 个即可恢复、每个分片失效率为 λ、每次只修复一个且修复率为 μ 的情形,推导平均数据丢失 时间。
解答
设状态 i 为失效的分片数;到达 i = n − k + 1 时数据丢失。在状态 i ≤ n − k,失效以速率 λ_i = (n − i)λ 发生;i ≥ 1 时, 修复以速率 μ 发生。设 T_i 为从 i 第一次到达 i + 1 的期望时间。T₀ = 1/(nλ)。对 i ≥ 1,链在 i 停留的平均时间为 1/(λ_i + μ);以 概率 λ_i/(λ_i + μ) 向上走,否则退到 i − 1,需要 T_{i−1} 才回到 i,然后再花 T_i:T_i = 1/(λ_i + μ) + μ/(λ_i + μ)·(T_{i−1} + T_i), 即 λ_i·T_i = 1 + μ·T_{i−1},或 T_i = (1 + μ·T_{i−1})/((n − i)λ)。要丢失数据,链必须依次爬过每一级,所以 MTTDL = Σ_{i=0}^{n−k} T_i。展开得 T_i = Σ_{j≤i} μ^{i−j}/(λ_j λ_{j+1} ⋯ λ_i);当 μ ≫ λ 时,最后一级中 j = 0 的项占主导: MTTDL ≈ μ^{n−k} / (n(n − 1)⋯k · λ^{n−k+1})。三副本(n = 3,k = 1),λ = −ln(0.98) 每年 = 每小时 2.305 × 10⁻⁶,μ = 每小时 1/24,μ²/(6λ³) = 2.36 × 10¹³ 小时,即 27 亿年,与精确和相差不到 0.03%。若丢失时间接近指数分布,一年内丢失的概率为 p = 1 − e^{−1/MTTDL} ≈ 1/MTTDL(以年计),即 3.7 × 10⁻¹⁰,9.4 个 9。多一个分片、多容忍一次丢失,平均时间大约乘上 μ/(nλ) (n 取新的值),这里 μ/λ ≈ 1.8 × 10⁴(从一副本到两副本:49.5 年变成 447,521 年,约 9,000 倍)。所以 9 的个数涨得这么快;也正因 如此,结果的好坏完全取决于“失效相互独立”这个假设。
-
动手。 给调和器加上依赖于第一种资源的第二种资源,并证明在随机删除之后它按依赖顺序收敛。
解答
解答要点。 用
control.plan作比较这一步。比如声明三个卷和五个 pod,每个 pod 在依赖列表里写上一个卷,格式为 名字 →(种类, 属性,依赖)。每一轮:以概率 p 从actual中删除一个随机资源,连同使用它的一切(或者把它们标记为损坏,让计划去更新它们);然后 调用plan(desired, actual),只执行它的第一步,每轮一个动作,就像reconcile每步只启动一个。因为计划按拓扑序列出创建和更新, 它的第一步的依赖总是已经存在:缺失的依赖本身会是更靠前的一步。这就是收敛的证明:设 Φ 为计划的步数;没有删除时,每一轮执行一个 可执行的步骤,使 Φ 减一,所以无论之前删了什么,调和器都会在最后一次删除之后的 Φ 轮之内到达期望状态。照tests/test_cs45_cloud.py的写法测试:对许多随机种子,断言删除停止后 |desired| 轮之内actual == desired,并断言执行日志中从不在卷之前创建 pod。把同一个 循环改成边沿触发,依据会丢失的删除事件行动,就会像第四章那样停在不足的状态。 -
★ 研究。 寿命未知的作业的在线向量装箱,带预测:预测准确时接近最优,不准确时依然稳健。
讨论。 尚未解决。三重困难叠加在一起。即使物品到达时尺寸已知、也没有离开,d 种资源的在线向量装箱的竞争比也随 d 增长,而首次适应 的 O(d) 几乎已是最好(Azar、Cohen、Kamara 与 Shepherd,2013)。有了离开,目标就变了(同时使用的机器数的峰值,或付费的机器小时数), 对手可以让每台机器只剩一个长寿命的作业。而从 Azure 等轨迹中学到的寿命预测(Cortez 等,2017)既有噪声又有重尾。好的答案应固定 d (d = 2 就已经有意思)、一个目标和一种预测误差的度量 η;给出一个算法,η = 0 时代价在最优值的常数倍以内,随 η 平滑退化,最差也在 不用预测的最好保证的常数倍以内;并证明这两个常数之间相匹配的权衡。部分结果,比如带寿命的一维情形、寿命精确已知的二维情形,或在 公开的集群轨迹上的细致评估,就已经有用。
Build the film
python -m videos.cs.cs45.compute # the part's numbers, into .cache/cs45
python tools/build.py cs45 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs45 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs45. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs45.compute
python -m unittest tests.test_cs45_cloud
python tools/build.py cs45