Kayavak

Kayavak / Deeper / What if?

Deeper · What if?

Change one assumption and reason out what happens

Thought experiments from every chapter. Reason each through before opening the answer: it teaches cause and effect, not definitions. 93 chapters so far. Also: Comparisons · Derivations · Origins. To change the numbers yourself, try the what-if calculators.

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

Foundations of Computing

What if programs couldn't be stored in memory?

Reason it through, then open

Every change would be a hardware change, so there would be no software industry as we know it: no downloads, no updates, no compilers (a compiler's output is a program stored as data), no operating system loading your code. Machines would be built for one job, like a calculator or a loom. The stored-program idea is what made a general machine cheap to repurpose.

What if the terminal had no separate error stream?

Reason it through, then open

Errors and results would arrive mixed in one stream. Redirect a program's output to a file and its error messages would land in that file too, silently corrupting the data, and you would see nothing on screen. Pipes would pass error text into the next program as if it were input. Unix gave every program a second output, standard error, so that results can travel down a pipe while problems still reach a person.

CS·02 Programming Fundamentals & Paradigms

Foundations of Computing

What if nothing could ever change once created?

Reason it through, then open

Every "change" would create a new value: appending to a list returns a new list. Whole classes of bugs disappear: nobody can modify a value you're still using, so sharing it between functions or threads is safe. The cost moves to memory and copying, which is why purely functional languages use persistent data structures that share unchanged parts between old and new versions (chapter 3). You'd also need another way to talk to the outside world, which does change: that is what Haskell's I/O types are about.

What if a language had functions but no recursion?

Reason it through, then open

FORTRAN up to the 1977 standard was like this: it didn't support recursive calls, partly because it gave each subroutine one fixed place for its variables instead of a fresh frame per call. You can still compute anything with loops and an explicit stack, but problems that are naturally recursive (walking a tree, parsing nested brackets) become bookkeeping. The fresh-frame-per-call design is what makes recursion work, and also what makes very deep recursion run out of stack.

CS·03 Data Structures

Foundations of Computing

What if a dynamic array grew by a fixed 10 slots instead of doubling?

Reason it through, then open

Appending n items would copy 10 + 20 + 30 + … items, about n²/20 in total: quadratic. Appending a million items would copy around fifty billion elements. Doubling (or any constant factor, like Java's 1.5×) keeps the total copying below a small multiple of n, which is what makes append amortised O(1). See the derivation below.

What if memory had no caches?

Reason it through, then open

Every access would cost the same main-memory trip, around 100 nanoseconds. Arrays would lose much of their real-world advantage over linked lists, because their speed comes from loading 64 bytes at a time and prefetching the next line. Big-O would predict running time much better than it does today, and everything would be far slower.

What if an attacker chooses your hash table's keys?

Reason it through, then open

They can pick keys that all land in one bucket, turning O(1) lookups into O(n) scans: a web server parsing request parameters into a hash map can be slowed to a crawl (the 2011 "hash flooding" attacks on many web platforms). The defences are a secret, randomised hash seed per process (Python, Rust, Go) or tree-shaped buckets with a log n worst case (Java 8's HashMap).

CS·04 Algorithms

Foundations of Computing

What if comparing two items were free, but moving one were expensive?

Reason it through, then open

Then the number of moves would matter, not comparisons. Selection sort, which looks slow (n² comparisons), does at most n − 1 swaps, so it could beat merge sort, which moves every element on every level. This is a real situation for very large records on slow storage, and it's why real systems often sort small keys with pointers to the records instead of the records themselves.

What if your input is already almost sorted?

Reason it through, then open

Insertion sort does only as much work as there are out-of-place pairs, so nearly sorted input costs it close to O(n). A naive quicksort that always picks the first element as pivot does the opposite: sorted input makes every split lopsided and it degrades to O(n²). Timsort, used for objects in Python and Java, looks for already-sorted runs and merges them, so it's fast on exactly this kind of real-world input.

CS·05 Discrete Mathematics

Foundations of Computing

What if a hash function were perfect?

Reason it through, then open

Collisions would still happen. If there are more possible keys than buckets, the pigeonhole principle guarantees two keys share a bucket, however clever the function. A perfect hash can only spread keys evenly, and even then the birthday effect (derived below) makes a first collision likely after only about the square root of the number of buckets. That's why every hash table needs a collision strategy.

What if you proved the step of an induction but forgot the base case?

Reason it through, then open

You can "prove" false things. Claim: every n satisfies n = n + 1. Step: if n = n + 1, add one to both sides and get n + 1 = n + 2. The step is valid; there's just no starting point where the claim is true, so the chain never begins. In code, this is a recursive function whose recursive case is right but whose base case is wrong or missing.

CS·06 Number Systems & Data Representation

Foundations of Computing

What if computers used decimal floating point?

Reason it through, then open

0.1 + 0.2 would equal 0.3, because tenths are exact in base ten. But 1/3 would still be inexact, as it is on paper, so rounding wouldn't disappear, it would just happen at the fractions people expect. IEEE 754 has had decimal formats since its 2008 revision, and some hardware and libraries (Java's BigDecimal, Python's decimal) provide them; binary remains the default because it's faster and simpler in hardware.

What if every machine were big-endian?

Reason it through, then open

Network byte order and memory order would match, so the conversion calls in every networking library would vanish, and hex dumps would read in the natural order. Nothing else fundamental would change: endianness is a pure convention. Little-endian survived on x86 partly because it makes reading a smaller integer from the start of a larger one free, which mattered to early hardware.

CS·07 Computer Architecture

Foundations of Computing

What if there were no caches?

Reason it through, then open

Every load would go to main memory, about 100 ns away. A 3 GHz core runs 300 cycles in that time, so a loop that reads memory each iteration would be one or two hundred times slower. Clever instruction scheduling wouldn't help much: almost every instruction would be waiting. The derivation below shows how much a cache with even a modest hit rate buys.

What if the branch predictor were always right?

Reason it through, then open

The pipeline would never be flushed, so code with unpredictable ifs (sorting-dependent filters, parsing, interpreters) would speed up noticeably, and tricks like branchless code would lose their point. The branch-based Spectre attacks would stop working too, because they depend on training the predictor to guess wrong and then reading what the wrongly speculated code left in the cache. Other speculation attacks, such as Meltdown and speculative store bypass, don't involve branch prediction, so a perfect predictor wouldn't stop them.

CS·08 Operating Systems

Foundations of Computing

What if there were no virtual memory?

Reason it through, then open

Every program would see real physical addresses. Two programs couldn't both be loaded at address 0x400000, so programs would have to be relocated when loaded; a stray pointer in one would overwrite another program or the kernel; and fork couldn't share memory copy-on-write. Embedded systems without an MMU live like this, which is why they usually run one trusted program.

What if the OS never interrupted a running program?

Reason it through, then open

That's cooperative multitasking: each program must give up the processor voluntarily. One infinite loop or slow computation freezes everything, including the mouse pointer. Classic Mac OS and 16-bit Windows worked this way, and users knew the frozen-screen result well. Preemptive scheduling with timer interrupts is what lets the OS take the CPU back. The same trade-off reappears inside programs: an event loop is cooperative, so a blocking call stalls every request it serves.

CS·09 Networking Fundamentals

Foundations of Computing

What if TCP had no congestion control?

Reason it through, then open

Every sender would transmit as fast as its own link allowed. Routers' queues would overflow, packets would be dropped, and senders would retransmit them, adding more load. The network would spend its capacity carrying copies that get dropped again: congestion collapse, which is what happened in 1986. Congestion control makes each sender slow down when loss or delay signals a full queue, sharing the bottleneck instead of fighting over it.

What if TCP never retransmitted lost packets?

Reason it through, then open

You'd have UDP with a connection handshake: data arrives in order when it arrives, but gaps stay gaps. Every application would need its own recovery, which is exactly what real-time voice and video do over UDP, preferring a brief glitch to waiting for a late packet. For files and web pages, where every byte matters, each application would end up reinventing retransmission.

CS·10 Compilers & Runtimes

Foundations of Computing

What if a JIT's assumption turns out wrong?

Reason it through, then open

A JIT compiles hot code assuming what it has seen so far: this call always reaches one class, this number is always an integer. When a different class or a string appears, the guard check fails and the runtime deoptimises: it discards the fast code, rebuilds the interpreter's state for the exact point it was at, and continues slowly, maybe recompiling later with the wider assumption. Correctness is kept; the cost is a pause and a slower path. It's also why benchmarks must warm up and why types that change unpredictably make JavaScript or Java code slower.

What if a language had neither garbage collection nor ownership?

Reason it through, then open

That's C: the programmer frees memory by hand. It's fast and predictable, and it's also the source of use-after-free, double-free and leak bugs, which security teams at Microsoft and Google have each reported cause around 70% of their serious security vulnerabilities in C and C++ code. Garbage collection removes those bugs by tracking reachability at run time; Rust's ownership removes them by checking lifetimes at compile time instead.

CS·11 Computer Science Mastery Projects

Foundations of Computing

What if you read the reference implementation first?

Reason it through, then open

You'd understand that solution, and you might even remember it. But you'd skip the part that teaches most: deciding what to build, making a wrong choice and discovering why it's wrong. Studies of learning find that struggling first and then seeing the answer helps more than seeing the answer first, even though it feels slower. Reading the reference after your attempt is where it's most useful: you can compare decisions.

What if you skipped tests because the project is "just for learning"?

Reason it through, then open

Every later change would risk silently breaking earlier parts, and you'd spend your time re-checking by hand instead of learning. Tests are also a second way of stating what you understand: if you can't write a test for a function, you probably can't say exactly what it should do.

FE·00 Start Here: How the Web Works

The Web Frontend

Reason it through, then open

Every link would need an agreement, so the web would have grown like a set of walled catalogues rather than one network. Search engines, which crawl by following links, would barely work. Broken links are the price of the opposite choice: anyone can link to anything, and nothing guarantees the target still exists.

What if browsers rejected any page with an error in its HTML?

Reason it through, then open

Most of the early web would have shown nothing, because hand-written HTML was full of mistakes. XHTML tried this strictness in the 2000s (one error, no page) and authors avoided it. HTML5's answer was the opposite: specify exactly how every browser must recover from every error, so broken markup at least breaks the same way everywhere.

FE·12 The Web Platform

The Web Frontend

What if there were no same-origin policy?

Reason it through, then open

Any page you visited could fetch your email, your bank statements and your company's intranet, using your logged-in cookies, and read the answers. Every site would effectively have your identity everywhere. The web would only be usable with one tab, or with no logins at all.

What if origins ignored the port?

Reason it through, then open

Two unrelated services on one host (a development server on :3000 and an admin console on :8080) could read each other's storage and responses. Origins include the scheme, host and port precisely so that different services don't share an identity. Cookies, older than origins, do ignore the port, which is one of their known weaknesses.

FE·13 HTML

The Web Frontend

What if every element were a <div>?

Reason it through, then open

The page could look identical with enough CSS and JavaScript, and still be broken for everyone who doesn't use it by mouse and eye. Screen readers would announce no headings, lists or landmarks to jump between; keyboard users couldn't reach the "buttons"; forms wouldn't submit on Enter or validate; search engines would see no structure. You'd have to rebuild with ARIA and scripts what native elements give for free, and most rebuilds miss something.

What if forms needed JavaScript to submit?

Reason it through, then open

Any script error, slow load or blocked script would leave users unable to submit anything. A plain <form> with action and method works with no JavaScript at all; scripts can then improve it. That layering (it works first, then it gets better) is called progressive enhancement.

FE·14 CSS

The Web Frontend

What if CSS had no cascade, only "last rule wins"?

Reason it through, then open

Every stylesheet would depend on load order. A reader's high-contrast style would be overridden by whichever site stylesheet loaded later, and a component library couldn't set defaults that applications reliably override. The cascade (origins, importance, layers, specificity) exists so that who wrote a rule, and how specific it is, matters as well as when it appeared.

What if lengths could only be in pixels?

Reason it through, then open

Pages couldn't adapt to readers who set a larger default font, to narrow phones or to zoom levels without breaking. Relative units (em, rem, %, viewport and container units) and intrinsic sizing (min-content, fr) let layout follow content and context. Pixels in CSS aren't even device pixels: one CSS pixel is defined by a reference viewing angle, so it maps to several device pixels on high-density screens.

FE·15 JavaScript

The Web Frontend

What if JavaScript were multi-threaded with shared memory?

Reason it through, then open

Every DOM operation would need locks, every library would need to be thread-safe, and every page would be open to data races, the hardest bugs in programming (Foundations, ch08). The single-threaded, run-to-completion model means your code can't be interrupted halfway through updating something. Workers add parallelism without that cost by sharing nothing by default and passing messages; SharedArrayBuffer is the opt-in exception, and it's gated behind cross-origin isolation.

What if await blocked the thread until the result arrived?

Reason it through, then open

The whole page would freeze for every network request. await doesn't block: it ends the current function's run, returns control to the event loop, and resumes the function in a later microtask when the promise settles. Other code can run in between, which is also why state you read before an await may have changed after it.

FE·16 TypeScript

The Web Frontend

What if TypeScript checked types at run time too?

Reason it through, then open

Every function call would pay for checks, and the output would no longer be plain JavaScript that runs anywhere. It would also need a runtime representation of every type, which erasure avoids. The practical compromise is to check at the boundaries where untrusted data enters (with validation libraries that also produce types) and trust the checker inside.

What if TypeScript's types were nominal, like Java's?

Reason it through, then open

Two interfaces with identical fields wouldn't be interchangeable, so ordinary JavaScript patterns (passing an object literal, duck typing) would need explicit declarations everywhere. Structural typing fits how JavaScript is written. When you do want nominal distinctions (a UserId that isn't any string), branding adds a fake property to make otherwise identical shapes incompatible.

FE·17 DOM & Browser APIs

The Web Frontend

What if every DOM change re-rendered the page immediately?

Reason it through, then open

Adding a hundred list items would trigger a hundred layouts and paints, and the page would crawl. Browsers instead record that the tree changed and do the work once, before the next frame. The danger case is when you force the work early by asking for a size or position after a change: the browser must lay out now to answer correctly.

What if events didn't bubble?

Reason it through, then open

You'd need a listener on every clickable element, including ones added later. Event delegation (one listener on a container, using event.target.closest() to find what was clicked) would be impossible, and so would the patterns frameworks build on. Bubbling lets one ancestor handle events for a whole, changing subtree.

FE·18 Browser Internals

The Web Frontend

What if all tabs ran in one process?

Reason it through, then open

One crash or memory leak would take every tab with it, one hung script could freeze the whole browser, and a compromised page would share memory with your bank's page. That was the pre-2008 normal. Processes cost memory, which is why browsers balance isolation against footprint, for instance by sharing a process between pages of the same site.

What if animations ran on the main thread only?

Reason it through, then open

Any long JavaScript task would freeze scrolling and animations mid-motion. Because the compositor thread can move, fade and scale already-painted layers without the main thread, animations of transform and opacity stay smooth even while scripts run. Animating top or width needs layout, which only the main thread can do.

FE·19 Frontend Networking

The Web Frontend

What if browsers sent cookies with every cross-site request, as they once did?

Reason it through, then open

Any page could submit a form to your bank and the request would arrive with your session cookie: cross-site request forgery. That was the default for most of the web's history; sites defended themselves with anti-CSRF tokens. SameSite cookies (Lax by default since 2020 in Chrome) stop the cookie travelling on cross-site sub-requests and form posts, removing most CSRF at the browser level.

What if HTTP had no caching?

Reason it through, then open

Every page view would re-download every script, image and font, and every CDN would be a plain proxy. Caching rules (max-age, validators like ETags, immutable for hashed files) are what let a returning visitor load a page from disk in milliseconds, and let CDNs absorb most traffic. The hard part is invalidation, which is why assets get content hashes in their names.

FE·20 Accessibility

The Web Frontend

What if you couldn't use a mouse for a day?

Reason it through, then open

On a well-built site nothing changes: Tab moves through links and controls in a sensible order, focus is always visible, menus open with Enter and close with Escape. On many sites you'd meet controls you can't reach, focus that vanishes or gets trapped in a dialog behind an overlay, and hover-only menus. Keyboard access matters to screen reader users, switch users, voice-control users and anyone with a broken trackpad.

What if colour were the only signal of an error?

Reason it through, then open

About one in twelve men and one in two hundred women have some colour-vision deficiency, and the most common types make red and green hard to tell apart. A red border alone wouldn't tell them which field is wrong; a screen reader wouldn't announce it at all. WCAG requires that colour never be the only means of conveying information: add text, an icon, and a programmatic link between the field and its error message.

FE·21 UI Architecture

The Web Frontend

What if the DOM were the source of truth?

Reason it through, then open

To know whether a todo is done you'd read a checkbox; to count items you'd count elements. Any code that changes the DOM (a browser extension, a third-party widget, a translation tool) could change your data, and re-rendering would erase user input you hadn't saved. Keeping truth in JavaScript data and treating the DOM as an output makes the screen reproducible from state.

What if every component could change any state?

Reason it through, then open

You'd lose the ability to answer "why did this change?": any component might have done it. Bugs would require searching the whole app. One-way data flow (state owned in one place, changed only through its owner's callbacks) keeps that question answerable, at the cost of passing callbacks down.

FE·22 React

The Web Frontend

What if you mutate an array in state instead of replacing it?

Reason it through, then open

items.push(x); setItems(items) passes React the same array. It compares the old and new values by identity, sees no change, and may skip the re-render. Even when something else causes a render, memoised children comparing props by identity won't update. Creating a new array ([...items, x]) is what tells React something changed.

What if an effect's dependency list is wrong?

Reason it through, then open

Leave a dependency out and the effect keeps using the value from an old render: a stale closure, like a chat subscription stuck on the previous room. Add an object that's recreated every render and the effect runs after every render, perhaps in a loop if it sets state. The lint rule for hook dependencies exists because both mistakes are easy and silent.

FE·23 Angular

The Web Frontend

What if Angular checked every binding after every event, as AngularJS did?

Reason it through, then open

Every click, timer and network response would re-evaluate every expression on the page. Small apps wouldn't notice; large ones would spend most of their time checking bindings that hadn't changed. OnPush change detection and then signals let Angular check only components whose inputs or signals actually changed.

What if there were no dependency injection?

Reason it through, then open

Each component would create its own services (new HttpClient(...) with all its configuration), so tests couldn't swap in fakes and two components couldn't share one instance. DI makes "give me something that can do X" the default and lets the application decide what X is: one instance per app, per route, or per component.

FE·24 Full-stack Frameworks

The Web Frontend

What if you hydrated nothing?

Reason it through, then open

The page would load fast and look complete, and no button would work: the HTML is there, the event handlers aren't. That's the honest baseline: decide which parts must be interactive and hydrate only those. Islands architecture makes that the default; Server Components do it at component granularity inside React.

What if every page were statically generated at build time?

Reason it through, then open

Pages would be as fast and cheap as possible to serve, and stale until the next build. Sites with thousands of pages would take long to build, and anything personal (a cart, a dashboard) couldn't be pre-rendered at all. Incremental regeneration rebuilds pages after a time or on demand, trading a little staleness for scale.

FE·25 State Management

The Web Frontend

What if you put server data in a client store as if it were yours?

Reason it through, then open

You'd write by hand what a cache library provides: when to refetch, how to deduplicate requests from two components, what to show while loading, how to invalidate after a mutation, and how to recover from errors. And the copy would silently go stale when someone else changed the data. Server state is a cache; treat it like one.

What if two people edit the same document offline?

Reason it through, then open

When they reconnect, "last write wins" throws one person's work away. Locking would have stopped them working offline at all. CRDTs and operational transformation merge concurrent edits so both survive and every copy converges to the same result, at the cost of more complex data structures and metadata.

FE·26 Frontend Testing

The Web Frontend

What if your tests had 100% coverage?

Reason it through, then open

Every line would have run during a test, which says nothing about whether any test checked its result. A test that renders a component and asserts nothing covers every line. Mutation testing measures what coverage can't: change < to <= and see if a test fails. If none does, that line is covered but untested.

What if end-to-end tests waited a fixed two seconds before each check?

Reason it through, then open

On a fast machine they'd waste time; on a slow CI runner they'd sometimes check too early and fail: flaky by design. Auto-waiting (retrying an assertion until it holds or a timeout passes) ties the test to the condition rather than the clock, which is why modern tools made end-to-end tests far more reliable.

FE·27 Frontend Performance

The Web Frontend

What if you optimised for the average instead of the 75th percentile?

Reason it through, then open

The average is pulled down by your fastest users (good phones, fast connections), so it can look fine while a quarter of your users wait several times longer. Percentiles describe how many people get a bad experience. Core Web Vitals use p75 so that most visitors, including slower ones, are covered.

What if JavaScript were free to download?

Reason it through, then open

It still wouldn't be free to run. Each kilobyte of JavaScript must be parsed, compiled and executed on the main thread, and on a low-end phone that can take several times longer than on a laptop. Image bytes, by contrast, mostly decode off the main thread. That's why shipping less JavaScript helps responsiveness far more than shrinking images by the same number of bytes.

FE·28 Frontend Security

The Web Frontend

What if you kept the access token in localStorage?

Reason it through, then open

Any script running in your page (an XSS payload, a compromised dependency) could read it and send it anywhere, and use it from another machine until it expires. An HttpOnly cookie can't be read by script, so a successful XSS can still act as the user while the page is open, but can't steal the credential for later. That difference in blast radius is why the backend-for-frontend pattern keeps tokens on a server.

What if CSP allowed scripts from your CDN's whole domain?

Reason it through, then open

Any script hosted on that CDN, including old libraries with known gadgets (such as old Angular versions that evaluate expressions in templates), could be loaded by an attacker who finds an injection point. Allowlists of hosts were bypassed so often that "strict" CSP uses nonces or hashes instead: only scripts carrying this response's secret nonce run.

FE·29 PWAs, Workers & WebAssembly

The Web Frontend

What if a service worker cached everything, forever, cache-first?

Reason it through, then open

The app would load instantly offline, and never update: users would keep the version they first saw until they cleared their data, including your bugs. That's why HTML is usually network-first and only content-hashed assets are cached "forever" (a new version gets a new name), and why service workers need a versioned cache they clean up on activation.

What if WebAssembly could call any browser API directly?

Reason it through, then open

Compiled code from anywhere would have the page's full powers with none of the visibility JavaScript has; auditing what a module can do would mean reverse-engineering it. Wasm can only call functions its host explicitly imports into it, so the page decides its capabilities. That design is also what makes Wasm useful outside browsers, for plug-ins and sandboxed server code.

FE·30 Build Tooling & Monorepos

The Web Frontend

What if there were no lockfile?

Reason it through, then open

Every install would resolve ^1.2.0 to whatever is newest today. Two developers, or CI and production, could run different code from the same commit, and a bad patch release of a deep dependency would reach you without any change on your side. The lockfile pins exact versions and integrity hashes, so the dependency tree is part of the commit.

What if bundles weren't split?

Reason it through, then open

Every page would download all the code for every page: the admin screens for every visitor, the chart library on the login page. And any change anywhere would invalidate the one cached file. Splitting by route and keeping vendor code in separately hashed chunks means users fetch only what a page needs and re-fetch only what changed.

FE·31 Frontend Deployment

The Web Frontend

What if you deleted the previous version's assets on every deploy?

Reason it through, then open

Anyone with the app already open would request a lazily loaded chunk that no longer exists and get a 404 in the middle of using it: blank screens and "ChunkLoadError" reports right after every release. Keeping old hashed assets for a while (they cost little) lets open tabs finish their session; the HTML for new visitors points to the new set.

What if HTML were cached for a day at the CDN?

Reason it through, then open

A deploy wouldn't reach users for up to a day, and rollbacks wouldn't either. Worse, different edge locations would serve different versions. HTML is the pointer to everything else, so it's served with revalidation (no-cache) or a very short CDN cache that the deploy purges, while the files it points to are cached for a year.

FE·32 Frontend Observability

The Web Frontend

What if you sent telemetry on the unload event?

Reason it through, then open

On phones it often wouldn't fire at all: switching apps or swiping a tab away usually just hides the page, and the OS may kill it later without unload. You'd lose exactly the sessions that ended abruptly. visibilitychange (when the page becomes hidden) with sendBeacon or fetch with keepalive is the reliable moment, and unload handlers also prevent the back/forward cache from keeping the page.

What if you recorded everything users did?

Reason it through, then open

Debugging would be easier, and you'd be collecting personal data you probably don't need, including what people type, which carries legal duties and real risk if leaked. Good telemetry is designed for questions you need to answer: errors with context, timings, and the steps leading to a failure, with sensitive fields scrubbed by default.

FE·33 Frontend Projects

The Web Frontend

What if you added accessibility at the end?

Reason it through, then open

You'd find custom widgets with no keyboard support, focus lost on every route change, colour-only states and missing labels, each needing changes to components already used everywhere. Built in from the start (native elements, a focus plan, contrast tokens), most of that work never exists. Retrofitting usually costs more than doing it first.

What if you never tested on a slow phone?

Reason it through, then open

Your app's JavaScript would be parsed and run several times faster on your machine than on a median phone, so you'd never see the long tasks that make it feel broken for many users. Throttling in DevTools, or an inexpensive phone kept for testing, turns those hidden costs into visible ones.

BE·00 Start Here: What a Backend Is

The Backend

What if you trusted the client to enforce the rules?

Reason it through, then open

Anyone can send any request with a few lines of code or the browser's developer tools, bypassing your interface completely. Prices, permissions, limits and validation enforced only in the frontend are suggestions. The backend must re-check everything that matters, because it's the only code you actually control.

What if each server kept users' sessions in memory?

Reason it through, then open

With one server it works. With two behind a load balancer, a user's next request may land on the other one, which has never heard of them. Restarting a server logs everyone out. Stateless servers, with sessions in a shared store or in signed tokens, can be added, removed and restarted freely.

BE·33 Language Foundations

The Backend

What if Java had no primitive types, only objects?

Reason it through, then open

Every int would be a heap object with a header, so an array of a million numbers would be a million pointers to a million objects: several times the memory and far worse cache behaviour. Java kept primitives for speed, at the cost of two kinds of values and boxing between them. Project Valhalla's value classes aim to let objects without identity be stored as flatly as primitives.

What if Java exceptions were all unchecked?

Reason it through, then open

Signatures would no longer say which failures a method can produce, so callers would learn about I/O errors at run time. That's how most languages (C#, Kotlin, Python) work, and how most modern Java code behaves in practice, because lambdas and streams don't mix well with checked exceptions. The debate is about whether forcing callers to acknowledge errors helps more than the boilerplate it creates.

BE·34 Object-Oriented Programming and Its Alternatives

The Backend

What if every field were public?

Reason it through, then open

Any code anywhere could put an object into an invalid state (a negative balance, an order with no items), so every reader would have to re-check it, and any change to the representation would break callers you can't find. Encapsulation makes the class the single place that has to get the rules right.

What if you reused code only through inheritance?

Reason it through, then open

Every class would carry its parents' implementation details, and a change to a base class could silently break subclasses that relied on how it called its own methods: the fragile base class problem. Composition (holding an object and delegating to it) reuses behaviour through its public contract only, so the parts can change independently.

BE·35 Collections

The Backend

What if you used a mutable object as a HashMap key and then changed it?

Reason it through, then open

The entry stays in the bucket chosen by its old hash. Looking it up with the changed key computes a new hash and searches a different bucket, so get returns null and containsKey says false, while iterating the map still shows the entry. Keys should be immutable (strings, records of immutable fields) or never changed while stored.

What if equals and compareTo disagree?

Reason it through, then open

A HashSet uses equals, a TreeSet uses compareTo, so the same elements give different sets: BigDecimal's 1.0 and 1.00 are unequal by equals but compare as equal, so a HashSet keeps both and a TreeSet keeps one. The Comparable documentation asks for consistency with equals for exactly this reason.

BE·36 Generics and Type Parameters

The Backend

What if List<Dog> were a subtype of List<Animal>?

Reason it through, then open

See the derivation below: you could add a Cat through the List<Animal> reference and the list of dogs would hold a cat. Java's arrays are covariant (Dog[] is an Animal[]) and pay for it with a run-time check that throws ArrayStoreException. Generics chose to reject the program at compile time instead.

What if Java had reified generics, like C#?

Reason it through, then open

new T[], instanceof List<String> and overloading on List<String> vs List<Integer> would work, and List<int> could store numbers without boxing. The price would have been breaking every library compiled before generics, in 2004. Valhalla is trying to get some of the benefits (specialisation over value types) without that break.

BE·37 Functional Programming

The Backend

What if a stream had no terminal operation?

Reason it through, then open

Nothing would happen. list.stream().map(x -> { log(x); return x; }) without toList() or forEach never calls the lambda, because streams are lazy: intermediate operations only describe the pipeline. That's what lets filter and limit stop early on an infinite stream, and why side effects in intermediate steps are unreliable.

What if you made a sequential stream .parallel()?

Reason it through, then open

The work would be split across the common fork-join pool. Pure, independent operations on large in-memory data might run faster. Lambdas that touch shared state would race; order-dependent operations (findFirst, forEachOrdered) would cost coordination; small streams would be slower from the overhead; and blocking I/O would starve the shared pool for the whole application. Parallelism is only free for pure functions on large, splittable data.

BE·38 Concurrency

The Backend

What if two threads increment an int counter a million times each, unsynchronised?

Reason it through, then open

The total will usually be less than two million. count++ is read, add, write; two threads read the same value, both add one, both write, and one increment is lost. The exact shortfall changes every run. AtomicInteger, LongAdder or a lock make the read-modify-write indivisible.

What if virtual threads made locks unnecessary?

Reason it through, then open

They don't: virtual threads change how cheap threads are, not how they share memory. Races and deadlocks are exactly as possible. What changes is that blocking a thread costs almost nothing, so you can write simple blocking code for I/O instead of callbacks, and use one virtual thread per task rather than a tuned pool.

BE·39 Modern Java Through JDK 27

The Backend

What if you used a preview feature in production?

Reason it through, then open

You'd have to run with --enable-preview, and the feature could change incompatibly or even be withdrawn in the next release (string templates were previewed in Java 21 and 22, then removed). Previews exist to collect feedback before the design is fixed. They're for experiments and early adopters who can afford to rewrite.

What if Java still shipped every three years?

Reason it through, then open

Records, pattern matching, virtual threads and switch expressions would each have waited for the slowest feature in their release, and arrived together in a large upgrade. Small releases reduce the risk of each upgrade and get feedback sooner, the same reasoning as continuous delivery for applications.

BE·40 JVM Internals and Other Runtimes

The Backend

What if every call site in a hot loop saw ten different implementing classes?

Reason it through, then open

The JIT couldn't inline the call: it inlines when a site sees one class (monomorphic) or two (bimorphic), behind a cheap type check. With many classes it falls back to a virtual dispatch each time, and loses the optimisations inlining enables (escape analysis, constant folding across the call). Grouping work by type, or using sealed types and switch, can turn a megamorphic site back into predictable ones.

What if a server process lived only a second?

Reason it through, then open

It would spend its whole life loading classes and interpreting, never reaching C2-compiled code, so the JIT's peak speed would never matter. That's the serverless and command-line case, and why AOT compilation (GraalVM native image) and start-up caching (Project Leyden, class data sharing) exist.

BE·41 Memory and Performance

The Backend

What if you halved the time of a function that takes 10% of a request?

Reason it through, then open

The request gets 5% faster, at best. Amdahl's law applies to latency as well as to cores (ch38): the improvement is bounded by the share of time the part actually takes. That's why the first step is a profile of the whole request, which often shows a database call or network wait dwarfing all the code.

What if your JMH benchmark's result is never used?

Reason it through, then open

The JIT may notice the computation has no effect and delete it, so you'd measure an empty loop and report an absurd speed. JMH's Blackhole (or returning the result) keeps the work alive. Benchmarks also need warm-up, several forks and attention to constant folding; JMH exists because naive timing loops get these wrong.

BE·42 Modules, Packaging and Dependency Conflicts

The Backend

What if two libraries need Guava 20 and Guava 33 respectively?

Reason it through, then open

Only one Guava can be on the classpath. The resolver picks one (nearest or highest), and whichever library expected the other version may fail at the first call to a method that was added, removed or changed. Options: find versions of the libraries that agree, shade (relocate) one library's copy of Guava into its own package, or isolate them in separate class loaders.

What if Maven picked the highest version instead of the nearest?

Reason it through, then open

Libraries would more often get versions at least as new as they asked for, which usually works because most libraries stay backward compatible, but a library asking for an older major version could break. "Nearest wins" lets you fix any conflict by declaring the version you want directly in your own POM, since your declaration is nearest of all. Neither rule is safe without tests; they're different defaults.

BE·43 Build Systems

The Backend

What if a build step read the current date?

Reason it through, then open

Two builds of the same commit would produce different artifacts, so their checksums wouldn't match and caches would never hit. You couldn't prove a released binary came from a given source. Reproducible builds fix timestamps (for example to the commit time), sort file orders and remove machine-specific paths, so anyone can rebuild and compare.

What if the build didn't know the full dependency graph?

Reason it through, then open

It couldn't tell which tasks a change affects, so it would either rebuild everything (slow) or miss something (wrong): the stale-binary problem make was invented to stop. Declared dependencies are what make incremental and cached builds both fast and correct.

BE·44 Backend Fundamentals

The Backend

What if a server stopped instantly on every deploy?

Reason it through, then open

Requests in progress would be cut off mid-response; clients would see errors or, worse, not know whether a payment went through. Graceful shutdown stops accepting new connections, tells the load balancer it's leaving, lets in-flight requests finish within a deadline, then closes resources. Rolling deploys depend on it.

What if business rules lived in controllers?

Reason it through, then open

The same rule would be copied into every entry point (HTTP, a message consumer, a scheduled job) and drift apart; tests would need HTTP requests to check arithmetic. Services keep rules in one place that every entry point calls, and can be tested directly.

BE·45 HTTP API Design

The Backend

What if a client times out on "create payment" and retries?

Reason it through, then open

The first request may have succeeded; the client just didn't hear back. Without protection, the retry creates a second payment. An idempotency key (a client-generated id sent with the request, stored with the result) lets the server recognise the retry and return the original response. It turns an unsafe POST into a safely retryable one.

What if you paginate with ?page=2 over data that's changing?

Reason it through, then open

When rows are inserted or deleted between requests, items shift between pages: clients see duplicates or skip items, and deep pages get slower because the database still counts past every earlier row. Keyset (cursor) pagination asks for "items after this id", which is stable under inserts and uses an index.

BE·46 Spring Core

The Backend

What if a @Transactional method is called from another method of the same class?

Reason it through, then open

The call goes straight to this, not through the proxy Spring wrapped around the bean, so the transaction advice never runs: no transaction starts and nothing rolls back on error. It's the most common Spring surprise. Calling through another bean, or moving the transactional method into its own service, routes the call through a proxy.

What if classes created their own dependencies with new?

Reason it through, then open

Each class would choose its collaborators' concrete types and configuration, so tests couldn't substitute fakes, and changing a database client would mean editing every class that creates one. Injection moves those decisions to one place (configuration), which is the whole point of the container.

BE·47 Spring Boot

The Backend

What if you add a JDBC driver to the classpath with no database configured?

Reason it through, then open

Auto-configuration sees a data-source library and tries to create a DataSource, and with no URL it may fall back to an embedded database if one is present or fail at start-up. That's the trade of convention over configuration: behaviour follows from what's present. The --debug condition evaluation report shows exactly which auto-configurations matched and why.

What if Boot had no "back off when the user defines a bean" rule?

Reason it through, then open

Every customisation would fight the defaults: two ObjectMappers, two security chains, ambiguous injection errors. Most auto-configurations are guarded by "only if no bean of this type exists" (@ConditionalOnMissingBean), so defining your own replaces the default cleanly. That rule is what makes the opinions overridable.

BE·48 Spring Web — MVC and WebFlux

The Backend

What if a reactive pipeline had no backpressure?

Reason it through, then open

A fast producer (a database cursor, a message stream) would push items faster than a slow consumer (a client on a weak connection) could take them, and the items would pile up in memory until the server ran out. Backpressure lets the consumer say how many items it can handle (request(n)), so the producer slows to match.

What if exception handling were left to each controller?

Reason it through, then open

Every controller would format errors differently, some would leak stack traces, and validation failures would come back as 500s in one place and 400s in another. A single @RestControllerAdvice producing Problem Details gives every error the same shape and status logic.

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

The Backend

What if you loop over 100 orders and read each one's customer?

Reason it through, then open

With a lazy association, the ORM runs one query for the orders and then one query per order for its customer: 101 queries where one join would do. It looks fine with 3 test rows and collapses with real data. Fetch joins, entity graphs or a batch-fetch size make the loading explicit.

What if the connection pool had 10 connections and requests held them for a second each?

Reason it through, then open

By Little's law (ch41), the pool can serve at most 10 requests per second; the eleventh waits. Holding a connection during slow work (a remote call inside a transaction) shrinks capacity further. Keep transactions short and do remote calls outside them.

BE·50 Spring Security and Modern Identity

The Backend

What if your API checked roles but not ownership?

Reason it through, then open

Any customer could fetch /orders/1042 belonging to someone else, just by changing the number: an insecure direct object reference, a form of broken access control. Role checks answer "may customers read orders?"; only an object check answers "may this customer read this order?". The check belongs in the service or query (where customer_id = ?), so every entry point gets it.

What if passwords were stored with a fast hash like SHA-256?

Reason it through, then open

A stolen database could be attacked offline at billions of guesses per second on GPUs, and most human passwords would fall quickly. Slow, salted, memory-hard functions (bcrypt, scrypt, Argon2) make each guess expensive and stop precomputed tables, which turns a breach from an immediate catastrophe into a slow, partial one.

BE·51 Asynchronous Work, Jobs and Messaging

The Backend

What if you saved an order and then published "order created" as two separate steps?

Reason it through, then open

If the process crashes between them, the order exists and nobody hears about it; if the publish succeeds and the database commit fails, other services react to an order that doesn't exist. The transactional outbox writes the event to a table in the same database transaction as the order, and a separate relay publishes it, so both happen or neither does.

What if a message always fails to process?

Reason it through, then open

With unlimited retries it blocks its queue or partition forever, and everything behind it waits: a poison message. After a bounded number of attempts it should move to a dead-letter queue, with an alert, where someone can inspect and replay it once the bug is fixed.

BE·52 Resilience

The Backend

What if every layer of a call chain retried three times?

Reason it through, then open

See the derivation below: a failure at the bottom of a three-layer chain receives up to 27 attempts for each original request, exactly when it's least able to cope. Retry at one layer (usually closest to the user), cap retries with a budget, and add jitter.

What if a dependency becomes slow instead of failing?

Reason it through, then open

Errors return quickly; slow calls hold threads, connections and memory while they wait. Without timeouts, Little's law (ch41) says in-flight requests grow with the delay until pools run dry and your service stops answering anything, including requests that don't need the slow dependency. Timeouts, bulkheads (separate pools per dependency) and circuit breakers keep one slow dependency from taking everything down.

BE·53 Caching

The Backend

Reason it through, then open

Every one of them misses at the same moment and goes to the database to rebuild the same value: a cache stampede. The database may fall over and the cache stays empty. Single-flight (one request rebuilds, the rest wait for its result), refreshing before expiry, and jittered TTLs prevent it.

What if the cache cluster disappears?

Reason it through, then open

All reads go to the source at once. If the database was sized assuming a 95% hit rate, it suddenly sees twenty times its normal load. A cache that the system can't run without is no longer an optimisation but a dependency, and needs the capacity planning and failure handling of one.

BE·54 Backend Testing

The Backend

What if you tested the repository against an in-memory database instead of PostgreSQL?

Reason it through, then open

Tests would be fast, and would miss everything that differs: SQL dialect, locking and isolation behaviour, constraints, JSON operators, query plans. A migration that works in H2 can fail in production. Testcontainers runs the real database for integration tests, at the cost of a few seconds of start-up.

What if every collaborator in a unit test were mocked?

Reason it through, then open

The test would check that your code calls its mocks in a particular way: it would pin the implementation, failing on harmless refactors, and still pass if the real collaborators behaved differently from the mocks. Mock at boundaries you own and that are expensive or non-deterministic (a payment gateway, a clock); use real objects for the rest.

BE·55 Backend Projects

The Backend

What if you load-tested only after building everything?

Reason it through, then open

You'd find the bottleneck (a missing index, a pool too small, an N+1 query) at the end, possibly in a design decision that's now expensive to change. Measuring a thin end-to-end slice early tells you where the costs are while the code is still small.

What if you never killed a dependency during testing?

Reason it through, then open

You'd learn how the service behaves without its database or broker during the first real outage, at the worst moment. Stopping a container in a test, injecting latency and replaying duplicate messages turn those unknowns into results you've seen and fixed.

DB·00 Start Here: What a Database Is

Databases

What if programs still navigated data by stored paths?

Reason it through, then open

Adding an index or reorganising storage for speed would break every program that followed the old paths, so physical design would freeze. Codd's data independence (programs say what, not how) is what lets a database add an index tomorrow and make yesterday's queries faster without changing them.

What if constraints lived only in the application?

Reason it through, then open

The first time someone ran a one-off script, a second service wrote to the same table, or two requests raced, invalid data would get in: orders for customers who don't exist, duplicate emails. A foreign key or unique constraint is checked by the database for every writer, every time, including concurrent ones.

DB·55 The Relational Model

Databases

What if a customer's address were stored on every order?

Reason it through, then open

Changing the address means updating every order, and missing one leaves the customer with two addresses (an update anomaly); a customer with no orders has nowhere to store an address at all (an insertion anomaly). Storing the address once, keyed by customer, removes both. If you need the address as it was when the order shipped, that's a different fact (the shipping address), and storing it on the order is correct.

What if NULL meant false?

Reason it through, then open

SQL would be two-valued and simpler, but "unknown" would be indistinguishable from "known to be no". Real SQL's three-valued logic is why WHERE x NOT IN (SELECT y …) returns no rows when any y is NULL: for each x the database can't be sure it's not equal to the unknown value. NOT EXISTS avoids the trap.

DB·56 SQL from SELECT to Window Functions

Databases

What if you join orders to both their items and their payments, then sum the totals?

Reason it through, then open

An order with 3 items and 2 payments produces 3 × 2 = 6 joined rows, so summing item prices counts each item twice and summing payments counts each payment three times. Aggregate each child table separately (in subqueries or CTEs) and then join the results, one row per order.

What if SQL ran in the order it's written?

Reason it through, then open

SELECT comes first in the text, but it can't run first: it needs rows from FROM and filtering from WHERE. That's why you can't use a column alias from SELECT in WHERE, but can in ORDER BY, which logically runs after it. Knowing the logical order explains most "why can't I write this?" errors.

DB·57 PostgreSQL in Depth

Databases

What if a transaction stayed open for a day?

Reason it through, then open

VACUUM can't remove any row version that transaction might still see, so every update and delete in the whole database leaves dead rows that accumulate: tables and indexes bloat, queries slow down, and in the extreme transaction-id wraparound protection forces emergency vacuuming. Idle-in-transaction timeouts and monitoring the oldest transaction age prevent it.

What if PostgreSQL updated rows in place?

Reason it through, then open

Readers would need locks or an undo log to see consistent old values while a writer changed them. Oracle and MySQL's InnoDB do keep old versions in an undo log; PostgreSQL keeps them in the table itself. In-place designs avoid table bloat but pay to reconstruct old versions for long reads; PostgreSQL's design makes reads simple and pushes cost into VACUUM.

DB·58 Storage Engine Internals

Databases

What if you used random UUIDs as a clustered primary key?

Reason it through, then open

Each insert lands on a random leaf page, so the whole index must stay in memory to avoid disk reads, pages split everywhere and fill to about half, and caches thrash. Sequential keys (or time-ordered UUIDs such as UUIDv7) append to the rightmost page instead, keeping inserts cheap and pages full.

What if a database wrote data pages directly instead of logging first?

Reason it through, then open

A crash in the middle of a transaction would leave some pages changed and others not, with no record of what was intended: a torn, inconsistent database. Write-ahead logging records the intent first, sequentially and cheaply; after a crash, redo the committed changes and undo the uncommitted ones from the log.

DB·59 Transactions and Concurrency Control

Databases

What if two on-call doctors both go off call at the same moment?

Reason it through, then open

The rule is "at least one doctor on call". Each transaction reads the table under snapshot isolation, sees two doctors on call, and removes itself. Neither wrote the row the other wrote, so neither conflicts, and both commit: zero doctors on call. That's write skew. Serializable isolation (or locking the rows that were read, with SELECT … FOR UPDATE, or a constraint the database can check) prevents it.

What if the database never aborted transactions?

Reason it through, then open

To guarantee serializable results without aborting, it would have to lock pessimistically and make transactions wait for each other, sometimes for a long time, and deadlocks would still force one to give up. Aborts and retries are the price of letting transactions run in parallel optimistically.

DB·60 Query Optimisation

Databases

What if the planner thinks a filter keeps 10 rows when it keeps 100,000?

Reason it through, then open

It will choose plans that are cheap for 10 rows: a nested loop that looks up each row in another table by index. With 100,000 rows that's 100,000 index lookups instead of one hash join, and the query that "should" take milliseconds takes minutes. Fixing the estimate (fresh statistics, extended statistics on correlated columns) usually fixes the plan without touching the query.

What if you add an index for every query?

Reason it through, then open

Reads get faster, and every insert, update and delete must now update every index: writes slow down, storage grows, and the planner has more options to choose wrongly between. Indexes that are never used still cost on every write. Add indexes for measured needs and remove unused ones.

DB·61 Scaling Databases

Databases

What if you sharded by hash(key) mod N and then added a server?

Reason it through, then open

Changing N changes almost every key's shard: going from 4 to 5 servers moves about 80% of the data. See the derivation below. Consistent hashing (or fixed virtual partitions assigned to servers) moves only the share the new server should own, about 1/5.

What if a user's write goes to the primary and their next read goes to a lagging replica?

Reason it through, then open

They don't see what they just saved, and assume it failed, so they save again. Read-your-writes needs routing: send a user's reads to the primary for a short time after they write, or to a replica that has caught up past their write's log position.

DB·62 NoSQL Data Models and Stores

Databases

What if product managers ask a new question of a Cassandra table?

Reason it through, then open

If it isn't answerable from the partition key, it needs a full scan across nodes (which Cassandra discourages), a new table holding the data arranged for that query, or a secondary index with its own costs. Query-first design is the deal: excellent for known patterns, expensive for new ones. Relational databases handle unplanned questions with a new query.

What if you read and write with quorums where R + W > N?

Reason it through, then open

With N replicas, writing to W of them and reading from R guarantees the read set overlaps the latest write's set, so a read sees the latest acknowledged write (given no concurrent failures muddying it). With N = 3, R = W = 2 gives that overlap while tolerating one replica down. Lower R or W trades the guarantee for latency and availability.

DB·63 Search Engines and Hybrid Search

Databases

What if you used only vector search for a product catalogue?

Reason it through, then open

Queries like "waterproof hiking boots" would work well, but exact searches like a part number "XR-2041B" might return similar-looking codes instead of the one product, because embeddings capture meaning, not exact strings. Keyword search gets exact identifiers right. Hybrid search runs both and fuses the rankings.

What if common words like "the" counted as much as rare ones?

Reason it through, then open

Documents would rank high for containing "the" many times, and a query's distinctive terms would be drowned out. Inverse document frequency weights a term by how rare it is across the collection: matching a rare word says much more about relevance than matching a common one.

DB·64 Durability, Backups and Recovery

Databases

What if your only protection were a synchronous replica?

Reason it through, then open

It would survive the primary's hardware dying with zero data loss, and it would apply a mistaken DROP TABLE within milliseconds, faithfully. Replication copies every change, good or bad. Recovering from a mistake needs a copy from before it: a backup plus logs to replay up to just before the mistake.

What if you'd never timed a full restore?

Reason it through, then open

Your recovery time objective would be a guess. Restoring terabytes, then replaying a day of logs, can take many hours, and the first real attempt often uncovers missing steps, permissions and tools. Regular restore drills turn RTO from a number in a document into a measured fact.

DB·65 Database Projects

Databases

What if you tested with 100 evenly distributed rows?

Reason it through, then open

Every plan would be fast, every lock brief, every index optional. Real data is large and skewed: one customer with a million orders, most with a few. Skew is what breaks estimates and creates hot rows, so generate test data with realistic size and distribution.

What if you killed the database process during a batch of writes?

Reason it through, then open

A correct system recovers to a state where every acknowledged transaction is present and no partial transaction is. Doing it on purpose (and checking) is the only way to know your durability settings and application retries do what you believe.

AN·01 Start Here: What Numbers Are

Arithmetic and Numbers

What if expressions were always read strictly left to right?

Reason it through, then open

3 + 4 × 5 would be 35, not 23, and you'd need brackets around every product inside a sum: 3+(4×5). This isn't hypothetical: the programming language Smalltalk evaluates its binary operators strictly left to right, and many simple four-function calculators do too. Nothing in arithmetic breaks; only the notation gets noisier, because sums of products are far more common than products of sums. That's the whole case for "multiplication first": it's a convenience, not a truth. (APL went the other way and evaluates right to left, for similar reasons of simplicity.)

What if counting started at 1 and there were no zero?

Reason it through, then open

Counting objects would work exactly as before: nobody counts "zero, one, two" sheep. But "how many are left?" would sometimes have no answer (5 − 5), so subtraction would fail even more often, addition would lose its identity element (nothing you add leaves a number unchanged), and place value (chapter 2) would have no way to mark an empty position. Roman numerals had no zero and managed counting and recording; what they couldn't do was calculation in columns. Zero is less about "nothing" than about making the system closed and the notation positional.

What if 1 ÷ 0 were defined to be some number, say 0?

Reason it through, then open

Division is defined as the inverse of multiplication, so 1÷0=0 would mean 0×0=1, which is false. You could keep the rule "x÷0=0" as a separate convention (some proof assistants do, so that division is a total function), but then ab×b=a stops being true in general, and every theorem that uses it needs the extra condition b≠0. The choice only moves the exception; it can't remove it.

AN·02 Place Value and Bases

Arithmetic and Numbers

What if we counted in base twelve?

Reason it through, then open

Twelve has divisors 2, 3, 4 and 6, so a third and a quarter would be "round": 13=0.412 and 14=0.312, both ending, where in decimal a third never ends. Divisibility tests would change: the digit sum would test for 11 (12−1), and the last digit would test for 2, 3, 4 and 6. We'd need two new digit symbols, a times table of 144 facts instead of 100, and fifths would repeat forever. Advocates (the Dozenal Society was founded in 1944) argue the trade is worth it; the cost of changing every numeral, price and habit is why it hasn't happened. Mathematically, nothing about numbers would change, only which of them have short names.

What if computers used base three?

Reason it through, then open

Each wire would have to distinguish three voltage levels reliably, which is harder than two. In exchange, numbers would need fewer digits, and with balanced ternary (digits −1, 0, 1) negative numbers would need no sign bit and rounding would be simply truncation. A real machine did this: the Setun, built at Moscow State University in 1958. By one simple cost model (base × number of digits, the "radix economy"), base 3 is the most efficient whole-number base, slightly ahead of 2 and 4. Binary won because two-state devices are so much cheaper and more reliable that the model's small advantage disappears.

What if numerals had no fixed base at all?

Reason it through, then open

That's a mixed-radix system: each position has its own size, as in 2 days, 3 hours, 46 minutes, 40 seconds. Reading and writing still work, digit by digit with a different divisor each time, and numerals are still unique as long as each digit is below its own position's size. What you lose is uniform arithmetic: carries happen at 60 in one column and 24 in the next, and multiplying by the "base" no longer shifts digits, because there is no single base. That's why time arithmetic feels awkward and why computers convert times to a single count of seconds first.

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

Arithmetic and Numbers

What if a column were allowed to hold more than nine?

Reason it through, then open

You could postpone carrying: add columns independently, let them hold 13 or 18, and tidy up once at the end. Numbers would then have several representations (13 tens and 5 ones is 135, and so is 1 hundred, 3 tens, 5 ones), which breaks uniqueness but speeds up long chains of additions. Hardware does exactly this: a carry-save adder keeps a sum as two numbers (the column sums and the pending carries) so that many numbers can be added without waiting for carries to ripple, and only the final step resolves them. Multiplier circuits are built this way. Uniqueness is convenient for reading numbers, not essential for computing with them.

What if computers added in decimal?

Reason it through, then open

Each decimal digit would be stored in 4 bits (binary-coded decimal), with an adder that carries when a column reaches ten instead of sixteen. Money amounts like 0.10 would be exact, and printing numbers would need no conversion. Early business computers and pocket calculators did use decimal arithmetic, and some mainframes still have hardware decimal floating point for financial work. The costs: about 20% more bits for the same range, and more complex, slower circuits. Binary won for general computing; decimal survives where exact decimal amounts matter.

What if everyone subtracted only by counting up?

Reason it through, then open

Every subtraction would become an addition: start at the smaller number and add convenient steps until you reach the larger. For close numbers and numbers near round values it's the fastest method there is (making change, durations), and it never needs borrowing. For arbitrary large numbers (7,032 − 2,845) the steps depend on the numbers, so it's harder to make into a fixed procedure that's quick and hard to get wrong. That's why written methods survive alongside it: an algorithm is valuable precisely because it doesn't require judgement at every step.

AN·04 Multiplying and Dividing

Arithmetic and Numbers

What if multiplication weren't commutative?

Reason it through, then open

The rectangle argument would have to fail, so "a rows of b" and "b rows of a" would be different things. For numbers that can't happen, but for other mathematical objects it does: rotating an object and then turning it over usually gives a different result from turning it over and then rotating it, and matrices (which describe such moves) don't commute. William Rowan Hamilton's quaternions (1843), used today for 3D rotations in graphics and spacecraft, were the first number-like system people deliberately built without commutative multiplication. Long multiplication would still work, but you'd have to keep every product in its original order.

What if remainders could be negative?

Reason it through, then open

Allow r anywhere from −b2 to b2 and you get the "least absolute remainder": 17=3×5+2 still, but 18=4×5−2. Every number still has exactly one such quotient and remainder (with a tie rule at exactly half), and some algorithms converge faster with it, because the remainder is never more than half the divisor; one version of Euclid's algorithm uses it. Programming languages already disagree about remainders for negative numbers (floored, truncated, Euclidean); this is one more convention, and the theorem's content is only that, once you fix the allowed range, the answer is unique.

What if computers had no division instruction?

Reason it through, then open

Many early and small processors didn't. Division is then a subroutine: binary long division, one quotient bit per step (shift, compare, subtract), which is chapter 4's method with the times table reduced to "0 or 1 times". It's slow, so programmers avoided it: dividing by a power of two became a shift, and dividing by a constant became multiplication by a precomputed reciprocal. Modern compilers still do exactly that, because even with a hardware divider, division takes several times longer than multiplication.

AN·05 Factors, Multiples and Primes

Arithmetic and Numbers

What if 1 counted as a prime?

Reason it through, then open

Nothing about numbers would change, but every statement about primes would need an exception. "Exactly one factorisation" would fail at once: 6 =2×3 =1×2×3 =1×1×2×3, so the theorem would have to say "apart from 1s". The sieve would cross out every number as a multiple of 1. Many writers before the 1900s did call 1 a prime; it was dropped because the exceptions piled up, not because of a discovery. The modern definition (exactly two factors) is a choice that makes the theorems clean.

What if there were only finitely many primes?

Reason it through, then open

Multiply them all and add 1. That number leaves remainder 1 on division by every prime on the list, so its prime factors (it has at least one, being above 1) aren't on the list: the list wasn't complete. This is Euclid's argument, and it shows what "finitely many" would break. Every number would be a product of a fixed handful of primes, so the counts of numbers up to x built from them would grow only like a power of lnx, far slower than x itself: there wouldn't be enough products to go round. Leonhard Euler turned that counting idea into a second proof in 1737, and it led eventually to the prime number theorem.

What if factoring large numbers became easy?

Reason it through, then open

RSA and every system built on it would break: anyone could recover a private key from the public one. That is exactly what Peter Shor's 1994 algorithm would do on a large enough quantum computer, which is why standards bodies are replacing RSA and elliptic-curve key exchange with "post-quantum" methods based on other hard problems. Gcds, primality tests and modular arithmetic would stay easy, as they are now; it's only the gap between multiplying and factoring that cryptography uses, and only that gap would close.

AN·06 Fractions

Arithmetic and Numbers

What if fractions were added top to top and bottom to bottom?

Reason it through, then open

The rule would give 12⊕13 =25. But 24 is the same number as 12, and 24⊕13 =37, which is a different number from 25. So the "sum" would depend on how you happened to write the fraction: it isn't an operation on numbers at all, only on pairs. That's exactly the mediant, and it's meaningful for pairs that are records (runs and balls, orders and visits), where 24 and 12 are different records. The derivation below shows that ordinary addition doesn't have this problem.

What if dividing by zero were allowed?

Reason it through, then open

10 would have to be a number that times 0 gives 1, and nothing does, so ordinary arithmetic breaks: from 1=0×10 you could prove 1=0. Mathematicians do sometimes add a single point "at infinity" written 10, but only after giving up some rules (∞−∞ and 0×∞ have no value). The Stern–Brocot tree starts from 01 and 10 for this reason: as the endpoints that every positive fraction lies between, not as numbers to calculate with. Floating point does something similar: 1/0.0 is inf in many languages, with special rules attached.

What if only unit fractions were allowed, as in Egypt?

Reason it through, then open

Every fraction could still be written (Fibonacci's method, the chapter's lab), so nothing would be lost in what can be expressed. Arithmetic would be harder: doubling 15 gives 25, which must be rewritten as 13+115, and the Rhind papyrus opens with a table of exactly these doublings. But comparing and sharing can be easier: 34 =12+14 says "everyone gets half a loaf and a quarter loaf", which is a practical way to cut bread for four people sharing three loaves.

AN·07 Decimals and Percentages

Arithmetic and Numbers

What if we counted in base 12?

Reason it through, then open

A fraction ends in base 12 when its denominator's primes divide 12, that is, are only 2 and 3. So 13=0.4, 14=0.3 and 16=0.2 would all be short, the fractions people use most in sharing and measuring; but 15 would repeat (0.2497 2497 …), and so would 110. Every base trades one set of short fractions for another. Advocates of base 12 (the "dozenal" societies) argue its trade is better for daily life; base 10 won because of fingers and because the metric system was built on it.

What if money were still divided into 16 annas?

Reason it through, then open

Halving would always be exact down to the smallest coin (16, 8, 4, 2, 1 annas, then pice), which is why many old systems used powers of two and twelves: they suit repeated halving and splitting three ways. But adding a column of "₹3, 11 annas, 2 pice" amounts means carrying at 4 pice and 16 annas, two different carries, and percentages and interest are much harder. Decimalisation gave up easy halving and thirding to make every calculation ordinary column arithmetic, and to make machines and ledgers simpler. Software that stores paise is doing what the 1957 reform did.

What if percentage changes were measured from the end value, or both?

Reason it through, then open

Measured from the end, ₹60 to ₹66 would be a rise of 666≈9.09%, and a rise then an equal fall would still not cancel. Economists use a symmetric measure instead: the log change, ln(new/old), about 9.53 "log points" for 60 to 66 and exactly −9.53 back again. Log changes add up over time (a rise then a fall of the same log size cancels exactly), which is why they're used for growth rates and returns. Chapter 10 introduces the logarithm; the everyday percentage stays measured from the start because that's what a price tag means.

AN·08 Ratio, Proportion and Rates

Arithmetic and Numbers

What if every relationship were proportional?

Reason it through, then open

Prices would have no fixed parts (no delivery fee, no monthly charge), work would always divide perfectly among workers, and bigger animals would be scaled-up small ones. The last one shows why the world isn't like that: if an animal's length doubles, its weight goes up eight times (volume, 23) but the cross-section of its bones only four times (area, 22), so the bones carry twice the stress. Galileo made this argument in 1638, and it's why elephants have thick legs. Proportion is the first model to try and the first to check: scaling laws in chapter 10 show what replaces it.

What if groups were always combined before comparing?

Reason it through, then open

Every study, test and dashboard would report one pooled rate per option, and Simpson's paradox would mislead whenever the options had different mixes of cases. Treatment A in the chapter would be abandoned although it was better for every patient. The opposite rule, "always split by every factor", fails too: split finely enough and each group has only a few cases, and the comparisons become noise. Practice sits between: split by the factors that influence both which option was used and the outcome, and use randomisation where possible so the mixes are equal by design.

What if prices were always quoted per unit?

Reason it through, then open

Comparing would be one glance, and pack-size tricks would stop working. Many countries require unit prices on shelf labels for exactly this reason, and studies of shoppers suggest people use them when they're clear and consistent (the same unit across a product type). Sellers then compete on the unit price, which pushes offers towards simple discounts rather than odd sizes. The arithmetic doesn't change; who does it does.

AN·09 Negative Numbers

Arithmetic and Numbers

What if we had kept separate columns instead of negative numbers?

Reason it through, then open

Accounting did exactly that for centuries, and double-entry bookkeeping still does: debits and credits are both recorded as positive numbers in different columns. It works well for ledgers, and it builds in a check (the columns must balance). But algebra needs one kind of number: solving x+5=3 has no answer without −2, and every formula would split into cases according to which quantities happen to be "losses". Negative numbers let one rule cover every case, at the cost of having to keep track of signs.

What if (−1)×(−1) were −1?

Reason it through, then open

Then (−1)(1+(−1)) would be (−1)+(−1)=−2 by distributivity, but also (−1)×0=0. So 0=−2, and from that every number equals every other. You could keep the rule only by giving up distributivity, and with it the methods of chapters 3 and 4 (long multiplication is distributivity used over and over). There are number systems where some familiar laws fail (matrices aren't commutative, as chapter 4's Deeper page notes), but none keeps distributivity and this sign rule together.

What if computers stored negatives in sign and magnitude?

Reason it through, then open

Some early machines did (and floating-point numbers still do, with a separate sign bit). Adding +5 and −3 would need the hardware to compare sizes, subtract the smaller from the larger and pick the sign, a different circuit from adding two positives. There would be two zeros, +0 and −0, which must compare equal. Two's complement avoids all of that: one adder, one zero, subtraction as adding the negation. The price is the lopsided range and the one value with no opposite; designers judged that a good trade, and almost every processor since the 1960s agrees.

AN·10 Powers, Roots, Scientific Notation and Logarithms

Arithmetic and Numbers

What if 00 were 0?

Reason it through, then open

Formulas that count would break. The number of ways to fill n slots from k choices is kn; with no slots there's exactly one way (do nothing), so k0=1 even for k=0. The binomial theorem, (a+b)n =∑(ni)aibn−i, needs 00=1 to give (0+b)n=bn. And a polynomial like 3+2x written as 3x0+2x1 would equal 0 at x=0 instead of 3. That's why algebra, combinatorics and most programming languages take 00=1. In calculus, the expression f(x)g(x) with both parts heading to 0 can approach anything, so there 00 is left undefined as a limit; the two uses don't conflict.

What if there were no logarithms?

Reason it through, then open

Before calculators, multiplying two seven-digit numbers by hand took minutes and invited errors; astronomers and navigators did thousands of such products. Logarithm tables reduced each to two look-ups, an addition and a reverse look-up. Without them, celestial navigation, astronomy and engineering in the seventeenth to twentieth centuries would have been far slower. Today calculators multiply directly, but logarithms remain essential as ideas: for solving exponential equations, for measuring things across many orders of magnitude, for algorithm analysis, and for working with tiny probabilities without underflow.

What if our scales were linear?

Reason it through, then open

Sound from a whisper to a jet engine spans a factor of about 1012 in power. On a linear scale, every sound people normally hear would be squeezed into the bottom fraction of a percent of the range. Human hearing and vision respond roughly to ratios (the Weber–Fechner observation), so a logarithmic scale like the decibel matches perception: each step feels similar. The same holds for earthquake energy, acidity and star brightness. A linear scale would be exact and useless; a logarithmic one compresses the range into numbers people can compare.

AN·11 Estimation, Rounding, Error and Units

Arithmetic and Numbers

What if every number were exact?

Reason it through, then open

In pure mathematics they are: 13 and 2 are exact numbers. But no ruler, scale or clock delivers an exact real number, and no computer stores most of them. A world of exact measurement would need infinite precision in every instrument and infinite memory in every computer. So applied arithmetic always works with ranges, explicitly (81±0.5 cm) or implicitly (81 cm, to the nearest centimetre). The question is never "is it exact?" but "is it precise enough for the decision?", and that's what error analysis answers.

What if everyone used one unit system?

Reason it through, then open

Most of the world nearly does: the SI is used for science, and metric units for trade, in almost every country. The remaining mixtures (miles, pounds and Fahrenheit in a few countries; feet in aviation altitudes; inches for screens and pipes; acres, guntas and bighas for land in India) persist because of existing equipment, records and habits. Even with one system, conversion wouldn't vanish: prefixes (mg, kg), derived units (kWh against joules) and calendar units still need care. The lesson of the Mars Climate Orbiter is less "use metric" than "make the unit explicit at every interface".

What if we always rounded down?

Reason it through, then open

Truncation is simple and some systems do it (cutting decimals off, integer division towards zero). But it's biased: on average it loses half a unit per value, so totals of truncated amounts drift down steadily (a bank truncating each customer's interest would keep about half a paisa per account per crediting, which over millions of accounts is real money). For quantities that must be whole and sufficient (boxes, seats, cylinders) you round up, not down; for counts of complete things (full boxes) you round down. The rule must match the question.

AN·12 The Real Number Line

Arithmetic and Numbers

What if √2 were a fraction?

Reason it through, then open

Then unique factorisation would fail: p2=2q2 would have the prime 2 an even number of times on the left and an odd number on the right. The whole structure of chapter 5 would collapse, and with it lowest terms, gcds and the tests of chapter 7. So the irrationality of 2 isn't an isolated curiosity: it's a direct consequence of unique factorisation, and as certain as the fact that every number factors into primes in one way.

What if we only ever used fractions?

Reason it through, then open

Every calculation anyone actually performs uses fractions (or floats, which are fractions), so practice would hardly change. Theory would: a function could go from negative to positive without crossing zero (t2−2 on the fractions has no zero), bisection could chase a root that isn't there, and the theorems of calculus (that a continuous function on a closed interval reaches a maximum, that limits exist) would fail. The reals are what make those guarantees true; fractions are what we compute with. Constructive mathematicians build analysis using only what can be computed, and get much of it back, at the cost of some classical theorems.

What if every real number could be computed?

Reason it through, then open

They can't: there are countably many programs and uncountably many reals. But suppose we restricted mathematics to computable reals. Arithmetic would still work, and so would most numbers anyone has met (π, e, 2). But even then, no program can decide in general whether two computable reals are equal, because that might need infinitely many digits to be checked. This is why numerical software always compares with a tolerance, and why computer algebra systems sometimes answer "unknown".

IT·01 Start Here: What Information Is

Information Theory

What if information were measured by the number of possibilities, not the logarithm?

Reason it through, then open

Then two independent messages, one of 8 possibilities and one of 4, would carry 8×4=32 units together but 12 units separately: the measure would multiply when messages are combined. A file twice as long would carry not twice the information but its square. Every practical quantity (how long a line is busy, how much a disk must store) grows by addition, so the measure must turn the multiplication of possibilities into addition, and only the logarithm does. Hartley made exactly this argument in 1928.

What if sender and receiver disagreed about the probabilities?

Reason it through, then open

Surprise depends on the probability the receiver assigns. If a receiver thinks a message is rare when it's actually common, the receiver is "surprised" more than the message deserves, and a code designed for the receiver's beliefs wastes symbols on common messages. Chapter 11 measures that waste exactly: it's the Kullback–Leibler divergence between the true and the assumed probabilities, the quantity machine learning minimises when it trains a model.

What if meaning were part of the measure?

Reason it through, then open

The theory would need to know what every message means to every receiver, and the telephone company would have to understand every conversation to know how much it had carried. Attempts exist: Yehoshua Bar-Hillel and Rudolf Carnap (1952) proposed measuring the semantic information in a statement by how many possible states of the world it rules out. But such measures depend on a language and a model of the world, and none gives theorems as general as Shannon's. Leaving meaning out is what let the theory apply to every kind of message at once.

IT·02 Counting Possibilities: Bits, Logarithms and Questions

Information Theory

What if questions had three answers?

Reason it through, then open

A balance scale answers "left heavier", "right heavier" or "balanced", so each weighing can split the possibilities three ways and give up to log23≈1.585 bits. A tree with three branches at every node has 3d leaves at depth d, so N possibilities need ⌈log3N⌉ weighings: the twelve-coin puzzle of chapter 1 needs 3, since 33=27≥24. Computers built on three-valued "trits" exist (the Soviet Setun, 1958), and base 3 is in a narrow sense the most economical base, but two-state hardware is far easier to build reliably, so binary won.

What if a shuffle used a 64-bit seed?

Reason it through, then open

It could produce at most 264≈1.8×1019 different orders out of 52!≈8×1067: about one in 4×1048. Every game would still look random, but an attacker who sees a few cards could search the seeds, since 264 is within reach of large computing efforts and the first few cards narrow it fast. The safe design draws the shuffle from a cryptographic generator whose state is far bigger than 226 bits, or draws fresh randomness for each card.

What if sorting were allowed to compare three items at once?

Reason it through, then open

A "which of these three is largest, middle and smallest?" question has 6 answers, worth up to log26≈2.585 bits. The log2n! bits still have to be gathered, so the number of such questions is at least log6n!≈(nlog2n)/2.585: fewer questions, but each costs more. The total information is fixed by the problem; the hardware decides how much of it each step can collect. That's why sorting networks, GPUs and databases think about "how many bits per operation", not just "how many operations".

IT·03 The Probability You Need

Information Theory

What if probabilities didn't have to add up to 1?

Reason it through, then open

Then "the chance something happens" could be more or less than certain, and a bettor could exploit anyone whose odds broke the rule. If you price bets on "rain" and "no rain" so that the probabilities you'd accept add to 1.2, someone can sell you both bets and collect 1.2 while paying out exactly 1, whatever the weather: a "Dutch book". Frank Ramsey (1926) and Bruno de Finetti (1937) showed that the axioms are exactly what's needed to avoid such sure losses, which is one argument that degrees of belief should obey them even when there's no frequency to measure.

What if letters in text were independent?

Reason it through, then open

Then the plays' letters would carry their full 4.19 bits each (chapter 1), and no compressor could do better than a code built on letter frequencies alone. Every pair would occur in proportion to its letters' frequencies: "th" no commoner than "ht". Text would read like a scramble of letters in the right proportions, which is what Shannon showed in 1948 by generating "first-order" random text from letter frequencies. The dependence between neighbouring letters, words and ideas is what makes text compressible to under 2 bits per letter, and it's what language models learn.

What if identifiers had to be unique and couldn't coordinate?

Reason it through, then open

Random identifiers from M values collide after about M, so uniqueness without coordination costs twice the bits of a counter: a counter names N things with log2N bits, random names need about 2log2N plus a margin. Systems that can't afford it coordinate a little instead: Twitter's Snowflake ids combine a timestamp, a machine number and a per-machine counter, so each machine only has to avoid collisions with itself, and UUID version 7 puts a timestamp in front of the random bits, so collisions can only happen within the same millisecond.

IT·04 Entropy: the Average Surprise of a Source

Information Theory

What if we averaged probabilities instead of surprises?

Reason it through, then open

The average probability ∑p(x)2 (the chance that two independent draws match) is a real quantity, called the collision probability, and −log2∑p(x)2 is the collision entropy (Rényi entropy of order 2). It's always at most the Shannon entropy and it matters for hashing and for how fast a password guesser expects to succeed. But it doesn't add for independent sources in the way grouping requires, and it isn't the limit of compression. Rényi (1961) found a whole family of such entropies; Shannon's is the one with the grouping property, and the one coding theorems are about.

What if the probabilities you use are wrong?

Reason it through, then open

A code built for probabilities q when the true ones are p costs ∑p(x)log21q(x) bits per symbol on average, the cross-entropy, which is always at least the true entropy H(p). The excess, ∑p(x)log2p(x)q(x), is the Kullback–Leibler divergence: zero only when q=p. Chapter 11 builds on it; it's the quantity machine learning minimises when it fits a model to data.

What if a source had infinitely many symbols?

Reason it through, then open

Entropy can still be finite: a geometric distribution over the whole numbers 1, 2, 3, … with p(k)=2−k has entropy exactly 2 bits, since ∑k2−k=2. But it can also be infinite: probabilities falling slowly enough, like p(k) proportional to 1k(logk)2, add up to 1 while their surprises, weighted, don't add up to anything finite. A source like that can't be compressed to any fixed average number of bits per symbol, however clever the code.

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

Information Theory

What if codewords could use three symbols instead of two?

Reason it through, then open

Huffman's algorithm generalises: merge the three least likely trees at each step (after adding zero-probability dummy symbols so the count works out), and Kraft's inequality becomes ∑3−li≤1. The average length is then at least the entropy measured in trits, H/log23. Morse code is close to this: dots, dashes and gaps make it effectively ternary, with timing as a fourth signal. Binary won for electronics, but the theory doesn't care about the alphabet's size.

What if symbols had costs instead of lengths?

Reason it through, then open

In Morse code a dash takes three times as long to send as a dot, so codewords should be judged by their time, not their number of signals. Finding the best code when the code symbols have unequal costs is a harder problem (studied by Richard Karp in 1961), with no simple bottom-up rule. The entropy bound changes too: the best rate depends on the root of an equation involving the costs. Huffman's algorithm is special to equal-cost symbols.

What if the decoder didn't know the probabilities?

Reason it through, then open

Then the code must either be sent (as DEFLATE sends its lengths) or learned as the data arrives. Adaptive Huffman coding keeps counts and updates the tree after each symbol, so encoder and decoder, seeing the same symbols, always agree. The price is the early symbols, coded with poor estimates, and the work of updating the tree. Universal codes like Elias gamma go further and assume almost nothing, at a cost of about a factor of two. Chapter 6's universal compressors make the cost of not knowing the probabilities vanish per symbol for long inputs.

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

Information Theory

What if a compressor were allowed to lose information?

Reason it through, then open

Then the limit isn't the entropy but a trade-off between bits and distortion: rate–distortion theory, which Shannon founded in 1959. A photo or a song can be coded far below its lossless entropy if small errors are allowed, and the theory says exactly how few bits per symbol are needed for a given average error. JPEG, MP3, AAC and every video codec live on this curve. The source coding theorem is the special case where the allowed distortion is zero.

What if the source changed its statistics halfway through?

Reason it through, then open

A code tuned to the first half would be wrong for the second, and a model that learned from the whole file would be a blend that fits neither. The theorem's guarantee assumes a stationary source. Practical compressors cope by adapting: counts that decay over time, per-block tables (DEFLATE), or models that mix several predictions and shift weight to whichever has been right recently (context mixing). Universal compressors handle any stationary source; for non-stationary data, how fast a compressor forgets is a design choice with no single right answer.

What if you tried to compress the output of a good compressor again?

Reason it through, then open

A good compressor's output is close to random: its bits are nearly independent and equally likely, because any pattern left would have been exploited. So a second pass finds nothing to remove and adds its own header: chapter 4's exercises measured lzma's output at 8.000 bits per byte, and compressing it again made it about 0.03 % bigger. If a second pass does help noticeably, the first compressor was weak (or the data was mixed, such as an archive of compressed and uncompressed files).

IT·07 Joint and Conditional Entropy, Mutual Information

Information Theory

What if we used correlation instead of mutual information?

Reason it through, then open

Correlation measures how well a straight line fits, so it misses any relationship that isn't linear. For X uniform on −2,−1,1,2 and Y=X2, the correlation is exactly 0, while I(X;Y)=1 bit and Y is fully determined by X. On the other hand, correlation is easy to estimate from little data and has a sign (it says which way), while mutual information needs much more data and only says how much. In practice: correlation for quick checks of linear trends, mutual information when the relationship might be anything.

What if processing could create information?

Reason it through, then open

Then you could start with a noisy measurement, run it through a clever enough algorithm, and end up knowing more about the world than the measurement contained: an image upscaler that recovered real detail that the camera never recorded, or a model that learned facts absent from its data. The data processing inequality forbids it. What such systems actually do is add information from somewhere else, their training data or built-in assumptions, which is why an upscaled image's "detail" is a plausible guess, not a recovery, and can be confidently wrong.

What if English had no memory beyond the previous letter?

Reason it through, then open

Then the conditional entropy given the last letter (about 3.3 bits per symbol in the lab) would be the entropy rate, and the best possible compressor would reach that and no further. Shannon's "second-order approximation" to English is exactly such text: it has the right pairs of letters but reads as nonsense ("ON IE ANTSOUTINYS ARE T INCTORE ST" in his 1948 paper). Real English carries far less information per letter, around 1 bit, because words, grammar and meaning reach back much further than one letter.

IT·08 Channels and Noise

Information Theory

What if channels told you which bits were wrong?

Reason it through, then open

Then every channel would be an erasure channel, and protection would be much cheaper: a channel that loses 10 % of bits carries 0.9 bits per use, against 0.531 for one that flips 10 %. Simple schemes work well for erasures: one parity block can rebuild any one lost block, which is how RAID 5 survives a failed disk. Networks get close to this by checking every packet and discarding damaged ones, so the layers above see only missing packets. The difference between the two numbers, about 0.37 bits per use at 10 %, is the price of not knowing where the damage is.

What if errors were never independent?

Reason it through, then open

Real channels make errors in bursts: a scratch on a disc, a fade on a radio link, a lightning strike near a cable. A code designed for one error per block fails when a burst puts several into one block, as the exercises' P2 measured (Hamming(7,4) barely helped until the codewords were interleaved). Engineers respond in three ways: interleave, so a burst is spread over many codewords; use codes over whole bytes (Reed–Solomon), so a burst costs a few symbols rather than many bits; and use CRCs for detection, because they catch every burst up to their length. Memory in the noise is also structure, and in principle a code that models it can do better than one that assumes independence.

What if checksums had to stop attackers too?

Reason it through, then open

None of the chapter's checks would do. Sums, Adler-32 and CRCs are designed so that accidental damage is unlikely to go unnoticed, but they're easy to compute and, for CRCs, linear, so anyone can alter data and fix the check (the companion forges a CRC-32 in a few lines). Checks against attackers need cryptographic hash functions, where finding a different message with the same hash is believed infeasible, and, when the check travels with the data, a secret key (a message authentication code) or a signature. They cost more computation, which is why systems use fast checks for accidents and cryptographic ones where tampering is a risk.

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

Information Theory

What if you could send faster than capacity?

Reason it through, then open

Then a channel that flips one bit in ten could carry more than 0.531 bits of message per bit sent, and the counting argument would break: there would have to be more codewords than non-overlapping clouds of typical noise, so some received blocks would be equally consistent with two or more messages, and the receiver would have to guess. Fano's inequality turns that into a lower bound on errors, and the strong converse shows the error probability actually tends to 1 for long blocks. Every "faster than Shannon" claim so far has turned out to measure something else: more bandwidth or antennas than stated, raw rates that include redundancy, or a channel better than assumed.

What if the receiver could talk back?

Reason it through, then open

For a memoryless channel, feedback doesn't increase capacity (Shannon proved it in 1956), but it changes how easily capacity is reached. On an erasure channel, simply resending whatever was lost achieves capacity with no code at all, as the companion measures. On other channels, feedback makes errors fall much faster with block length and allows simpler codes. That's why networks, where every link can acknowledge, rely on retransmission, while broadcasting, storage and deep space, where there's no useful return path, depend on strong codes.

What if the noise weren't Gaussian?

Reason it through, then open

Among all noises of a given power, Gaussian noise has the most differential entropy, and it turns out to be the worst for communication: any other noise of the same power leaves at least 12log2(1+P/N) bits per use available. So the Gaussian formula is a safe lower bound for systems facing unknown noise of known power. Real noise can still be harder in other ways: impulsive noise (sudden spikes), interference from other transmitters that has structure, or fading, which changes the channel itself; each needs its own model and its own codes.

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

Information Theory

What if a model could predict English perfectly?

Reason it through, then open

Then its cross-entropy would equal the entropy rate of English, whatever that is, and compressing text with it would reach the limit. It still wouldn't reach zero: language carries information because what someone will write next is genuinely uncertain, even to a perfect model of the language. Today's large language models report cross-entropies below 1 bit per character on standard benchmarks, consistent with Shannon's 1951 range, and each improvement lowers the upper bound; nobody knows how much lower it can go, because no one can measure the true rate directly.

What if passwords were chosen by machines?

Reason it through, then open

Then their min-entropy would equal their Shannon entropy, and both would be exactly what the generator provides: 52 bits for 4 random words from 7,776, 78 bits for 12 random printable characters. Guess curves would be flat: 1,000 guesses would break 1,000 in 252 accounts, not 11 % of them. That's the argument for password managers and passkeys: they take the choice away from people, whose choices have a min-entropy around 7 bits. The remaining risks are elsewhere: phishing, reuse across sites (which machines also prevent), and theft of the stored secrets.

What if a random number generator's seed leaked?

Reason it through, then open

Then every output would be predictable to whoever has the seed: a deterministic generator is just an expansion of its seed, and its outputs carry no more min-entropy than the seed did, however random they look. That's why secure generators are reseeded continually from fresh noise, why their state is protected like a key, and why generators are designed so that a leaked current state doesn't reveal past outputs ("forward secrecy" for generators). The Debian bug was the extreme case: the seed had about 15 bits, so every key was one of about 32,767.

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

Information Theory

What if we trained classifiers to maximise accuracy directly?

Reason it through, then open

Accuracy changes only when a prediction crosses the threshold, so it gives no gradient for most parameter changes and can't be optimised by the methods that train neural networks; it's also indifferent to confidence, so the resulting probabilities would mean nothing. Surrogates that behave like accuracy near the threshold (the hinge loss of support vector machines) give good decisions but uncalibrated scores. Cross-entropy is used because it's smooth, rewards honest probabilities, and is maximum likelihood; accuracy is measured afterwards.

What if KL divergence were symmetric?

Reason it through, then open

Then mistaking English for French would cost the same as mistaking French for English, and a model that rules out something that happens would be no worse than one that's merely too vague. Real costs aren't like that: KL's asymmetry records which way the mistake goes. Symmetric versions exist (Jensen–Shannon, which is also bounded), and they're useful for comparing distributions when neither is "the truth", but they lose the interpretation as extra code length or as the rate at which evidence accumulates.

What if a model could reach zero cross-entropy?

Reason it through, then open

Only if the data had no information at all: cross-entropy is at least the entropy, which is zero only for a source that always produces the same thing. A model that reaches near-zero cross-entropy on its training data has memorised it (chapter 7's seven-letter contexts, the companion's leaked split), and on new data it will do worse. The floor for any real source is its entropy rate, unknown for language but certainly above zero.