Kayavak

Kayavak / Deeper / Origins

Deeper · Origins

Why each idea exists

The problems people had before each idea, who solved them and when, what competed, and what came after. 93 chapters so far. Also: Comparisons · Derivations · What if?.

CS·01 Start Here: Computers, Programs and Your Toolbox

Foundations of Computing

Before stored programs, "programming" a computer meant rewiring it. ENIAC (1945) was set up for each new problem by plugging cables and setting switches, which could take days. The idea that changed this was to keep the instructions in the same memory as the data, so a new program was just new contents of memory. John von Neumann's First Draft of a Report on the EDVAC (1945) described that design; the Manchester Baby ran the first stored program in June 1948 and Cambridge's EDSAC began regular service in 1949.

Once a program is data, other programs can produce it. That is the whole lineage of this chapter: assemblers turned mnemonics into machine code, compilers (Grace Hopper's A-0 in 1952, FORTRAN in 1957) turned formulas into instructions, and operating systems loaded and ran programs for you. The terminal descends from the teleprinter: a keyboard and a printer wired to a machine, which is why we still say "TTY" and why programs read and write streams of text. Unix (1969 onwards) made that text interface composable: small programs, standard input and output, and pipes between them.

CS·02 Programming Fundamentals & Paradigms

Foundations of Computing

Early programs were one long list of machine instructions with jumps. Two problems grew with their size: the same piece of work was written out again and again, and nobody could follow where control went. The first answer was the subroutine: David Wheeler's "Wheeler jump" on Cambridge's EDSAC (around 1949–51) let a program call a shared piece of code and come back. Everything in this chapter called a function descends from it.

The second answer came in the 1960s. Corrado Böhm and Giuseppe Jacopini proved in 1966 that sequence, selection and iteration are enough to express any computation, and Edsger Dijkstra's 1968 letter Go To Statement Considered Harmful argued that programs should be built from those shapes so their text mirrors what happens when they run. That is structured programming, and it's why every language you'll meet has if, while and functions rather than only jumps.

The paradigms came from different problems. Lisp (John McCarthy, 1958) treated programs as mathematical functions over symbols. Simula 67 (Ole-Johan Dahl and Kristen Nygaard), built for simulations, bundled data with the procedures that act on it: the first objects. Smalltalk (Alan Kay's group at Xerox PARC, 1970s) made "everything is an object sending messages" a whole language. ML (Robin Milner, 1973) added types the compiler infers for you. Modern languages borrow from all of them.

CS·03 Data Structures

Foundations of Computing

A computer's memory is one long row of numbered bytes. That's all the hardware offers. Every data structure is an answer to the same question: how do I lay data out in that row so the operations I need are cheap?

The answers arrived as problems demanded them. Arrays came straight from how memory is addressed: item i lives at start + i × size, so FORTRAN (1957) made them its central type. Linked lists were invented by Allen Newell, Cliff Shaw and Herbert Simon for their Information Processing Language (1955–56), because their early AI programs needed structures that grew and changed shape while running. Hashing appears in an internal IBM memo by Hans Peter Luhn in 1953: turn a key into a number and use it as an address. Balanced trees followed when sorted data had to stay fast under inserts: AVL trees (Georgy Adelson-Velsky and Evgenii Landis, 1962), B-trees for disks (Rudolf Bayer and Edward McCreight, 1972), red-black trees (Leonidas Guibas and Robert Sedgewick, 1978). J. W. J. Williams introduced the binary heap with heapsort in 1964.

None of these replaced the others, because each makes a different operation cheap at another's expense.

CS·04 Algorithms

Foundations of Computing

Algorithms are far older than computers. Euclid's method for the greatest common divisor (around 300 BCE) is still taught unchanged, and the word itself comes from the name of the ninth-century Persian mathematician Muhammad ibn Musa al-Khwarizmi, whose book on calculating with Hindu–Arabic numerals spread step-by-step arithmetic through Europe.

What computers added was the need to compare procedures. A machine that does millions of steps a second makes the difference between n² and n log n the difference between a second and a week. John von Neumann wrote merge sort for the EDVAC in 1945; Tony Hoare invented quicksort around 1959–60 while working on machine translation; Edsger Dijkstra found his shortest-path algorithm in 1956 (published 1959), reportedly in about twenty minutes at a café. Donald Knuth's The Art of Computer Programming (from 1968) turned the analysis of algorithms into a discipline, and in 1976 he fixed the meanings of O, Ω and Θ that computer scientists use, borrowing notation from Paul Bachmann (1894) and Edmund Landau.

CS·05 Discrete Mathematics

Foundations of Computing

Each branch of discrete mathematics started with a concrete puzzle. Probability began with a gambling question that Blaise Pascal and Pierre de Fermat settled in letters in 1654: how to split the stakes of a game interrupted before the end. Graph theory began in 1736 when Leonhard Euler proved that nobody could walk across all seven bridges of Königsberg exactly once, by throwing away everything except which land touched which bridge. Logic as algebra began with George Boole's The Laws of Thought (1854), which treated true and false as values you can calculate with. Set theory came from Georg Cantor's work on infinity in the 1870s.

For a long time these looked like separate curiosities. Then in 1937 Claude Shannon's master's thesis showed that Boole's algebra describes relay switching circuits exactly, which made it the design language of every digital computer. Computing gathered the rest: proofs to show programs correct, counting to size search spaces, graphs for networks and dependencies, probability for hashing, sampling and randomised algorithms.

CS·06 Number Systems & Data Representation

Foundations of Computing

Gottfried Leibniz described binary arithmetic in 1703, but nobody needed it until machines did. Two-state devices (relays, then vacuum tubes, then transistors) are far easier to build reliably than ten-state ones: telling "on" from "off" survives noise that would blur ten voltage levels. Once Shannon showed in 1937 that switching circuits compute Boolean logic, binary won, and every other representation in this chapter is a convention for what a pattern of bits means.

Those conventions were fought over. Early machines represented negative numbers in sign-magnitude or ones' complement, which have two zeros and need extra circuitry; two's complement won because the same adder works for signed and unsigned numbers, and C23 and C++20 finally made it the only allowed representation. Floating point was a mess of incompatible formats until the IEEE 754 standard (1985), led by William Kahan, who received the Turing Award in 1989 largely for it. Text went from dozens of national character sets to ASCII (1963), then to Unicode (1991) for every writing system, and UTF-8, designed by Ken Thompson and Rob Pike in 1992, became the way almost the whole web stores it.

CS·07 Computer Architecture

Foundations of Computing

Processors got faster much more quickly than memory. By the mid-1990s a CPU could finish dozens of instructions in the time one value arrived from RAM; William Wulf and Sally McKee called it "the memory wall" in 1995. Most of modern computer architecture is the response to that gap and to the limits of making one instruction stream faster.

The ideas arrived one by one. Pipelining, overlapping the stages of successive instructions, appeared in IBM's Stretch (1961). Maurice Wilkes proposed small fast "slave memories" in 1965, and IBM's System/360 Model 85 (1968) shipped the first commercial cache. In the late 1970s and early 1980s, IBM's 801 research machine, David Patterson's Berkeley RISC and John Hennessy's Stanford MIPS argued for RISC: simple, regular instructions a compiler can schedule and hardware can pipeline deeply. Around 2005 the old trick of raising the clock speed stopped working, because power and heat no longer fell as transistors shrank (the end of Dennard scaling), so chips turned to multiple cores and wider vector units instead.

CS·08 Operating Systems

Foundations of Computing

The first computers ran one program at a time, loaded by hand, and sat idle while people prepared the next. Batch systems in the 1950s queued jobs so the machine never waited for an operator; then the machine waited for tapes and printers instead, and people waited hours for results. Time-sharing answered that: switch between many users' programs so fast that each feels it has the machine. MIT's CTSS, led by Fernando Corbató, demonstrated it in 1961; Multics (MIT, Bell Labs and General Electric, from 1965) tried to make it a dependable utility; Ken Thompson and Dennis Ritchie, after Bell Labs left Multics, built the much smaller Unix from 1969.

Sharing one machine safely needed new ideas, each still in your kernel. The Atlas computer at Manchester (1962) had the first virtual memory: each program sees its own address space, and pages move between fast and slow memory automatically. Dijkstra introduced semaphores in 1965 to coordinate concurrent processes. In 1971 Edward Coffman and colleagues set out the four conditions under which processes deadlock, which the chapter lists. Hardware support for privilege levels let the kernel stop one program from corrupting another or the system.

CS·09 Networking Fundamentals

Foundations of Computing

Telephone networks reserve a whole circuit for each call, which is wasteful for computers that send short bursts with long silences. In the early 1960s Paul Baran at RAND, looking for networks that could survive damage, and Donald Davies at Britain's National Physical Laboratory, looking for efficient computer communication, independently proposed packet switching: chop data into small blocks that travel separately and share the lines. ARPANET sent its first message in October 1969.

As other networks appeared (radio, satellite), they needed to interconnect. Vint Cerf and Bob Kahn's 1974 paper described a protocol for joining different networks through gateways; it split into TCP and IP, and the ARPANET switched to TCP/IP on 1 January 1983. Names came next: Paul Mockapetris designed DNS in 1983 to replace a single, hand-edited hosts file. In 1986 the network suffered "congestion collapse", throughput between two neighbouring sites in Berkeley falling by a factor of about a thousand, until Van Jacobson's 1988 algorithms made TCP back off when packets are lost. Netscape's SSL (1995) added encryption for the commercial web, now TLS 1.3 (2018); QUIC (2021) and HTTP/3 (2022) moved reliable, encrypted streams onto UDP.

CS·10 Compilers & Runtimes

Foundations of Computing

In the early 1950s most programmers believed a machine could never translate formulas into code as good as a person's. John Backus's team at IBM built FORTRAN (released 1957) to prove otherwise, and spent much of their effort on optimisation, because they knew nobody would adopt a compiler that produced slow programs. They succeeded, and programming in mathematical notation became normal.

The rest of the pipeline followed. The ALGOL 60 report described its syntax in a notation now called BNF (after John Backus and Peter Naur), so grammars became formal objects that parsers could be built from. John McCarthy's Lisp (1958–60) introduced garbage collection, freeing memory automatically once nothing could reach it. Research on Smalltalk and then Self (David Ungar, Craig Chambers and Urs Hölzle, late 1980s–1990s) made just-in-time compilation with speculative optimisation practical; that work led, through a startup Sun acquired, to Java's HotSpot (1999). In 1991 Ron Cytron and colleagues published an efficient way to build SSA form, now the core of most optimising compilers, and from 2000 Chris Lattner's LLVM made a reusable optimiser and code generator that many languages (Rust, Swift, Zig, Clang's C and C++) share.

CS·11 Computer Science Mastery Projects

Foundations of Computing

Reading about a mechanism and being able to build it are different abilities, and only the second survives contact with a real problem. That's an old idea in teaching (apprenticeships, laboratory courses) and a well-measured one in learning research: people remember more of what they generate and retrieve themselves than of what they reread. When Richard Feynman died in 1988 his blackboard read "What I cannot create, I do not understand."

Computer science has a long tradition of learning by rebuilding the classics: courses where students write a small operating system, a compiler for a toy language, a network stack or a database from scratch. The projects in this chapter follow that tradition: each forces several earlier chapters to work together, because real systems never use one idea alone.

FE·00 Start Here: How the Web Works

The Web Frontend

In March 1989 Tim Berners-Lee, at CERN, proposed a way to share documents between physicists using different computers: link documents across machines by address. By the end of 1990 he had the three pieces this chapter introduces: a way to name a document anywhere (the URL), a protocol to fetch it (HTTP), and a format for writing it with links (HTML), plus the first browser and server. The web went public in 1991. NCSA Mosaic (1993) showed images inside pages and made it popular; Netscape (1994) made it a business. CERN put the web's technology in the public domain in April 1993, which is a large part of why it spread.

The web won over other systems of the time, such as Gopher, partly because it asked so little: any server could link to any other without permission, and a broken link was allowed. That openness is still its shape: anyone can publish, anyone can link, and browsers must cope with anything.

FE·12 The Web Platform

The Web Frontend

Early web pages were documents. When Netscape added JavaScript in 1995, pages became programs, and a new problem appeared at once: a script from one site, running in your browser next to your bank's page, could read it. Netscape Navigator 2.0 introduced the same-origin policy in response: a page may freely use resources only from its own origin. Nearly every rule in this chapter descends from that decision to run code from strangers side by side.

The platform kept growing: storage (cookies in 1994, then localStorage and IndexedDB), background work, cameras, payments. Each new capability had to fit the same model of origins and permissions. After the Spectre attacks of 2018 showed that code in one page could read memory in the same process through CPU side channels, browsers went further: Chrome shipped site isolation, putting each site in its own process, and new rules such as cross-origin isolation gate the most powerful features.

FE·13 HTML

The Web Frontend

Berners-Lee's first HTML (1991) borrowed from SGML, a document markup standard: tags described what text was (a heading, a list, a link), not how it looked. Then the browser wars of the mid-1990s pushed the other way: Netscape and Microsoft added presentational tags like <font> and <blink>, and pages were laid out with tables. CSS (1996) and the W3C's push for structure tried to separate meaning from presentation again.

The W3C's next plan, XHTML 2, abandoned compatibility with existing pages. In 2004 Apple, Mozilla and Opera formed the WHATWG to evolve HTML instead, specifying the messy reality browsers already handled: forms that validate themselves, <video>, semantic sectioning, and a precise parsing algorithm for every error. That became HTML5 (W3C Recommendation 2014), and since 2019 the W3C and WHATWG agree on one HTML Living Standard maintained by the WHATWG. Semantic HTML matters now mostly because of machines that read pages: assistive technology, search engines and browsers' own features (reader modes, autofill).

FE·14 CSS

The Web Frontend

By 1994 page authors wanted control over fonts, colours and layout, and browsers were adding presentational HTML to give it to them, which mixed appearance into every document. Håkon Wium Lie proposed Cascading Style Sheets at CERN in October 1994, and with Bert Bos turned it into CSS1, a W3C Recommendation in December 1996. The word cascading was the key idea: several parties have a say in how a page looks (the browser's defaults, the author, and the reader, who might need larger text), and the cascade is the rule for combining their wishes.

Layout was the long struggle. For a decade, pages were laid out with tables and then with floats, techniques built for other purposes. Flexbox (widely usable from about 2012–2015) gave one-dimensional layout, and CSS Grid, which shipped in all major browsers in 2017, gave real two-dimensional layout. Modern additions (custom properties, container queries, :has(), cascade layers, nesting) have made CSS a language people architect rather than patch.

FE·15 JavaScript

The Web Frontend

In May 1995 Netscape asked Brendan Eich for a scripting language for the browser, simple enough for designers, that "looked like Java" for marketing reasons. He wrote the first version in about ten days. It borrowed syntax from Java, first-class functions from Scheme and prototypes from Self, and its rushed edges (type coercion, ==, typeof null) have been with us ever since, because the web can't break old pages.

Netscape submitted it to Ecma for standardisation (ECMAScript, 1997). After a long stall, ES5 (2009) tidied the language, and ES2015 transformed it: let and const, classes, modules, promises, arrow functions. Since then a smaller edition ships every year. Two other events made JavaScript the world's most widely deployed language: Gmail and Google Maps (2004–05) showed what in-page requests could do ("Ajax", named in 2005), and Node.js (Ryan Dahl, 2009) took V8 out of the browser and onto servers.

FE·16 TypeScript

The Web Frontend

By around 2010, teams at large companies were writing JavaScript applications of hundreds of thousands of lines, in a language with no way to say what a function expects. Renaming a field meant searching text and hoping. Google's Closure Compiler used type annotations in comments; Microsoft's answer, led by Anders Hejlsberg (who had designed Turbo Pascal and C#), was TypeScript, released publicly in October 2012: a superset of JavaScript whose types are checked and then erased, so the output is ordinary JavaScript.

Two design choices explain why it won over alternatives like Facebook's Flow. It describes JavaScript as it's actually written, so its type system is structural (shapes, not names) and deliberately unsound in places to fit real code. And the editor experience (autocomplete, rename, go-to-definition) came from the same checker, so developers felt its value before they trusted its errors.

FE·17 DOM & Browser APIs

The Web Frontend

When scripts arrived in 1995–96, each browser exposed the page to them differently: Netscape's document.layers, Microsoft's document.all. Code had to be written twice, and much of it sniffed the browser to decide which half to run. The W3C's Document Object Model (Level 1, 1998) defined one tree of nodes and one API for every browser, but real compatibility took another decade. jQuery (John Resig, 2006) became the most widely used JavaScript library by papering over the differences with one simple API.

As browsers converged, the platform absorbed what libraries had provided: querySelector (selectors from CSS, 2008–09 in browsers), classList, fetch (2015), and observers (MutationObserver, IntersectionObserver, ResizeObserver) that replaced polling and fragile event tricks. Today the DOM is consistent enough that most pages need no compatibility layer at all.

FE·18 Browser Internals

The Web Frontend

Early browsers were single programs: one crashing page, or one runaway script, took down every tab. In September 2008 Google released Chrome with a multi-process architecture, putting renderers in separate, sandboxed processes, and a new JavaScript engine, V8, that compiled JavaScript to machine code. Other browsers followed on both fronts: JIT-compiling engines (SpiderMonkey, JavaScriptCore) made heavy web applications possible, and process separation became standard.

The engines themselves have a lineage. Apple built WebKit (2001–03) from KDE's KHTML; Google forked WebKit into Blink in 2013. Mozilla's Gecko descends from Netscape. In 2018, after the Spectre attacks, Chrome turned on site isolation, a process per site, including cross-site iframes. Rendering moved work off the main thread too: a separate compositor thread scrolls and animates even while JavaScript runs.

FE·19 Frontend Networking

The Web Frontend

HTTP/1.0 opened a new TCP connection for every request; pages with dozens of images paid a handshake each time. HTTP/1.1 (1997) kept connections open but still allowed one request at a time per connection, so browsers opened about six per host and sites spread assets across domains. Google's experimental SPDY (2009) multiplexed many requests over one connection and became HTTP/2 (2015). Its remaining weakness, that one lost TCP packet stalls every stream, led to QUIC and HTTP/3 (2022).

The browser's other networking rules came from security problems. Cookies (Lou Montulli at Netscape, 1994) gave the stateless web a memory, and were sent with every request to their site, which made cross-site request forgery possible; the SameSite attribute, with Lax as the default in Chrome from 2020, was the fix. The same-origin policy blocked useful cross-site APIs as well as attacks, so CORS (a W3C Recommendation in 2014) let servers opt in. For real-time updates, long polling gave way to WebSockets (2011) and server-sent events.

FE·20 Accessibility

The Web Frontend

Disabled people were among the web's earliest enthusiasts, because text that a screen reader can speak is more usable than printed paper. But as pages turned into images, tables-for-layout and script-built widgets, they broke for those same users. The W3C launched the Web Accessibility Initiative in 1997 and published WCAG 1.0 in 1999; WCAG 2.0 (2008) restated the guidelines as testable success criteria, organised by the four principles perceivable, operable, understandable and robust; 2.1 (2018) and 2.2 (2023) added mobile, low-vision and cognitive needs.

Law followed. The US Americans with Disabilities Act (1990) and Section 508 (amended 1998 to cover electronic information) were applied to websites through court cases; the European Accessibility Act applies to many products and services from June 2025. WAI-ARIA (a Recommendation in 2014) gave script-built widgets a way to tell assistive technology what they are, because HTML lacked native elements for many of them.

FE·21 UI Architecture

The Web Frontend

Keeping a screen consistent with changing data is an old problem. Trygve Reenskaug described Model–View–Controller at Xerox PARC in 1978–79 for Smalltalk: separate the data from its presentation and from input handling. On the web, the first big single-page apps (Gmail, 2004) did this by hand, and pages filled with code that found elements and patched them; every new feature added more ways for the screen and the data to disagree.

Frameworks attacked that disagreement. Backbone and AngularJS (both 2010) added structure and two-way data binding. React (Facebook, open-sourced in 2013) proposed something more radical: re-describe the whole screen from the current state on every change, and let the framework work out the minimal DOM updates. Its one-way data flow and components spread to almost every framework since. More recent frameworks (Solid, Svelte, Angular, Vue) use signals, which track exactly which values each piece of the screen depends on, an idea with roots in spreadsheets and in earlier reactive libraries such as Knockout.

FE·22 React

The Web Frontend

Inside Facebook around 2011, engineers struggled with interfaces where many parts changed in response to each other (the notification count, chat, the news feed). Jordan Walke built a prototype that re-rendered components from scratch on every change and compared the result with the previous one, applying only the differences. It was released as React in 2013 and initially met scepticism, mostly about JSX mixing markup into JavaScript.

React then changed itself several times. React 16 (2017) rewrote the internals as Fiber, so rendering can be split into pieces and interrupted. Hooks (React 16.8, February 2019) replaced class components with functions that use state and effects, and spread the idea of composable stateful logic. React 18 (2022) made rendering concurrent, so urgent updates can interrupt slow ones. React 19 (2024) brought Server Components and Actions into the stable release, and the React Compiler automates the memoisation people used to write by hand.

FE·23 Angular

The Web Frontend

AngularJS (Miško Hevery and Adam Abrons, 2009–10, then Google) made two-way data binding mainstream: change the data and the page updated, type in a field and the data changed. It ran a "digest cycle" that re-checked every binding until nothing changed, which became slow and unpredictable in large apps. Google rewrote it from scratch as Angular (2016), in TypeScript, with components, dependency injection, ahead-of-time compiled templates and RxJS observables, aimed at large enterprise teams. The rewrite was incompatible, which upset many AngularJS users.

Angular then evolved in steps rather than rewrites. The Ivy compiler (default in Angular 9, 2020) made templates compile to smaller, faster instructions. Standalone components removed the need for NgModules. Signals (from Angular 16, 2023) introduced fine-grained reactivity, which lets Angular drop Zone.js, the library that patched every browser API to know when to check for changes.

FE·24 Full-stack Frameworks

The Web Frontend

The web started with server rendering: CGI scripts, then PHP (1995), Rails (2004) and others produced finished HTML on every request. Single-page apps (2010s) moved rendering into the browser for richer interaction, and paid for it: blank pages until JavaScript loaded, poor results in search engines, slow phones doing all the work. Frameworks then tried to get both. Next.js (2016) made server rendering of React apps routine; static generation and incremental regeneration served pre-built pages from CDNs.

The cost that remained was hydration: the browser re-running every component's JavaScript just to attach event handlers to HTML it already had. The 2020s produced several answers: islands (named by Katie Sylor-Miller in 2019 and popularised by Jason Miller and Astro), where only interactive parts ship JavaScript; resumability (Qwik), which serialises enough state to skip re-running; and React Server Components (announced December 2020), which run only on the server and send no code to the browser.

FE·25 State Management

The Web Frontend

When React made components the unit of UI, a new question appeared: where does data live when many distant components need it? Facebook's Flux architecture (2014) answered with one-directional flow through a dispatcher to stores. Redux (Dan Abramov and Andrew Clark, 2015) simplified it into one store, updated only by pure reducer functions responding to actions, which made every change traceable and enabled "time-travel" debugging. For a few years nearly every React app put nearly everything in Redux.

Then people noticed that most of that state was a copy of something on a server, with all the problems of caching: staleness, refetching, deduplication, errors. Libraries such as React Query (TanStack Query, 2019–20) and SWR treated server state as a cache with its own rules, and client stores shrank to what genuinely belonged to the browser. For state shared between devices or people, CRDTs (formalised by Marc Shapiro and colleagues in 2011) let copies merge without a central referee.

FE·26 Frontend Testing

The Web Frontend

Browser automation began with Selenium (Jason Huggins at ThoughtWorks, 2004), which drove a real browser to click and type like a person; WebDriver later became a W3C standard (2018). For years these tests were slow and flaky, failing on timing rather than bugs, so teams wrote few of them. Mike Cohn's test pyramid (2009) put many fast unit tests at the bottom and few end-to-end tests at the top.

Frontends challenged the pyramid: most bugs live where components meet the DOM, data and each other, which unit tests of pure functions don't reach. Testing Library (Kent C. Dodds, 2018) made component tests query the page the way users do (by role, label and text) instead of by implementation details, and Dodds proposed the testing trophy, weighted towards integration tests. Cypress (2017) and Playwright (Microsoft, 2020) made end-to-end tests faster and much less flaky with automatic waiting. Mutation testing, proposed by Richard Lipton in 1971, checks the tests themselves by planting bugs and seeing whether any test fails.

FE·27 Frontend Performance

The Web Frontend

In 2007 Steve Souders, then at Yahoo, published High Performance Web Sites and made a finding that redirected the field: most of the time users waited was spent in the browser (downloading, parsing, waiting on scripts), not on the server. His rules (fewer requests, cache, put scripts at the bottom) and the YSlow tool started frontend performance as a discipline.

Measuring it well took longer. Lab tools gave numbers that didn't match what real users felt, and metrics such as "onload" didn't reflect when a page looked ready. In 2020 Google introduced Core Web Vitals, three field metrics measured on real users' devices: loading (LCP), responsiveness and visual stability (CLS). Responsiveness was first measured by First Input Delay, which only covered the first interaction; Interaction to Next Paint replaced it in March 2024, because the slowest interactions usually come later. Their use as a search ranking signal (from 2021) made businesses care.

FE·28 Frontend Security

The Web Frontend

When pages began showing content from their users (comments, profiles, search terms), they began running those users' scripts by accident. Microsoft engineers named the problem cross-site scripting around 2000. Its most famous demonstration was the Samy worm (2005): a script in one MySpace profile added its author as a friend of everyone who viewed it and copied itself into their profiles, reaching over a million accounts in about a day.

Defences grew in layers. Frameworks escaped output by default. Mozilla proposed Content Security Policy, first shipped in Firefox 4 (2011), so a page can declare which scripts may run. SameSite cookies closed most cross-site request forgery. Then the attack surface moved to the code teams import: the 2018 event-stream incident, where a new maintainer of a popular npm package added code to steal cryptocurrency wallets, and the 2024 compromise of the polyfill.io domain, which served malicious script to over a hundred thousand sites, made the supply chain part of frontend security.

FE·29 PWAs, Workers & WebAssembly

The Web Frontend

Web pages were only usable online, and only on one thread. Each limitation got a first attempt that failed and a second that stuck. AppCache (about 2009) tried to make pages offline with a declarative manifest and became known for its traps; the Service Worker (shipped in Chrome in 2015) replaced it with a programmable proxy between the page and the network. In 2015 Alex Russell and Frances Berriman coined progressive web apps for sites that use it to install and work offline like apps. Web Workers (around 2009) gave pages background threads with no shared memory.

For running other languages at near-native speed, Mozilla's asm.js (2013) showed that a strict subset of JavaScript could be compiled ahead of time very efficiently. Browser vendors then designed WebAssembly together: a compact, sandboxed binary format, shipped in all major browsers in 2017 and a W3C Recommendation in 2019. It's how this library runs Python, SQL and Go in your browser.

FE·30 Build Tooling & Monorepos

The Web Frontend

For most of its life JavaScript had no module system: scripts shared one global scope and depended on load order. Node.js (2009) adopted CommonJS require, and npm (Isaac Schlueter, 2010) made publishing and installing packages trivial, which grew into the largest package registry in existence. Browsers couldn't load CommonJS, so bundlers appeared: Browserify (2011) and webpack (Tobias Koppers, 2012) followed every require and produced one file a browser could run. ES2015 finally standardised modules (import/export), static enough for tools to remove unused code (tree shaking).

Tools then got faster and simpler. esbuild (Evan Wallace, 2020), written in Go, bundled 10–100× faster than JavaScript-based tools; Vite (Evan You, 2020) served native modules in development and bundled only for production. The dependency explosion had a cost: in 2016 the removal of left-pad, an 11-line package, broke builds across the industry, and lockfiles, integrity hashes and stricter package managers (pnpm) followed.

FE·31 Frontend Deployment

The Web Frontend

Deploying a website once meant copying files to a server over FTP, overwriting them one by one while visitors were loading pages. Content delivery networks (Akamai, 1998) moved copies close to users to cope with traffic spikes and distance. Two ideas then reshaped frontend deployment. First, cache-busting by filename: if every asset's name includes a hash of its contents, it can be cached forever, and a new version simply has a new name. Second, platforms that deploy a whole build atomically to a CDN and switch a pointer, popularised around 2015–16 under the label "Jamstack" by Netlify and others, with a preview URL for every branch.

Server rendering brought servers back into frontend deployment, now in several shapes: long-running Node servers, serverless functions, and edge runtimes that run code in many CDN locations.

FE·32 Frontend Observability

The Web Frontend

Server teams have logs and metrics for every request; frontend teams were long blind, because their code runs on millions of devices they never see. Early tools hooked window.onerror and sent reports home, but the reports were nearly useless: minified code reported errors at line 1, column 40,000. Source maps (developed at Google and Mozilla around 2009–11) mapped compiled code back to the original files, which made client error tracking practical.

Browsers then began exposing timing data: the Navigation Timing API (2012), Resource Timing, and later PerformanceObserver and the APIs behind Core Web Vitals. Real-user monitoring (RUM) grew out of these, collecting what users actually experienced instead of what lab tests predicted. Distributed tracing reached the browser through standards like W3C Trace Context (2020) and OpenTelemetry, so a slow click could be followed into backend services.

FE·33 Frontend Projects

The Web Frontend

Frontend work is where every earlier chapter meets one person's screen: HTML's meaning, CSS's layout, JavaScript's event loop, the network, accessibility, performance and security all show up in a single feature. Chapters teach them one at a time; real products need them at once, under constraints (a slow phone, a screen reader, a flaky network, a deadline). These projects exist to practise that combination, the way architecture students build models and medical students practise on cases.

BE·00 Start Here: What a Backend Is

The Backend

The first web servers only sent files. To answer with something computed (search results, a shopping basket) servers needed to run a program per request: the Common Gateway Interface (NCSA, 1993) started a new process for each one, which was simple and slow. Java servlets (1997) kept a program running and handled each request on a thread, and enterprise Java (J2EE, 1999) added transactions, messaging and remote objects, at a large cost in complexity. Spring (2002–04), Rails (2004) and Django (2005) made server programming lighter; Node.js (2009) showed one thread with an event loop could serve many connections.

Underneath every one of those, the backend's job hasn't changed: receive a request over the network, apply the business's rules, read or change stored data, and answer, for many people at once, without losing anything.

BE·33 Language Foundations

The Backend

Java began in 1991 as "Oak", in Sun Microsystems' Green Project led by James Gosling, aimed at consumer devices. Those devices used many different processors, so the team compiled to bytecode for a virtual machine instead of to one chip. When the web arrived, the same property ("write once, run anywhere") made Java the language of browser applets; Java 1.0 shipped in January 1996. Applets faded, but the virtual machine, garbage collection and a large standard library made Java the main language for enterprise servers.

Its conservative design was deliberate: C-like syntax to be familiar, no pointer arithmetic or manual memory freeing to be safe, checked exceptions to make error handling visible. Sun open-sourced Java as OpenJDK (2006–07) and Oracle acquired Sun in 2010. Since 2018 Java has shipped every six months, and the language has gained records, pattern matching and sealed types that make it much more expressive than its 1990s self.

BE·34 Object-Oriented Programming and Its Alternatives

The Backend

Object-oriented programming began with simulation. Simula 67 (Ole-Johan Dahl and Kristen Nygaard, Norway) modelled ships and queues as objects carrying their own data and behaviour, with classes and inheritance. Alan Kay's team at Xerox PARC built Smalltalk in the 1970s around objects sending messages, and Kay has said the messaging, not the classes, was the important idea. C++ (Bjarne Stroustrup, from 1979) and then Java (1995) made classes mainstream for large commercial software.

Experience refined the practice. Barbara Liskov's 1987 keynote, and her 1994 paper with Jeannette Wing, defined when a subtype can safely stand in for its parent: the Liskov substitution principle. The "Gang of Four" Design Patterns book (1994) urged "favour object composition over class inheritance" after a decade of fragile hierarchies. Today's alternatives (records and sealed types, algebraic data types, functional core with an imperative shell) keep the parts that protect invariants and drop the parts that tangled code.

BE·35 Collections

The Backend

Java 1.0 (1996) had only Vector, Hashtable and arrays: every method synchronised whether you needed it or not, and no common interfaces. Java 1.2 (1998) added the Collections Framework, designed by Joshua Bloch: interfaces (List, Set, Map) separated from implementations (ArrayList, HashSet, HashMap), so code could depend on the shape of the data and swap the structure. Java 5 (2004) made collections generic and added java.util.concurrent's concurrent maps and queues; Java 8 (2014) added streams and made HashMap resist pathological hashing by turning long chains into trees; Java 21 (2023) added sequenced collections with a defined first and last element.

BE·36 Generics and Type Parameters

The Backend

Before Java 5 (2004), a List held Objects: you cast everything you took out, and a wrong type surfaced as a ClassCastException far from where it went in. Generic types were well known from ML (1970s) and C++ templates, and Martin Odersky and Philip Wadler showed how to add them to Java in the Pizza language (1997) and then GJ (1998), which became Java 5's generics.

The decisive constraint was compatibility: millions of lines of existing code and libraries used raw collections, and compiled classes had to keep working. So Java chose erasure: generic types are checked by the compiler and then removed, leaving the old bytecode. C# made the opposite choice a year later (.NET 2.0, 2005), with generics kept at run time, at the cost of breaking compatibility once. Most of Java generics' oddities (no new T(), no List<int>, wildcards) follow from that one decision.

BE·37 Functional Programming

The Backend

Functional programming is older than computers. Alonzo Church's lambda calculus (1930s) described computation purely as applying functions, and John McCarthy's Lisp (1958) brought it to machines. ML, Haskell (1990) and others explored pure functions, immutability and types, mostly in research. Mainstream languages kept loops and mutation.

Two pressures changed that. Multicore processors (mid-2000s) made shared mutable state a source of race conditions, and code without mutation is safe to run in parallel. And data processing at scale (Google's MapReduce, 2004, named after two functional operations) showed that describing what to compute lets a system decide how. Java added lambdas and streams in Java 8 (2014); C#, JavaScript, Python and C++ added similar features in the same decade. Gatherers (final in JDK 24) let streams carry custom intermediate steps.

BE·38 Concurrency

The Backend

Java had threads from version 1.0 (1996), at a time when most machines had one processor and threads mainly kept interfaces responsive. Its original memory model, the rules for when one thread sees another's writes, turned out to be broken: researchers including Bill Pugh showed that common idioms (like double-checked locking) failed and that the specification forbade optimisations every JVM performed. JSR 133 rewrote it for Java 5 (2004) around the happens-before relation, and Doug Lea's java.util.concurrent arrived in the same release with executors, locks, atomics and concurrent collections.

Multicore processors then made concurrency unavoidable, and threads became the bottleneck for servers: each platform thread costs about a megabyte of stack and an operating-system thread, so tens of thousands of waiting connections meant tens of thousands of threads. Reactive frameworks avoided threads at the cost of harder code. Virtual threads (Project Loom, final in Java 21, 2023) made threads cheap again, so blocking, sequential code scales.

BE·39 Modern Java Through JDK 27

The Backend

For most of its history Java shipped a big release every two to three years, and each was late: Java 7 took nearly five years (2006 to 2011) and Java 9 slipped repeatedly while the module system was finished. Features that were ready waited for features that weren't. In 2017 Oracle announced a fixed six-month cadence starting with Java 10 (March 2018): whatever is ready ships, and the rest waits six months. Long-term-support releases give organisations stable points: 11, 17, 21 and 25, now every two years.

The cadence came with a pipeline for change: features are proposed as JEPs, tried as preview or incubator features, and finalised once feedback settles them. The result is a steady modernisation (records, pattern matching, sealed types, virtual threads, faster start-up) without the big-bang releases that made upgrades frightening.

BE·40 JVM Internals and Other Runtimes

The Backend

Early JVMs interpreted bytecode, and Java earned a reputation for being slow. Research on Smalltalk and Self (David Ungar, Craig Chambers, Urs Hölzle and others, late 1980s and 1990s) had shown how a dynamic runtime could beat static compilers: watch the program run, compile the hot paths with assumptions it observed, and undo them if they break. Several of those researchers founded Animorphic Systems, which Sun bought in 1997; their work became HotSpot, the JVM shipped from 1999 and still the base of OpenJDK.

Garbage collection followed a similar path, from long stop-the-world pauses to collectors that do most work concurrently: G1 (default since Java 9), ZGC (production-ready in Java 15, generational in Java 21) and Shenandoah, with pauses typically under a millisecond. Other runtimes took different points on the spectrum: Go compiles ahead of time with a concurrent collector, .NET has its own JIT, and GraalVM can compile Java ahead of time into a native image.

BE·41 Memory and Performance

The Backend

"Premature optimization is the root of all evil" comes from Donald Knuth's 1974 paper Structured Programming with go to Statements, and the full sentence is more useful than the slogan: we should forget about small efficiencies about 97% of the time, but not pass up our opportunities in that critical 3%. Finding the 3% is the subject of this chapter.

Tools for finding it improved slowly. Sampling profilers appeared with Unix (prof, then gprof in 1982), but on the JVM most profilers suffered safepoint bias, only sampling at points the JVM chose, so they blamed the wrong code. Async-profiler and Java Flight Recorder (open-sourced in Java 11, 2018) sample without that bias and cheaply enough for production. Brendan Gregg's flame graphs (2011) made the results readable at a glance.

BE·42 Modules, Packaging and Dependency Conflicts

The Backend

Java's classpath was simple: a list of JARs, searched in order, first match wins. As applications grew to hundreds of libraries, two versions of the same library would both end up on the classpath, and which one loaded depended on order: "JAR hell", with NoSuchMethodError appearing only when a rarely used path ran. OSGi (from 1999–2000) answered with a module system where each bundle declares what it imports and exports and can have its own versions, powerful and complex. Java's own module system (Project Jigsaw, Java 9, 2017) added strong encapsulation and reliable configuration, but not multiple versions of one module.

Dependency resolution itself is a design choice. Maven picks the version nearest to your project in the dependency tree; Gradle picks the highest requested; Go (2018, Russ Cox) chose minimal version selection: the oldest version that satisfies every requirement, making builds reproducible without a lockfile. Shading, BOMs and platforms are the tools for living with conflicts the resolver can't fix.

BE·43 Build Systems

The Backend

Stuart Feldman wrote make at Bell Labs in 1976 after a colleague wasted a morning debugging a program that hadn't been recompiled: make rebuilds only what's out of date, by comparing file timestamps along declared dependencies. Java projects used Ant (2000), essentially make in XML, then Maven (1.0 in 2004), which replaced scripts with conventions (a standard directory layout and life cycle) and added dependency download from repositories. Gradle (2008–2012) combined conventions with a programmable build and incremental task execution.

Large companies needed more. Google's internal Blaze, open-sourced as Bazel in 2015, treated builds as pure functions of their inputs: hermetic, sandboxed actions whose outputs can be cached and shared across every machine. Those ideas (content-addressed caches, remote execution) have since spread to Gradle and other tools.

BE·44 Backend Fundamentals

The Backend

In 1999 Dan Kegel posed the C10k problem: how can one server handle ten thousand simultaneous clients? With a thread or process per connection, memory and context switching ran out long before that. The answers shaped backend frameworks for two decades: event loops on non-blocking sockets (epoll, kqueue), used by nginx (2004), Node.js (2009) and Netty; lightweight threads in the runtime (Erlang's processes, Go's goroutines); and now Java's virtual threads, which bring the cheap-thread approach to the JVM.

Meanwhile the shape of a backend converged across languages: a listener, a chain of middleware, a router, handlers, services holding business rules, and repositories talking to storage. Spring, ASP.NET Core, Express, Django, Gin and Axum differ in style and agree on that structure, because it separates the HTTP concerns from the business from the storage.

BE·45 HTTP API Design

The Backend

In the late 1990s programs talked over the network through remote procedure calls dressed up as objects (CORBA, Java RMI) and then SOAP (1998–2000), XML messages sent to one endpoint with heavy tooling. In 2000 Roy Fielding, one of HTTP's authors, described in his doctoral dissertation the architectural style the web itself followed: REST. Resources with addresses, a small uniform set of methods, stateless requests and cacheable responses. The web had scaled to the whole world on those constraints, so APIs built the same way inherited caching, proxies and simplicity.

APIs labelled "REST" rarely follow all of Fielding's constraints, but the core ideas stuck. Other styles answered other needs: GraphQL (Facebook, released 2015) lets clients choose exactly the fields they need; gRPC (Google, 2015) offers typed, efficient calls between services. OpenAPI (from Swagger, 2010–11, renamed in 2016) made HTTP APIs describable by machines.

BE·46 Spring Core

The Backend

Enterprise Java around 2000 meant Enterprise JavaBeans: components that had to implement framework interfaces, needed an application server to run at all, and were configured with long XML descriptors. Simple business logic was hard to write and nearly impossible to unit-test. In 2002 Rod Johnson's book Expert One-on-One J2EE Design and Development argued that plain Java objects, wired together by a lightweight container, could do the same job; the code that came with it became the Spring Framework (1.0 in March 2004).

The central idea had several names. "Inversion of control" (the framework calls you, not the other way round) was already used in the 1990s; in January 2004 Martin Fowler named the specific pattern of handing objects their collaborators dependency injection. Spring's other pillar was proxies for cross-cutting concerns (transactions, security) applied without touching business code. Java EE eventually adopted the same ideas (CDI, EJB 3), and Spring Boot (ch47) made the container nearly invisible.

BE·47 Spring Boot

The Backend

By 2012 Spring had solved EJB's complexity and created its own: a new project meant choosing dozens of compatible library versions, writing XML or Java configuration for each, and deploying a WAR into a separately installed Tomcat. Ruby on Rails (2004) had shown the alternative, convention over configuration: sensible defaults, overridable when needed. Spring Boot 1.0 (April 2014) applied it to Spring: starters that pull in a tested set of dependencies, auto-configuration that sets up beans when it sees a library on the classpath, and an embedded server, so the application is just a JAR you run.

That last point matched where operations were going: containers and cloud platforms wanted self-contained processes with health endpoints and configuration from the environment, which Boot's Actuator and externalised configuration provided. Later versions added ahead-of-time processing and native images to reduce start-up time.

BE·48 Spring Web — MVC and WebFlux

The Backend

Java web applications have been built on the Servlet API since 1997: a container calls your code on a thread for each request. Spring MVC (from Spring 1.0, annotation-based from 2.5 in 2007) put a front controller, the DispatcherServlet, in front of servlets to route requests to annotated methods and convert bodies to and from objects. It's still the most used Java web framework.

The reactive movement asked a different question: what if threads were never blocked waiting? The Reactive Manifesto (2013–14) and the Reactive Streams specification (2015), from Lightbend, Netflix, Pivotal and others, defined asynchronous streams with backpressure, so a fast producer can't overwhelm a slow consumer. Spring 5 (2017) added WebFlux on Project Reactor and Netty. With virtual threads (Java 21), much of WebFlux's throughput advantage for ordinary request–response services is available to plain blocking MVC code.

BE·49 Persistence — JDBC, JPA, Hibernate and Spring Data

The Backend

Programs model the world as objects with references; relational databases model it as tables of rows joined by values. Translating between them by hand (writing SQL, reading result sets column by column into objects) was the bulk of business code in the 1990s; JDBC (1997) standardised the database calls but not the translation. The mismatch got a name, the object–relational impedance mismatch, and tools to bridge it: Gavin King's Hibernate (2001) mapped classes to tables and loaded related objects automatically, and its design became the Java Persistence API (JPA, 2006). Spring Data added repositories generated from method names.

The bridge leaks. Ted Neward called object–relational mapping "the Vietnam of computer science" in 2006: easy at the start, ever more costly to finish. The classic symptoms (N+1 queries, surprise lazy loads, flushes at odd moments) come from hiding the database's cost model behind an object model. Modern practice uses ORMs for straightforward entities and plain SQL for reports and hot paths.

BE·50 Spring Security and Modern Identity

The Backend

For years, letting one application use your data on another meant giving it your password. Twitter, Google and others designed OAuth (1.0 in 2007, RFC 5849 in 2010) so you could grant a limited, revocable token instead. OAuth 2.0 (RFC 6749, 2012) simplified it for web and mobile apps, and OpenID Connect (2014) added a standard way to learn who the user is, which OAuth alone never promised. Mobile and browser apps that can't keep secrets got PKCE (RFC 7636, 2015), now recommended for every client.

Passwords themselves improved slowly: storing them hashed with slow, salted algorithms (bcrypt by Niels Provos and David Mazières, 1999; later scrypt and Argon2) limits the damage of a breach. WebAuthn (a W3C Recommendation in 2019) and passkeys replace passwords with public-key credentials that can't be phished. Meanwhile OWASP's 2021 Top 10 put broken access control at number one: most breaches aren't clever cryptography failures but missing checks on who may do what.

BE·51 Asynchronous Work, Jobs and Messaging

The Backend

Some work shouldn't happen while a person waits: sending email, generating reports, notifying other systems. Message queues let a program hand work to another reliably: IBM's MQSeries (1993) and the JMS API (1998) made them standard in enterprise systems. Kafka (LinkedIn, open-sourced in 2011) changed the model to a durable, replayable log that many consumers read at their own pace, and became the backbone of event-driven systems.

Long-running business processes that span services can't use one database transaction. Hector Garcia-Molina and Kenneth Salem described sagas in 1987: a sequence of local transactions, each with a compensating action to undo it if a later step fails. And underneath it all sits an impossibility: over an unreliable network you can't guarantee a message is delivered exactly once (a form of the Two Generals problem), so systems deliver at least once and make handlers idempotent.

BE·52 Resilience

The Backend

When a service depends on others, their failures become its failures, and slow failures are the worst: threads pile up waiting until the whole service stops. Michael Nygard's Release It! (2007) collected the patterns that stop this (timeouts, circuit breakers, bulkheads), named after electrical and ship design. Netflix, moving to the cloud, built them into its Hystrix library (2012) and started deliberately killing its own servers with Chaos Monkey (2011) to prove the system survived. In 2015 Marc Brooker at AWS published measurements showing that retries with jitter (random delays) prevent clients from retrying in synchronised waves.

The common lesson from large outages is that recovery mechanisms often cause the next failure: retries multiply load on a struggling service, timeouts set longer than the caller's own deadline waste work, and every server restarting at once overwhelms what they depend on.

BE·53 Caching

The Backend

Caching is as old as fast memory next to slow memory (Foundations, ch07). In 1966 László Bélády described the optimal replacement policy: evict the item whose next use is furthest in the future. It needs knowledge of the future, so real caches approximate it with least-recently-used, least-frequently-used and their refinements; Caffeine's W-TinyLFU (Einziger, Friedman and Manes, 2017) estimates frequency in a small, compact sketch and comes close to optimal on many workloads.

Web-scale applications made shared caches a standard tier. Brad Fitzpatrick wrote Memcached (2003) to keep LiveJournal's database from collapsing under reads; Redis (Salvatore Sanfilippo, 2009) added data structures and persistence. A saying usually attributed to Phil Karlton holds that "there are only two hard things in computer science: cache invalidation and naming things", and most of this chapter is about the first.

BE·54 Backend Testing

The Backend

Automated unit testing as most developers know it started with small frameworks: Kent Beck's SUnit for Smalltalk (1990s), then JUnit, which Beck and Erich Gamma wrote in 1997, famously starting on a flight to a conference. The "xUnit" pattern spread to every language. Beck's Test-Driven Development (2002) argued for writing the test first, so design follows from use. Mock Roles, not Objects (Steve Freeman, Nat Pryce and others, 2004) shaped how test doubles are used, and warned against mocking things you don't own.

Integration tests long meant shared, fragile test databases. Testcontainers (2015) made it practical to start a real PostgreSQL, Kafka or Redis in a container for each test run, so tests check against the real thing rather than an in-memory imitation. Property-based testing (QuickCheck, 2000) and mutation testing added ways to find cases nobody thought to write.

BE·55 Backend Projects

The Backend

A backend is judged when things go wrong: under load, when a dependency is slow, when a message arrives twice, when someone sends a request they shouldn't. Each chapter of this volume covered one of those concerns; real services meet all of them in every request. The projects make you combine them, the way the TiffinBox build does stage by stage, so that the question "what happens if this fails?" becomes a habit rather than a chapter.

DB·00 Start Here: What a Database Is

Databases

Before databases, every program kept its own files in its own format, and two programs that needed the same customers kept two copies that drifted apart. The first database systems (IBM's IMS, developed in the late 1960s partly for the Apollo programme's parts lists, and the CODASYL network model) put shared data in one place, but programs still navigated it record by record along fixed paths, so changing how data was stored broke the programs that read it.

In 1970 Edgar Codd at IBM proposed the relational model: describe data as tables and ask for what you want, and let the system work out how to fetch it. IBM's System R and Berkeley's Ingres proved it could be fast in the 1970s; Oracle shipped the first commercial SQL database in 1979; SQL became a standard in 1986. Fifty years later, the relational database is still the default place for an organisation's most important data.

DB·55 The Relational Model

Databases

Edgar Codd was a mathematician, and his 1970 paper brought set theory and logic to data: a table is a relation, a set of tuples; queries are operations on relations (selection, projection, join) whose results are relations too. That closure is why queries compose. In the following years Codd and others described normal forms, rules for splitting data into tables so that each fact is stored once, because duplicated facts get updated in one place and not another. Boyce–Codd normal form dates from 1974.

Real SQL departed from the model in ways critics such as Chris Date have argued about since: tables can contain duplicate rows, column order is visible, and NULL brings three-valued logic, where a comparison can be true, false or unknown. Those departures are behind several of the chapter's pitfalls.

DB·56 SQL from SELECT to Window Functions

Databases

Codd's relational algebra was mathematically precise and hard for most people to write. At IBM in 1974 Donald Chamberlin and Raymond Boyce designed SEQUEL, a "structured English query language" in which a query reads roughly like a sentence; a trademark clash renamed it SQL. It was meant for analysts as much as programmers, and it was declarative: you state the result, not the steps.

SQL kept growing through standards: joins written explicitly (SQL-92), recursive common table expressions (SQL:1999), window functions (SQL:2003), and later JSON and row-pattern matching. Window functions in particular turned many problems that once needed self-joins or application loops (running totals, rankings, comparisons with the previous row) into single queries.

DB·57 PostgreSQL in Depth

Databases

PostgreSQL began as Postgres ("post-Ingres"), Michael Stonebraker's research project at Berkeley from 1986. Its goal was extensibility: users should be able to add their own data types, operators and index methods, which is why PostgreSQL today hosts geographic data (PostGIS), vectors (pgvector) and full-text search as extensions. In 1994–95 Andrew Yu and Jolly Chen added SQL (Postgres95), and in 1996 it became PostgreSQL, developed since by an open community with no single owning company.

Many of its defining behaviours come from early choices. MVCC (from 1999) keeps old versions of rows so readers never block writers, which is also why it needs VACUUM to clean up dead versions. A process per connection, rather than a thread, made it robust and made connection pooling essential. Its reputation for correctness and features made it the most used database among developers in recent surveys.

DB·58 Storage Engine Internals

Databases

Disks reward reading large blocks and punish seeks, and that shaped storage engines for fifty years. Rudolf Bayer and Edward McCreight's B-tree (1972) made each tree node a disk page holding hundreds of keys, so finding any of billions of rows takes a handful of page reads. System R and its successors added a write-ahead log, so a change becomes durable by appending to one sequential file rather than rewriting scattered pages.

Write-heavy workloads pushed another design. The log-structured merge tree (O'Neil and others, 1996) buffers writes in memory, flushes them as sorted files and merges files in the background, turning random writes into sequential ones. Google's Bigtable (2006), then LevelDB (2011) and Facebook's RocksDB (2012) made LSM trees the engine of many modern databases. SSDs changed the costs again (random reads are cheap, rewriting flash wears it out), and engines keep adapting.

DB·59 Transactions and Concurrency Control

Databases

When several people change shared data at once, and machines crash mid-change, the data can end up in states no single person intended. Jim Gray's work in the 1970s, summarised in The Transaction Concept (1981), defined the transaction: a group of changes that happens completely or not at all, in isolation from others, and survives crashes. Theo Härder and Andreas Reuter coined ACID in 1983. Gray received the Turing Award in 1998 for it.

Full isolation (serializability) was expensive, so databases offered weaker isolation levels, and the 1995 paper A Critique of ANSI SQL Isolation Levels showed the standard's definitions were ambiguous and that snapshot isolation, widely used, allowed an anomaly called write skew. In 2008 Michael Cahill and colleagues published Serializable Snapshot Isolation, which detects dangerous patterns instead of locking; PostgreSQL adopted it in 2011.

DB·60 Query Optimisation

Databases

A declarative language only works if something turns "what" into a fast "how". In 1979 Patricia Selinger and colleagues at IBM published how System R did it: estimate the cost of alternative plans from statistics about the data, and use dynamic programming to search join orders efficiently. Nearly every relational optimiser since descends from that paper. It made SQL practical: a good plan and a bad plan for the same query can differ by factors of thousands.

The weak point has always been estimation. Optimisers guess how many rows each step produces, usually assuming columns are independent and values evenly spread, and errors multiply through joins. A 2015 study (How Good Are Query Optimizers, Really?, Leis and others) found cardinality estimates in real systems often off by orders of magnitude, and that those errors, more than cost models, cause bad plans.

DB·61 Scaling Databases

Databases

For decades the answer to a slow database was a bigger machine. Web companies in the 2000s outgrew the biggest machines, especially for writes, and split data across many: Flickr, Facebook, YouTube and others sharded MySQL by user. Read replicas spread reads; sharding spread writes and storage; both broke assumptions applications relied on, such as seeing your own write immediately or joining any two rows.

The techniques have a research lineage. Consistent hashing (David Karger and colleagues, 1997) let caches and stores add or remove nodes while moving only a small share of keys, and Amazon's Dynamo (2007) built on it. Google's Spanner (2012) showed sharded databases could keep SQL and strong transactions, and "NewSQL" systems (CockroachDB, TiDB, YugabyteDB) followed. Most applications, though, still scale a single PostgreSQL or MySQL primary much further than people expect.

DB·62 NoSQL Data Models and Stores

Databases

In the late 2000s large web companies needed things relational databases of the time didn't offer easily: writes spread across hundreds of machines, staying available through failures and network partitions, and data whose shape changed weekly. Google's Bigtable (2006) and Amazon's Dynamo (2007) papers described in-house answers; open-source systems followed (Cassandra from Facebook in 2008, MongoDB in 2009, HBase, Redis). The name NoSQL came from a 2009 meetup hashtag, and was later reinterpreted as "not only SQL".

Each traded away something relational databases gave: joins, multi-row transactions, enforced schemas or immediate consistency. Analytics took another path: column stores (C-Store in 2005, then Vertica, and later ClickHouse, BigQuery and others) store each column together and scan billions of rows fast. Over time the lines blurred: relational databases added JSON and horizontal scaling, and NoSQL stores added transactions and SQL-like languages.

DB·63 Search Engines and Hybrid Search

Databases

Libraries indexed books by subject long before computers, and information retrieval as a field (Gerard Salton's SMART system, from the 1960s) asked how to find the most relevant documents, not just the matching ones. The inverted index (a map from each word to the documents containing it) and weighting rare words above common ones (Karen Spärck Jones's inverse document frequency, 1972) became its foundations. Stephen Robertson and colleagues' BM25 (Okapi, mid-1990s) remains a strong ranking function today.

Doug Cutting wrote Lucene in 1999, the engine under Elasticsearch (2010), Solr and OpenSearch. Then embeddings changed the field: neural models map text to vectors where similar meanings lie close together, and approximate nearest-neighbour indexes such as HNSW (Malkov and Yashunin, 2016) search them quickly. Since meaning-based and keyword-based search fail in different ways, systems now combine them (hybrid search), often merging rankings with reciprocal rank fusion (Cormack and others, 2009).

DB·64 Durability, Backups and Recovery

Databases

Data loss rarely comes from the disaster people plan for. On 31 January 2017 an engineer at GitLab, working late on a replication problem, deleted the primary database's data directory on the wrong server. Of the backup methods the company believed it had, none produced a usable recent copy; they restored from a snapshot taken six hours earlier, losing that data. Their public post-mortem became a standard lesson: a backup that hasn't been restored is a hope, not a backup.

The techniques are older. Write-ahead logs, designed for crash recovery (ARIES, 1992), also enable point-in-time recovery: restore a base backup and replay archived logs to any moment, such as one second before a bad DELETE. The photographer Peter Krogh's 3-2-1 rule (three copies, two kinds of media, one off-site) spread from photo archives to IT. Ransomware added a new requirement: backups that attackers with your credentials can't delete or encrypt.

DB·65 Database Projects

Databases

Building a small database is one of computer science's classic learning projects, because it forces nearly every idea in this volume to fit together: a file format, an index, a query language, transactions, crash recovery. Courses at universities such as CMU (whose database systems course builds BusTub) and many self-study guides use it for that reason. The projects here combine the chapters at smaller scale, around real data and real failure.

AN·01 Start Here: What Numbers Are

Arithmetic and Numbers

People tracked quantities by matching long before they had number words: one notch, pebble or knot per thing. Clay tokens found across the Near East from about 8000 BCE have been interpreted, most fully by the archaeologist Denise Schmandt-Besserat, as an accounting system that led to writing itself around 3200 BCE; the interpretation is influential and debated. Names for numbers and numerals came next, and place-value numerals (chapter 2) made calculation on paper possible.

What a number is became a question only much later. In 1884 Gottlob Frege proposed defining "the number of" a collection through one-to-one correspondence, the idea this chapter starts from. Richard Dedekind (1888) and Giuseppe Peano (1889) gave rules from which all of arithmetic on the natural numbers follows: zero, a successor for each number, and induction. Georg Cantor's work on sets in the same decades used one-to-one correspondence to compare infinite collections. The order-of-operations convention has a much less dramatic history: it grew out of algebraic practice over centuries, and the school mnemonics (BODMAS, PEMDAS) are twentieth-century teaching devices, not mathematics.

AN·02 Place Value and Bases

Arithmetic and Numbers

Before place value, numerals were additive: Egyptian hieroglyphs and Roman numerals repeat symbols of fixed value and add them up. They record numbers well enough, but calculating with them needs counters on a board, so arithmetic and writing were separate activities. The Babylonians, by about 2000 BCE, made a symbol's value depend on its position, in base sixty, and computed with tables of reciprocals and products; their weakness was the missing zero. Chinese rod numerals were positional in base ten, with a blank for an empty place. The full system, nine digits plus a zero that is both a placeholder and a number, was developed in India in the first millennium CE; the Gwalior inscription of 876 CE writes zero as a small circle in ordinary use. It spread through al-Khwārizmī's book on Indian calculation (around 825) and Fibonacci's Liber Abaci (1202), and won in Europe over several centuries against counting boards and Roman numerals in account books. Leibniz described binary in 1703; Shannon's 1937 thesis showed switching circuits compute Boolean logic, and binary became the language of machines.

AN·03 Adding and Subtracting, and Why the Methods Work

Arithmetic and Numbers

For most of history, sums were done on counters: pebbles on ruled lines, beads on an abacus, rods on a counting board. Written numerals recorded the answer; they weren't calculated on. Place value made the numeral itself a calculating device, and the column methods were written down by Indian and then Arabic mathematicians and carried to Europe in Fibonacci's Liber Abaci (1202). European "abacists" with counting boards and "algorists" with pen and paper competed for centuries; paper won as paper got cheaper and Hindu–Arabic numerals became standard in bookkeeping.

The carry was also the hard part of mechanising arithmetic. Blaise Pascal's adding machine (1642) needed a mechanism to pass a carry from one wheel to the next without jamming when several carries rippled at once (999 + 1); Leibniz's stepped reckoner (1670s) and Babbage's difference engine (designed from the 1820s) each solved it differently. Electronic computers inherited the same problem: a ripple-carry adder waits for each column, and much of the cleverness in a processor's adder is about computing carries faster. Subtraction methods went through their own history: equal addition and decomposition competed in schools, and the switch in many countries during the twentieth century followed studies of which one children understood rather than which was correct.

AN·04 Multiplying and Dividing

Arithmetic and Numbers

The oldest written multiplication method, in the Egyptian Rhind papyrus (about 1550 BCE), doubled one number repeatedly and added the right doublings, the halving-and-doubling method in this chapter's exercises; it's binary multiplication four thousand years early. Babylonian scribes used tables of products and reciprocals, dividing by multiplying by a reciprocal. Place value made the shifted-rows method possible, and Indian and Arabic texts describe several layouts, including the lattice. Long division was the hardest to settle: European arithmetic books taught the "galley" or scratch method into the 1600s, and the layout schools use now took over after that.

The effort to make multiplication easier shaped mathematics: John Napier's rods ("Napier's bones", 1617) mechanised the lattice, and his logarithms (1614) turned multiplication into addition, which the slide rule exploited for three centuries. In 1960 Andrey Kolmogorov conjectured that multiplying n-digit numbers needs about n2 steps; Anatoly Karatsuba refuted it within a week. Faster methods followed (Toom–Cook, then Schönhage and Strassen's fast-Fourier-transform method in 1971), and in 2019 David Harvey and Joris van der Hoeven reached O(nlogn), conjectured to be the best possible.

AN·05 Factors, Multiples and Primes

Arithmetic and Numbers

Divisibility is older than written proofs: Babylonian scribes preferred base 60 partly because 60 has so many factors, and their reciprocal tables list only the "regular" numbers whose reciprocals end (those built from 2, 3 and 5). Euclid's Elements (about 300 BCE) collects the theory in Books VII to IX: the gcd algorithm opens Book VII, the fact that a prime dividing a product divides a factor is Book VII, Proposition 30, and the primes never running out is Book IX, Proposition 20. Eratosthenes' sieve comes from the following century.

The subject then went quiet for a long time. Pierre de Fermat revived it in the 1600s, stating (in a 1640 letter) the "little theorem" that ap−a is a multiple of p for every prime p, the basis of modern primality tests. Carl Friedrich Gauss's Disquisitiones Arithmeticae (1801) introduced the notation of congruences, a≡b(modm), and proved unique factorisation carefully. The prime number theorem, that primes near x have density about 1/lnx, was conjectured by Gauss and Legendre and proved in 1896, independently, by Jacques Hadamard and Charles de la Vallée Poussin. RSA (1977) made the whole subject practical; cryptographers at GCHQ, the British signals intelligence agency, had found an equivalent scheme in 1973, kept secret until 1997.

AN·06 Fractions

Arithmetic and Numbers

Fractions came from measuring and sharing, and different cultures chose very different ways to write them. Egyptian scribes used sums of unit fractions with tables to look them up. Babylonian scribes wrote fractions in base sixty, much as we write decimals, which made dividing by 2, 3, 4, 5 and 6 easy. Greek mathematicians mostly avoided fractions as numbers and spoke of ratios between magnitudes; when the Pythagoreans found that the diagonal and side of a square have no common measure (chapter 12), Eudoxus built a theory of proportion that worked even for such ratios, recorded in Book V of Euclid's Elements.

The written form we use is Indian: one number above the other, with Brahmagupta's rules (628 CE). Arabic writers added the bar between them. Decimal fractions, a way of writing every fraction with powers of ten as denominators, were used by al-Kāshī in fifteenth-century Samarkand and made popular in Europe by Simon Stevin's pamphlet De Thiende (1585), which argued that merchants, surveyors and mint officials should stop using fractions altogether. They didn't, entirely: inches, recipes and music still count in halves, quarters and eighths. The mediant property of neighbouring fractions was noticed by Charles Haros (1802) and again by the geologist John Farey (1816), whose name the sequence now carries; Augustin-Louis Cauchy proved it.

AN·07 Decimals and Percentages

Arithmetic and Numbers

Decimal fractions solved a practical problem: fractions with different denominators are awkward to compare and combine, and tradespeople, surveyors and tax collectors needed arithmetic anyone could check. Writing everything in tenths, hundredths and thousandths turned it all back into column arithmetic. The idea was old by the time Simon Stevin popularised it in 1585, but measures and money stayed non-decimal for centuries. India's rupee was divided into 16 annas, each of 4 pice (or 12 pies), until decimal coinage arrived on 1 April 1957, when the rupee became 100 "naya paise" (new paise); the metric system for weights and measures followed in the same years. France had adopted the metric system in the 1790s; Britain decimalised its currency on 15 February 1971.

The percent sign grew out of abbreviations of the Italian per cento in fifteenth-century merchants' books, slowly shortened to the symbol used today. And when computers arrived, they mostly chose binary fractions instead: fast in hardware, but unable to store 0.1. Different machines rounded differently until the IEEE 754 standard (1985), led by William Kahan, fixed one set of rules for binary floating point; its 2008 revision added decimal formats for exactly the problem this chapter describes.

AN·08 Ratio, Proportion and Rates

Arithmetic and Numbers

Proportional reasoning is what trade, building and taxation needed first: so much grain for so much silver, so many bricks for a wall of this size, a tax of this much per measure. Babylonian and Egyptian problem texts are full of it, solved by scaling a known case. Indian mathematicians turned the method into a named rule: Āryabhaṭa's rule of three (499 CE), then Brahmagupta's rules of five, seven, nine and eleven for problems where several quantities vary at once, such as interest depending on both the sum and the time. Bhāskara II's Līlāvatī (1150) has many such problems, including inverse ones, which it treats as a separate rule.

Greek mathematics went the other way, towards theory. Ratios of lengths that have no common measure (the side and diagonal of a square) can't be compared by counting, so Eudoxus defined equality of ratios by a test that works for any magnitudes; Book V of Euclid's Elements preserves it, and nineteenth-century mathematicians (Richard Dedekind, in 1872) used almost the same idea to define the real numbers (chapter 12). The statistical side of the chapter is modern: Karl Pearson noticed in 1899 that combining groups could create spurious associations, G. Udny Yule studied it in 1903, and Edward Simpson's 1951 paper gave the reversal its usual form.

AN·09 Negative Numbers

Arithmetic and Numbers

Negative numbers were used long before they were accepted. Chinese calculators of the Han dynasty set out equations on a counting board with red and black rods for gains and losses, and the procedure in The Nine Chapters for eliminating unknowns needs them. Brahmagupta's Brāhmasphuṭasiddhānta (628) gives complete rules for adding, subtracting, multiplying and dividing "fortunes", "debts" and zero, the first written treatment of negatives as numbers with an arithmetic of their own. Arabic algebra, which reached Europe, mostly avoided them by rearranging equations so every term was positive.

European mathematicians met negatives as solutions of equations and distrusted them for three centuries: Cardano (1545) used them while calling them "fictitious", Descartes called negative roots "false", and as late as 1831 the English mathematician Augustus De Morgan argued that a negative answer showed the question had been badly posed. What settled the matter was a change of view, from numbers as quantities to numbers as things that obey rules: George Peacock's Treatise on Algebra (1830) and later nineteenth-century work defined the integers by their laws, after which "why is a negative times a negative positive?" had the answer this chapter gives. Computers then reopened the question of how to write negatives, and settled on two's complement by the 1960s.

AN·10 Powers, Roots, Scientific Notation and Logarithms

Arithmetic and Numbers

Powers began as geometry: a "square" number is the area of a square, a "cube" number the volume of a cube, which is still what the words mean. Babylonian tables of squares and reciprocals let scribes multiply with the identity ab =(a+b)2−(a−b)24, turning a product into table look-ups and a subtraction, an early version of the idea that made logarithms famous. Indian mathematicians named powers of ten up to 1053 and beyond.

Logarithms arrived as a calculating tool before anyone thought of them as exponents. John Napier spent twenty years computing his tables (published 1614) to spare calculators the long multiplications, divisions and root extractions of great numbers, which he called the most troublesome part of mathematical practice; Henry Briggs visited him and proposed base 10, and his tables of 1624 were used for three centuries. Pierre-Simon Laplace is often quoted as saying that logarithms, by shortening the labours, doubled the life of the astronomer. The slide rule put logarithms in every engineer's pocket until electronic calculators replaced it in the 1970s. The modern view, that a logarithm is simply the inverse of a power, is Euler's (1748), and e itself was first met by Jacob Bernoulli in 1683 as the limit of compounding interest ever more often.

AN·11 Estimation, Rounding, Error and Units

Arithmetic and Numbers

Measurement is older than arithmetic: lengths from body parts (the cubit, the foot, the hand), weights from seeds, time from the sky. Every ruler and every market made its own units, and trade between towns meant converting. Indian texts such as the Arthaśāstra (compiled around the start of the common era) list official weights and measures and the penalties for false ones; the Harappan cities, two thousand years earlier, already used a standard system of cubic stone weights. Revolutionary France set out to replace hundreds of local units with one decimal system based on nature (the metre as a fraction of the Earth's meridian), adopted in 1795; the Metre Convention of 1875 created an international bureau to keep the standards, and the SI (1960) became the common language of science. India moved to metric weights and measures between 1958 and the 1960s.

The theory of error came from astronomy. Repeated observations of the same star disagreed, and astronomers needed to know how to combine them: Legendre (1805) and Gauss (1809) developed least squares, and Gauss's analysis of observational error gave the "normal" bell curve. In computing, rounding became a design question: early machines rounded inconsistently, and IEEE 754 (1985) fixed the rules, half even by default, for every floating-point operation.

AN·12 The Real Number Line

Arithmetic and Numbers

For most of history, mathematicians used numbers like 2 and π without saying what they were. Greek geometry kept lengths and numbers apart after the discovery of incommensurable lengths; Indian and Islamic mathematicians computed with irrational quantities freely (the Śulba Sūtras approximate 2 as 577408; al-Kāshī computed π to 16 decimal places in 1424); and the calculus of Newton and Leibniz (late 1600s) depended on limits that nobody could define precisely. Bishop Berkeley's 1734 attack on its "ghosts of departed quantities" was answered only in the nineteenth century, when Bolzano, Cauchy and Weierstrass made limits precise and found that they needed a precise description of the number line itself.

In 1872 several definitions appeared at once: Dedekind's cuts, Cantor's and Méray's sequences of fractions, and Weierstrass's approach. All gave the same real numbers. Cantor then asked how many there are, and his answers (1874, 1891) founded set theory, provoked opposition from mathematicians such as Leopold Kronecker, and led to questions, like the continuum hypothesis, that turned out to be undecidable from the usual axioms (Gödel 1940, Cohen 1963). In 1936 Alan Turing defined computable numbers, connecting the real line to what machines can do, the starting point of computer science.

IT·01 Start Here: What Information Is

Information Theory

Long before anyone measured information, engineers paid for it. Telegraph companies in the nineteenth century charged by the word, so merchants compressed their messages into commercial code books, where one five-letter group stood for a whole sentence. Morse code, developed by Samuel Morse and Alfred Vail from the late 1830s, gave common letters short signals. Both were practical answers to the same question: how few symbols can carry a message?

The theory arrived at Bell Telephone Laboratories. Harry Nyquist (1924) related a telegraph line's speed to the number of distinct signal levels it used, and Ralph Hartley (1928) defined the information in a message as the logarithm of the number of messages it could have been, deliberately leaving out "psychological factors". During the Second World War, Claude Shannon worked on cryptography and fire control; his classified 1945 memorandum on secrecy systems used the ideas that became "A Mathematical Theory of Communication" (1948). At almost the same time Norbert Wiener, in Cybernetics (1948), proposed a closely related measure of information for control and signal processing, and Alan Turing and I. J. Good at Bletchley Park had been scoring evidence in bans since the early 1940s. Shannon's paper won because it did more than define a measure: it proved what the measure means, as limits on compression and on communication through noise, which engineers spent the next fifty years reaching.

IT·02 Counting Possibilities: Bits, Logarithms and Questions

Information Theory

Counting arrangements is ancient. Indian scholars counted the possible metres of Sanskrit verse: Piṅgala's Chandaḥśāstra (around the last centuries BCE) enumerates patterns of short and long syllables, a binary system in all but name, and later commentators gave rules for the number of patterns of each length. Bhāskara II's Līlāvatī (1150) has rules for permutations and combinations, and in Europe Blaise Pascal's Traité du triangle arithmétique (written 1654) gathered the binomial coefficients into the triangle that bears his name. Abraham de Moivre and James Stirling (1730) found the approximation to n! that makes large counts usable.

The step from counting to coding came with machines. Morse's variable-length code suited human ears, but a machine reading pulses in step needs every character to take the same time. Émile Baudot's five-unit code (1870s), Donald Murray's revision (1901) and the international telegraph alphabet ITA2 (standardised in the 1920s and 1930s) fixed the pattern: count the characters, find the power of two that covers them. ASCII (1963) and the 8-bit byte followed. Meanwhile, the question-tree view of information gave algorithm designers their most famous lower bound: sorting by comparisons needs about nlog2n of them, a result in the textbooks by the 1960s and a standard example of how information limits computation.

IT·03 The Probability You Need

Information Theory

Gamblers knew the odds of dice long before anyone wrote them down, and some got them wrong: the Chevalier de Méré reportedly lost money believing that betting on at least one double six in 24 throws of two dice was favourable (it isn't: 1−(35/36)24≈0.491). His questions reached Blaise Pascal, whose letters with Pierre de Fermat in 1654 founded the mathematics of chance. Christiaan Huygens wrote it up (1657), Jakob Bernoulli proved that frequencies converge (1713), Abraham de Moivre found the bell-shaped curve that binomial counts approach (1733), Thomas Bayes and Pierre-Simon Laplace worked out how to reason from evidence back to causes, and Laplace's Théorie analytique (1812) made probability a tool for astronomy, demography and law.

What it lacked was a foundation. Paradoxes about "random" choices with infinitely many outcomes, and arguments over whether probability is a frequency or a belief, left the subject on uneven ground until Andrey Kolmogorov (1933) built it on measure theory: a probability is any assignment obeying a few axioms, whatever it means. That separation, rules first and interpretation second, is what let Shannon use probability for messages fifteen years later without having to say what the probabilities "really are".

IT·04 Entropy: the Average Surprise of a Source

Information Theory

The formula −∑plogp appeared in physics before communication. Ludwig Boltzmann, explaining in the 1870s why heat flows from hot to cold, measured the disorder of a gas by the logarithm of the number of molecular arrangements consistent with what we can observe; J. Willard Gibbs (1902) wrote the version with probabilities, which has exactly Shannon's form. In the 1920s Leo Szilard connected a single bit of knowledge about a molecule to a definite amount of physical entropy. None of this was about messages.

Shannon came to the same formula from the other side, asking how to measure the uncertainty of a source, and proved in 1948 that any measure that's continuous in the probabilities, grows with the number of equally likely outcomes, and can be computed in stages (grouping) must be a multiple of it. His entropy was immediately useful because of what it predicted: compression to H bits per symbol and no further. The link back to physics was made by E. T. Jaynes (1957), who argued that statistical mechanics is simply inference with the maximum-entropy distribution consistent with what's known, and by Rolf Landauer (1961), who showed that erasing a bit has a minimum physical cost. The Beautiful Intersections shelf follows that thread.

IT·05 Codes: Prefix Codes, Kraft's Inequality and Huffman Coding

Information Theory

Short codes for common things are old wisdom: Morse code, shorthand, and the telegraph code books that turned a common sentence into one word. What was missing was a way to find the best code. Shannon (1948) proved the entropy bound and gave a code within a bit of it; Fano (1949) gave a top-down splitting method; Leon Kraft's 1949 master's thesis at MIT stated exactly which codeword lengths are possible. Then David Huffman, a student in Fano's course, found in 1951 that building the tree from the bottom up gives the optimum, a result his teachers had looked for and missed.

For two decades Huffman coding was the compression method. Then its limits showed. Codes for single symbols can't spend less than a bit, and real data's probabilities change and depend on context. Arithmetic coding (Rissanen and Pasco, 1976; practical versions in the 1980s) removed the whole-number restriction; Lempel–Ziv methods (1977, 1978) learned repeated strings instead of symbol probabilities; and asymmetric numeral systems (Jarek Duda, around 2009) gave arithmetic coding's efficiency at Huffman's speed. Huffman codes survive inside DEFLATE, JPEG and HTTP headers because they're simple, fast and good enough after a strong model has done the real work.

IT·06 The Source Coding Theorem: Why Entropy Is the Limit

Information Theory

Before 1948, engineers knew compression was possible (Morse code, code books, Hartley's logarithm) but not how far it could go. Shannon's source coding theorem gave the answer, the entropy, and proved it with an idea that has outlived the theorem: in long messages, randomness becomes regular. Almost every long sequence from a source looks the same in its statistics, so describing it needs only enough bits to say which of the roughly 2nH typical sequences it is. The idea was made rigorous for sources with memory by McMillan (1953) and Breiman (1957), and it became the "method of types" in the hands of Imre Csiszár and János Körner in the 1970s.

The practical story is a chain of inventions that each closed part of the gap between theory and software. Huffman (1952) for single symbols; Elias's unpublished arithmetic coding idea, made precise by Rissanen and Pasco (1976) and practical by Witten, Neal and Cleary (1987); Lempel and Ziv (1977, 1978) for compression without known statistics; context modelling (PPM, 1984) and context mixing (PAQ, from 2002) for better models; and Duda's ANS (2009 onwards) for speed. Patents shaped which ideas spread: arithmetic coding and LZW were patented for years, which is partly why DEFLATE used Huffman and why GIF gave way to PNG.

IT·07 Joint and Conditional Entropy, Mutual Information

Information Theory

Correlation was the nineteenth century's measure of dependence: Francis Galton (1888) and Karl Pearson made it the standard way to say how two quantities move together. But correlation only sees straight-line relationships: Y=X2 for X symmetric around zero has correlation zero while Y is completely determined by X. Shannon's 1948 paper needed something else: a way to say how much a received signal tells you about a sent one, whatever the relationship. His conditional entropy and rate of transmission answered it, and they measure every kind of dependence.

The ideas spread well beyond communication. Robert Fano (1961) turned them into a textbook theory with his inequality linking uncertainty to error. In statistics, Solomon Kullback (1959) built on them. In machine learning, J. Ross Quinlan's ID3 decision trees (1986) chose questions by "information gain", the mutual information between a question and the answer. In neuroscience, from the 1950s, researchers asked how many bits a neuron's spikes carry about a stimulus. In imaging, mutual information became the standard way to align scans from different machines (1995). The data processing inequality became a principle with a philosophical edge: computation can rearrange information but never create it.

IT·08 Channels and Noise

Information Theory

Noise was an engineering problem long before it was a mathematical one. Telegraph operators repeated important words and spelled names letter by letter, telephone engineers fought crackle with louder signals, and early computers checked their arithmetic with parity bits and stopped when a check failed. Every one of these remedies assumed that reliability had to be paid for in speed or power. Shannon's 1948 paper reframed the problem: describe the noise by its probabilities, measure what still gets through in bits, and ask what the best possible code could do. Hamming, frustrated by a relay computer that detected errors in his weekend jobs but couldn't fix them, published the first efficient correcting codes in 1950, and the two papers together started coding theory.

Detection grew alongside. Cyclic redundancy checks (Peterson and Brown, 1961) gave cheap hardware a strong check against the bursts of errors real channels make. Check digits moved the same idea from wires to people: Hans Peter Luhn's scheme at IBM, the ISBN in 1970, and Jacobus Verhoeff's 1969 study of how people actually mistype numbers, which showed which errors a check digit must catch.

IT·09 Channel Capacity and the Noisy-Channel Coding Theorem

Information Theory

By the 1940s, communication engineering had many tricks and no limits. Harry Nyquist (1924, 1928) and Ralph Hartley (1928) had shown that a line's bandwidth limits how many distinct pulses it can carry per second, and Hartley had measured information as the logarithm of the number of possible messages. But nobody could say how much a noisy line could carry, or whether noise forced every message to slow down. Shannon's 1948 paper answered both: it defined capacity, proved that reliable communication is possible at any rate below it and impossible above it, and gave the capacity of the band-limited Gaussian channel, now the Shannon–Hartley formula.

The theorem changed what engineers aimed for. Instead of asking "how do we make this link a bit better?", they could ask "how far are we from the limit?", and the answer, for decades, was "a long way": practical codes stayed several decibels short until turbo codes (1993) and rediscovered LDPC codes (1996) closed most of the gap. Today, the codes in phones, Wi-Fi, satellites and SSDs operate within a fraction of a decibel of Shannon's limits, and the theorem is the yardstick every new system is measured against.

IT·10 Information Everywhere: Language, DNA, Randomness and Passwords

Information Theory

Shannon's theory gave exact answers for sources whose probabilities are known. Real sources come without labels: nobody knows the probability of an English sentence, a stretch of DNA or a password. So the theory had to become a measurement science, with its own instruments (models, compressors, guessing games) and its own pitfalls (bias, overfitting, the wrong alphabet). Shannon started it himself in 1951 by measuring English with human guessers, and the question "how much information is in this?" has since been asked of languages, genomes, music, images, neural signals and financial markets.

Security took the same tools in a different direction. Keys, tokens and passwords are only as strong as they are unpredictable, and the attacks of the 1990s and 2000s (Netscape's time-seeded keys, Debian's 32,767 possible keys, leaked password databases) showed that the average-case entropy of chapter 4 is the wrong measure for secrets. Min-entropy and guess curves became the way to measure them, and password guidance was rewritten around what people actually choose.

IT·11 Information in Machine Learning: Cross-Entropy and KL Divergence

Information Theory

Statistics and information theory grew up separately and met in the KL divergence. Kullback and Leibler, statisticians working on codebreaking, wanted to measure how well data can discriminate between two hypotheses; Turing and Good had already weighed evidence in the same units at Bletchley Park; and Shannon's coding theorems implied that the extra cost of coding with the wrong distribution is exactly the same quantity. Once that link was made, the tools of each field became tools of the other: likelihood became code length, hypothesis testing became a question about divergence, and model selection (Akaike, Rissanen) became a question about compression.

Machine learning inherited the whole package. Training a probabilistic model is minimising cross-entropy, judging a language model is measuring perplexity, distilling a large model into a small one is minimising a divergence, keeping a fine-tuned model close to its original is penalising one, and approximating an intractable posterior is minimising one in the other direction. The vocabulary of this book is, to a large extent, the working vocabulary of modern machine learning.