Kayavak / Deeper / Comparisons
Deeper · Comparisons
Where one idea ends and the next begins
Each idea beside the one it's most often confused with: what they share, how they differ, and when each is right. 93 chapters so far. Also: Derivations · What if? · Origins.
CS·01 Start Here: Computers, Programs and Your Toolbox
Foundations of Computing
| Aspect | Program | Process |
|---|---|---|
| What it is | A file of instructions (source or machine code) | A running instance of a program, with its own memory and state |
| How many | One file on disk | Any number at once, from the same file |
| Lives | Until deleted | From start to exit |
| Has | Instructions | Instructions plus memory, open files, a position in the code |
| Confused because | We say "the program is running" | Running is what turns a program into a process |
CS·02 Programming Fundamentals & Paradigms
Foundations of Computing
| Aspect | Value semantics | Reference semantics |
|---|---|---|
| Assignment copies | The value itself | A pointer to the same object |
After b = a; change b |
a is unchanged |
a sees the change |
| Typical in | Numbers everywhere; structs in C, Go, Rust, Zig; Java primitives | Java and Python objects, JS objects, Go maps and slices |
| Cost | Copying large values | Aliasing: two names, one object |
| Confused because | Python and Java pass references by value: the reference is copied, the object isn't |
CS·03 Data Structures
Foundations of Computing
| Aspect | Hash table | Balanced search tree |
|---|---|---|
| Find, insert, remove | O(1) average, O(n) worst | O(log n) always |
| Ordered iteration, ranges, "next larger key" | No | Yes |
| Needs from keys | A good hash and consistent equality | A consistent ordering |
| Memory | Spare capacity (load factor) | A node per entry, with pointers |
| Pick it when | You only ask "is it there?" and "what's its value?" | You need order, ranges or a guaranteed worst case |
CS·04 Algorithms
Foundations of Computing
| Aspect | Big-O complexity | Actual running time |
|---|---|---|
| Measures | How cost grows with input size | Seconds on a machine, for one input |
| Ignores | Constant factors, caches, the hardware | Nothing: it's what you feel |
| Good for | Predicting what happens when input grows 100× | Deciding between two algorithms at today's size |
| Misleads when | Inputs are small, or constants differ wildly | You measure one size and extrapolate |
CS·05 Discrete Mathematics
Foundations of Computing
| Aspect | "If A then B" (implication) | "If B then A" (converse) |
|---|---|---|
| Example | If it's a prime greater than 2, it's odd | If it's odd, it's a prime greater than 2 |
| True here? | Yes | No: 9 is odd and not prime |
| Equivalent to | "If not B then not A" (contrapositive) | "If not A then not B" (inverse) |
| Confused because | Everyday speech often means "if and only if" | |
| In code | A precondition implies a property; it doesn't follow from it |
CS·06 Number Systems & Data Representation
Foundations of Computing
| Aspect | Binary floating point (double) | Decimal (BigDecimal, decimal) |
|---|---|---|
| Exact for | Integers up to 2⁵³ and fractions with power-of-two denominators | Any number with a finite decimal expansion |
| 0.1 + 0.2 | 0.30000000000000004 | 0.3 |
| Speed | One hardware instruction | Software, many times slower |
| Use for | Measurements, science, graphics, ML | Money and anything with legal decimal rounding rules |
CS·07 Computer Architecture
Foundations of Computing
| Aspect | Instruction set architecture (ISA) | Microarchitecture |
|---|---|---|
| What it is | The contract: instructions, registers, memory model | How one chip implements that contract |
| Examples | x86-64, ARM64, RISC-V | Pipeline depth, cache sizes, number of execution units |
| Changes | Rarely, and compatibly | Every chip generation |
| Visible to programs | Always | Only as speed (and in side channels) |
| Confused because | "Faster CPU" usually means a better microarchitecture of the same ISA |
CS·08 Operating Systems
Foundations of Computing
| Aspect | Process | Thread |
|---|---|---|
| Memory | Its own address space | Shares its process's address space |
| Isolation | A crash or bad pointer stays inside | One bad write can corrupt every thread |
| Creation and switching | Heavier: new page tables | Lighter: new stack and registers |
| Communication | Pipes, sockets, shared memory set up on purpose | Just read and write the same variables (hence races) |
| Pick it when | You want isolation (browsers' tabs, servers' workers) | You want cheap sharing and accept the discipline it needs |
CS·09 Networking Fundamentals
Foundations of Computing
| Aspect | TCP | UDP |
|---|---|---|
| Delivers | An ordered, reliable byte stream | Independent datagrams, maybe lost, duplicated or reordered |
| Setup | A handshake before data | None |
| Message boundaries | None: applications must frame messages | Each datagram is one message |
| Congestion control | Built in | Up to the application (QUIC adds it) |
| Use for | Web, databases, files, most APIs | DNS queries, real-time media, games, and as the base for QUIC |
CS·10 Compilers & Runtimes
Foundations of Computing
| Aspect | Ahead-of-time compiler | Interpreter | JIT compiler |
|---|---|---|---|
| Translates | Before running, all at once | Not to machine code; executes as it reads | While running, only hot code |
| Start-up | Fast | Fast | Slow until warm |
| Peak speed | High | Low | High, sometimes higher (it knows run-time facts) |
| Examples | C, Rust, Go, Zig | CPython's bytecode loop | Java HotSpot, V8, PyPy |
| Confused because | Most real systems combine them: Java compiles to bytecode ahead of time, then interprets and JIT-compiles it |
CS·11 Computer Science Mastery Projects
Foundations of Computing
| Aspect | Understanding | Being able to build |
|---|---|---|
| Shows up as | You can follow an explanation | You can produce a working version without one |
| Tested by | Questions, quizzes | A project, under your own decisions |
| Fails silently | Yes: rereading feels like understanding | Rarely: the program either works or it doesn't |
| Builds | Recognition | Recall, judgement and debugging skill |
FE·00 Start Here: How the Web Works
The Web Frontend
| Aspect | The internet | The web |
|---|---|---|
| What it is | The network of networks carrying packets (IP) | One application on it: linked documents over HTTP |
| Since | ARPANET 1969; TCP/IP 1983 | Proposed 1989; public 1991 |
| Other uses | Email, video calls, games, file transfer, SSH | None: it is one use |
| Confused because | Most people reach the internet through a browser |
FE·12 The Web Platform
The Web Frontend
| Aspect | Origin | Site |
|---|---|---|
| Made of | Scheme + host + port | Scheme + registrable domain (eTLD+1) |
https://a.shop.example:443 vs https://b.shop.example |
Different origins | Same site |
| Governs | Same-origin policy, storage, most web APIs | Cookies' SameSite, site isolation processes |
| Confused because | "Cross-origin" and "cross-site" sound alike and differ for subdomains |
FE·13 HTML
The Web Frontend
| Aspect | <a href> |
<button> |
|---|---|---|
| Means | Go somewhere | Do something |
| Keyboard | Enter | Enter and Space |
| Works without JavaScript | Yes: it navigates | Only inside a form (submits it) |
| Gets for free | Open in new tab, copy link, history | Form submission, disabled state |
| Mistake | A link with href="#" and a click handler that doesn't navigate |
A button that only changes the URL |
FE·14 CSS
The Web Frontend
| Aspect | Specificity | Cascade layers |
|---|---|---|
| Decided by | The selector's shape (ids, classes, types) | The order layers are declared |
| Controlled by | Whoever writes each selector | The architecture, in one place |
| Problem it causes | Wars of ever-more-specific selectors | None of its own: it's the fix |
| Which wins first | Layers are compared before specificity: a simple selector in a later layer beats a complex one in an earlier layer |
FE·15 JavaScript
The Web Frontend
| Aspect | Task (macrotask) | Microtask |
|---|---|---|
| Comes from | Events, timers, network callbacks, messages | Promise reactions, queueMicrotask, await resumptions |
| When it runs | One per turn of the event loop | All of them, right after the current task, before rendering |
| Danger | A long one blocks input | An endless chain of them starves rendering and tasks |
| Confused because | Both are "later"; microtasks are much sooner |
FE·16 TypeScript
The Web Frontend
| Aspect | A type assertion (x as T) |
A type guard (narrowing) |
|---|---|---|
| What it does | Tells the checker "trust me" | Proves the type with a run-time check |
| Checked at run time | No | Yes |
| Wrong when | The data isn't really a T: errors appear later, elsewhere |
Never, if the guard is correct |
| Use for | Rare cases the checker can't follow | Anything from outside your code |
FE·17 DOM & Browser APIs
The Web Frontend
| Aspect | textContent |
innerHTML |
|---|---|---|
| Treats the string as | Text | Markup to parse |
<img onerror=…> in the data |
Shows the characters | Runs the attacker's code |
| Speed | Fast, no parsing | Parses HTML |
| Use for | Anything that came from a user or an API | Trusted or sanitised HTML only |
FE·18 Browser Internals
The Web Frontend
| Aspect | Main thread | Compositor thread |
|---|---|---|
| Does | Parsing, style, layout, paint recording, all page JavaScript | Combining painted layers into frames, scrolling, some animations |
| Blocked by | Long tasks | Rarely blocked by page code |
| Animate cheaply here | Nothing, if it can be avoided | transform, opacity |
| Confused because | Both are "the browser rendering" |
FE·19 Frontend Networking
The Web Frontend
| Aspect | CORS | CSRF protection |
|---|---|---|
| Protects | The response: whether another origin's script may read it | The server: against requests made with your credentials from another site |
| Enforced by | The browser, using the server's headers | The server (tokens) and the browser (SameSite) |
| Stops a request being sent? | Mostly not: simple requests still reach the server | Yes, that's its point |
| Confused because | Both concern cross-origin requests; they guard opposite directions |
FE·20 Accessibility
The Web Frontend
| Aspect | Native HTML | ARIA |
|---|---|---|
| Changes | Semantics and behaviour (focus, keyboard, form participation) | Semantics only: role, name, state |
A role="button" on a div |
Still needs tabindex, Enter and Space handling written by you |
|
| First rule | Use it whenever an element exists | Use it only to fill gaps HTML can't |
| Risk | Low | Bad ARIA misinforms users, which is worse than none |
FE·21 UI Architecture
The Web Frontend
| Aspect | Virtual DOM diffing | Signals (fine-grained reactivity) |
|---|---|---|
| On a change | Re-run the component, compare the new tree with the old | Update only what read the changed value |
| Cost grows with | Size of the re-rendered component tree | Number of dependents of the value |
| Mental model | Write it as if everything re-renders | Values notify their readers |
| Used by | React, Preact | Solid, Svelte 5, Angular signals, Vue's reactivity |
FE·22 React
The Web Frontend
| Aspect | State | Ref |
|---|---|---|
| Changing it | Schedules a re-render | Doesn't re-render |
| Read during render | Yes: it's the snapshot | Shouldn't be: it may change between renders |
| Use for | Anything shown on screen | Timer ids, DOM nodes, values you need between renders but don't display |
FE·23 Angular
The Web Frontend
| Aspect | Signals | RxJS observables |
|---|---|---|
| Represents | A value that changes over time, always readable now | A stream of events over time |
| Read | Synchronously, count() |
By subscribing |
| Good for | State shown on screen | Async workflows: debounce, retry, cancel, combine streams |
| Bridged by | toSignal / toObservable |
FE·24 Full-stack Frameworks
The Web Frontend
| Aspect | Server-side rendering (SSR) | Static generation (SSG) |
|---|---|---|
| HTML built | On every request | Once, at build time |
| Fresh data | Always | Only after a rebuild or revalidation |
| Server cost | Per request | Almost none (CDN files) |
| Personalised pages | Yes | No, except through client-side fetching |
FE·25 State Management
The Web Frontend
| Aspect | Client state | Server state |
|---|---|---|
| Owned by | This browser | A server (shared with others) |
| Examples | Open menus, form drafts, theme | User records, orders, search results |
| Can be stale? | No: it's the truth | Always potentially |
| Tool | Local state, a store | A query cache with invalidation |
FE·26 Frontend Testing
The Web Frontend
| Aspect | Code coverage | Mutation score |
|---|---|---|
| Measures | Which lines ran during tests | Which planted bugs tests caught |
| Says about test quality | Little: running isn't checking | Directly: a surviving mutant is an untested behaviour |
| Cost | Cheap | Expensive: runs the suite once per mutant |
FE·27 Frontend Performance
The Web Frontend
| Aspect | Lab data | Field data (RUM) |
|---|---|---|
| Comes from | One controlled run (Lighthouse, WebPageTest) | Real visits (Chrome UX Report, your own monitoring) |
| Good for | Debugging, comparing before and after a change | Knowing what users actually experience |
| Measures INP? | No: needs real interactions (TBT is a proxy) | Yes |
| Misleads when | Conditions differ from users' | Traffic is small or skewed |
FE·28 Frontend Security
The Web Frontend
| Aspect | XSS | CSRF |
|---|---|---|
| Attacker's code runs | In your page, as your origin | On their own site |
| What it can do | Anything your page can, including reading data | Send requests with your cookies, but not read responses |
| Main defences | Output escaping, sanitising, CSP, Trusted Types | SameSite cookies, anti-CSRF tokens, checking Origin |
| Which is worse | XSS defeats CSRF protections |
FE·29 PWAs, Workers & WebAssembly
The Web Frontend
| Aspect | Web Worker | Service Worker |
|---|---|---|
| Purpose | Parallel computation for one page | A network proxy and background agent for a whole scope |
| Lives | As long as its page keeps it | Independently of pages; started by events |
| Can intercept requests | No | Yes |
| Typical use | Parsing, image processing, running Python | Offline support, caching, push notifications |
FE·30 Build Tooling & Monorepos
The Web Frontend
| Aspect | ES modules | CommonJS |
|---|---|---|
| Syntax | import / export |
require() / module.exports |
| Resolved | Statically, before running | Dynamically, while running |
| Tree shaking | Yes | Hard: any require could be computed |
| Loading | Asynchronous | Synchronous |
| Where | Browsers, modern Node, Deno, Bun | Older Node code |
FE·31 Frontend Deployment
The Web Frontend
| Aspect | Static hosting + CDN | Server-rendered (Node, serverless, edge) |
|---|---|---|
| Runs your code | Only in the browser | On servers too |
| Cost and scaling | Very low, scales with the CDN | Per request or per instance |
| Failure modes | Mostly cache configuration | Cold starts, timeouts, distance to data |
| Rollback | Switch a pointer | Redeploy or shift traffic |
FE·32 Frontend Observability
The Web Frontend
| Aspect | Monitoring | Observability |
|---|---|---|
| Answers | Known questions: is the error rate up? | New questions you didn't plan for: why are these users failing? |
| Built from | Dashboards and alerts on chosen metrics | Rich, high-cardinality events and traces you can slice |
| Confused because | Tools offer both under one name |
FE·33 Frontend Projects
The Web Frontend
| Aspect | It works | It's done |
|---|---|---|
| Checked with | Your browser, your mouse, your Wi-Fi | Keyboard, screen reader, slow network and device, tests, a deployed URL |
| Covers | The happy path | Errors, empty states, loading, offline |
| Who it serves | You | Everyone who'll use it |
BE·00 Start Here: What a Backend Is
The Backend
| Aspect | Frontend | Backend |
|---|---|---|
| Runs on | Users' devices | Machines you operate |
| Trusted? | No | Yes: the only place rules are enforced |
| Serves | One person | Everyone at once |
| Failure looks like | One broken screen | Everyone affected |
BE·33 Language Foundations
The Backend
| Aspect | == |
equals() |
|---|---|---|
| On primitives | Compares values | Not applicable |
| On references | Same object? | Equal content, as the class defines it |
Integer 127 vs 127 |
true (cached box) |
true |
Integer 128 vs 128 |
Usually false |
true |
BE·34 Object-Oriented Programming and Its Alternatives
The Backend
| Aspect | Inheritance | Composition |
|---|---|---|
| Relationship | Is-a | Has-a, uses-a |
| Reuses | Implementation | Behaviour through an interface |
| Coupling | Tight: subclasses see protected details | Loose: only the public contract |
| Change at run time | No | Yes: swap the delegate |
| Use when | A true subtype that honours the contract | Almost everything else |
BE·35 Collections
The Backend
| Aspect | Unmodifiable view (Collections.unmodifiableList) |
Immutable copy (List.copyOf) |
|---|---|---|
| Can callers change it? | No | No |
| Can the original change underneath? | Yes: the view shows it | No: it's a snapshot |
| Use when | You want read-only access to live data | You want a value nobody can change |
BE·36 Generics and Type Parameters
The Backend
| Aspect | ? extends T |
? super T |
|---|---|---|
| You can | Read values as T |
Write values of T |
| You can't | Write (except null) | Read as anything but Object |
| Example | copy(List<? extends Number> src, …) |
…, List<? super Integer> dst) |
| Memory aid | Producer extends | Consumer super (PECS) |
BE·37 Functional Programming
The Backend
| Aspect | Pure function | Function with side effects |
|---|---|---|
| Result depends on | Only its arguments | Also on, or changes, outside state |
| Call it twice | Same result, nothing else changes | Maybe different results, maybe two database rows |
| Test | Inputs and outputs | Set up and inspect the outside world |
| Reorder or parallelise | Safe | Unsafe without thought |
BE·38 Concurrency
The Backend
| Aspect | Concurrency | Parallelism |
|---|---|---|
| Means | Several tasks in progress at once | Several tasks executing at the same instant |
| Needs multiple cores | No | Yes |
| Typical goal | Handle many waiting things (I/O) | Finish CPU work faster |
| Example | A server with 10,000 open connections | Sorting a large array on 8 cores |
BE·39 Modern Java Through JDK 27
The Backend
| Aspect | Preview feature | Final feature |
|---|---|---|
| Enabled by | --enable-preview at compile and run time |
Default |
| Can change | Yes, or be removed | Only through the normal deprecation process |
| Use in production | Not advisable | Yes |
BE·40 JVM Internals and Other Runtimes
The Backend
| Aspect | JIT (HotSpot) | AOT (native image) |
|---|---|---|
| Start-up | Slow until warm | Fast |
| Peak throughput | High; uses run-time profiles | Usually lower, without profile-guided builds |
| Memory | Higher (compiler, profiles) | Lower |
| Dynamic features (reflection, class loading) | Fully supported | Must be declared at build time |
BE·41 Memory and Performance
The Backend
| Aspect | Memory footprint | Allocation rate |
|---|---|---|
| Means | Bytes live at a moment | Bytes created per second |
| Shown by | Heap histograms, heap dumps | Allocation profilers, JFR |
| Problem when high | Out of memory, large heaps | GC work, CPU, cache pollution |
| Can differ | A scan allocating nothing has zero allocation and can still be slow |
BE·42 Modules, Packaging and Dependency Conflicts
The Backend
| Aspect | Classpath | Module path |
|---|---|---|
| Unit | JARs, unordered contents | Named modules with requires and exports |
| Encapsulation | None: every public class is reachable | Only exported packages are reachable |
| Missing dependency found | At run time, when used | At start-up |
| Split packages | Allowed, silently | Rejected |
BE·43 Build Systems
The Backend
| Aspect | Incremental build | Cached (hermetic) build |
|---|---|---|
| Reuses | Outputs from your last build, on your machine | Outputs from any build, anywhere, with the same inputs |
| Needs | Changed-file detection | Every input declared and hashed |
| Fails when | State on disk is stale or corrupted | An input isn't declared |
BE·44 Backend Fundamentals
The Backend
| Aspect | Thread per request (incl. virtual threads) | Event loop |
|---|---|---|
| Code style | Sequential, blocking calls | Callbacks, promises, reactive streams |
| One slow call | Blocks only its own thread | Blocks everything on that loop, if it blocks |
| Debugging | Normal stack traces | Fragmented stacks |
| Examples | Spring MVC, Go, Java with virtual threads | Node.js, Netty, WebFlux, Vert.x |
BE·45 HTTP API Design
The Backend
| Aspect | Safe | Idempotent |
|---|---|---|
| Means | Doesn't change server state | Doing it twice has the same effect as once |
| GET, HEAD | Yes | Yes |
| PUT, DELETE | No | Yes |
| POST | No | No (unless you make it so, e.g. with an idempotency key) |
BE·46 Spring Core
The Backend
| Aspect | Constructor injection | Field injection |
|---|---|---|
| Dependencies visible | In the constructor's signature | Hidden in private fields |
Can be final |
Yes | No |
| Testable without Spring | Yes: call the constructor | Needs reflection or the container |
| Recommended | Yes | No |
BE·47 Spring Boot
The Backend
| Aspect | Spring Framework | Spring Boot |
|---|---|---|
| Provides | The container, DI, web, data, transactions | Defaults, starters, auto-configuration, packaging, operations endpoints |
| You configure | Everything explicitly | Only what differs from the defaults |
| Runs as | Whatever you build | A self-contained JAR by default |
BE·48 Spring Web — MVC and WebFlux
The Backend
| Aspect | Spring MVC | Spring WebFlux |
|---|---|---|
| Model | Thread per request (or virtual thread) | Event loop with reactive types (Mono, Flux) |
| Blocking calls | Fine | Must be avoided or moved off the loop |
| Streaming and backpressure | Limited | First-class |
| Choose when | Most request–response services | Streaming, many long-lived connections, reactive end to end |
BE·49 Persistence — JDBC, JPA, Hibernate and Spring Data
The Backend
| Aspect | ORM (JPA/Hibernate) | Plain SQL (JdbcClient) |
|---|---|---|
| Good for | Entity lifecycles: load, change, save | Reports, bulk updates, tuned hot queries |
| You control the SQL | Indirectly | Exactly |
| Hidden costs | Lazy loads, dirty checking, flushes | None beyond what you wrote |
| Risk | N+1 queries, surprising writes | Hand-mapping mistakes |
BE·50 Spring Security and Modern Identity
The Backend
| Aspect | OAuth 2.0 | OpenID Connect |
|---|---|---|
| Answers | What may this client access on the user's behalf? | Who is the user? |
| Main token | Access token (for APIs) | ID token (for the client, about the user) |
| Use for | Calling APIs | Logging users in |
| Common mistake | Using an access token as proof of identity |
BE·51 Asynchronous Work, Jobs and Messaging
The Backend
| Aspect | Queue | Log (Kafka-style) |
|---|---|---|
| A message after processing | Removed | Kept for the retention period |
| Several consumer groups | Compete for messages | Each reads every message independently |
| Replay history | No | Yes, from any offset |
| Ordering | Per queue, weakened by parallel consumers | Per partition |
BE·52 Resilience
The Backend
| Aspect | Circuit breaker | Retry |
|---|---|---|
| Responds to failure by | Stopping calls for a while | Trying again |
| Helps | The failing dependency recover; callers fail fast | Transient blips succeed |
| Hurts when | Thresholds are wrong and it trips on noise | The dependency is overloaded or the error is permanent |
| Together | Retries inside a breaker: the breaker caps how much retrying can happen |
BE·53 Caching
The Backend
| Aspect | TTL expiry | Explicit invalidation |
|---|---|---|
| Staleness | Up to the TTL | Until the invalidation arrives (usually short) |
| Complexity | Low | High: every write path must invalidate correctly |
| Failure mode | Stale reads for a bounded time | Missed invalidations: stale until the next one |
| Common choice | Both: invalidate on write, TTL as a safety net |
BE·54 Backend Testing
The Backend
| Aspect | Mock | Fake |
|---|---|---|
| Is | A double you program with expectations | A working lightweight implementation (in-memory repository) |
| Verifies | Interactions: was this called? | State: what's there afterwards? |
| Breaks when | The implementation changes how it calls things | The fake drifts from the real behaviour |
| Prefer | At external boundaries | For your own interfaces |
BE·55 Backend Projects
The Backend
| Aspect | Works | Production-ready |
|---|---|---|
| Handles | Valid requests, healthy dependencies | Invalid input, duplicates, slow and failed dependencies, overload |
| Proven by | Manual tries | Tests, measurements, failure injection |
| Visible when broken | No | Logs, metrics and traces say what happened |
DB·00 Start Here: What a Database Is
Databases
| Aspect | A database | Files |
|---|---|---|
| Concurrent writers | Coordinated by transactions | Your problem |
| Crash in the middle of a change | Recovered from the log | Possibly a half-written file |
| Asking a new question | A new query | New code to read and filter |
| Shared rules | Constraints enforced for everyone | Conventions |
DB·55 The Relational Model
Databases
| Aspect | Natural key | Surrogate key |
|---|---|---|
| Is | A real-world identifier (email, ISBN) | A generated id with no meaning |
| Can change | Yes: people change emails | Never |
| Exposes information | Often | No |
| Use | As a UNIQUE constraint | As the primary key, usually |
DB·56 SQL from SELECT to Window Functions
Databases
| Aspect | GROUP BY |
Window function |
|---|---|---|
| Rows out | One per group | One per input row |
| Can see | The group's aggregate | The aggregate and each row's own values |
| Example | Total sales per day | Each sale with its day's running total |
DB·57 PostgreSQL in Depth
Databases
| Aspect | PostgreSQL's MVCC | Undo-log MVCC (InnoDB, Oracle) |
|---|---|---|
| Old versions live | In the table, as dead tuples | In a separate undo area |
| Cleanup | VACUUM | Purge of undo records |
| Cost shows up as | Bloat if VACUUM falls behind | Long reads reconstructing old versions; undo growth |
DB·58 Storage Engine Internals
Databases
| Aspect | B-tree | LSM tree |
|---|---|---|
| Writes | In place, random page writes | Appended, sorted and merged later |
| Reads | One path down the tree | May check several levels (Bloom filters help) |
| Space | Pages partly empty after splits | Old versions until compaction |
| Suits | Read-heavy, mixed OLTP | Write-heavy, ingest-heavy |
DB·59 Transactions and Concurrency Control
Databases
| Aspect | Snapshot isolation (Repeatable Read in PostgreSQL) | Serializable |
|---|---|---|
| Each transaction sees | A consistent snapshot | A consistent snapshot, plus conflict detection |
| Prevents | Dirty and non-repeatable reads, lost updates on the same row | Every anomaly, including write skew |
| Costs | Little | Some aborts to retry; tracking overhead |
DB·60 Query Optimisation
Databases
| Aspect | Nested loop join | Hash join |
|---|---|---|
| Best when | The outer side is small and the inner side has an index | Both sides are large, joined on equality |
| Cost grows with | Outer rows × lookup cost | Size of both inputs (linear) |
| Bad when | The outer side is much larger than estimated | The hash table doesn't fit in memory |
DB·61 Scaling Databases
Databases
| Aspect | Replication | Sharding |
|---|---|---|
| Each server holds | All the data | A part of the data |
| Scales | Reads, and availability | Writes and storage too |
| Costs | Replication lag | Cross-shard queries and transactions, rebalancing |
DB·62 NoSQL Data Models and Stores
Databases
| Aspect | Row store (OLTP) | Column store (OLAP) |
|---|---|---|
| Stores together | All columns of a row | All values of a column |
| Fast at | Reading and writing whole rows by key | Scanning a few columns over many rows |
| Compression | Modest | Very high: similar values sit together |
| Use for | Applications | Analytics and reporting |
DB·63 Search Engines and Hybrid Search
Databases
| Aspect | Keyword (BM25) | Semantic (vectors) |
|---|---|---|
| Matches | The same terms (after analysis) | Similar meanings |
| Strong at | Names, codes, rare terms, exact phrases | Paraphrases, synonyms, natural-language questions |
| Explainable | Yes: which terms matched | Hardly |
| Cost | Cheap | Embedding every document and query; vector index memory |
DB·64 Durability, Backups and Recovery
Databases
| Aspect | RPO | RTO |
|---|---|---|
| Measures | How much data you can afford to lose | How long you can afford to be down |
| Set by | Backup and log-archive frequency | Restore speed and procedures |
| Proven by | Restoring and checking the latest data | Timing a full restore drill |
DB·65 Database Projects
Databases
| Aspect | A schema that stores the data | A database design |
|---|---|---|
| Considers | What to store | What to store, how it's queried, how it changes concurrently, how it's recovered |
| Proven by | Inserting rows | Plans, load tests, concurrency tests, restore drills |
AN·01 Start Here: What Numbers Are
Arithmetic and Numbers
| Aspect | Number | Numeral |
|---|---|---|
| What it is | A quantity: what all collections of that size share | A name for a number, written in some system |
| How many there are per quantity | One | Many: 7, VII, ७, 111 in binary, "seven" |
| What arithmetic acts on | Numbers | Numerals only through a method that respects the number (column addition, chapter 3) |
| What changes with culture or machine | Nothing | Symbols, base, grouping, separators, word order |
| In software | A value of a numeric type | Its text, bits or encoding ("42", 0x2A, 6 bits) |
AN·02 Place Value and Bases
Arithmetic and Numbers
| Aspect | Positional (Hindu–Arabic, binary) | Additive (Roman, tally, Egyptian) |
|---|---|---|
| A symbol's value depends on | Its position | Only the symbol (and, in Roman, a few subtraction rules) |
| Needs a zero | Yes, to hold empty places | No |
| Length grows like | The number of digits, | Roughly the number's size, or worse |
| One numeral per number | Yes, without leading zeros | Not necessarily (IIII and IV) |
| Calculating on paper | Column methods with a small table of facts | Practically needs counters or an abacus |
| Still used for | Almost everything | Clock faces, chapter numbers, monarchs, tally marks |
AN·03 Adding and Subtracting, and Why the Methods Work
Arithmetic and Numbers
| Aspect | Decomposition (borrowing) | Equal addition ("borrow and pay back") |
|---|---|---|
| What changes | The top number is rewritten (same value, different digits) | Both numbers grow by the same amount, in different columns |
| Rule it relies on | Regrouping never changes a number | Same difference: |
| Borrowing across zeros | Each 0 becomes 9 on the way; several digits change | No special case: the "pay back" goes to the next bottom digit |
| Easy to picture with bundles | Yes: open a bundle | Less so: the added ten and the added one sit in different columns |
| Where it's taught | Dominant in most schools today | Common in many countries until the mid-twentieth century; still taught in some |
AN·04 Multiplying and Dividing
Arithmetic and Numbers
| Aspect | Division with remainder () | Exact division ( ) |
|---|---|---|
| Works in | Whole numbers | Fractions (ch06) and decimals (ch07) |
| Answer | Two whole numbers, quotient and remainder | One number |
| Always exists | Yes, for any divisor of at least 1 | Yes, for any divisor except 0 |
| Right when | Things come in wholes: people, buses, eggs | The quantity can be split: juice, money (to the paisa), length |
| In code | divmod, // and % |
/ (floating point) or a fraction type |
AN·05 Factors, Multiples and Primes
Arithmetic and Numbers
| Aspect | Testing whether a number is prime | Finding its prime factors |
|---|---|---|
| Example | Is 1,000,000,007 prime? | What are the factors of a 600-digit product? |
| By trial division | Up to divisions | Up to divisions, the same |
| Best known method | Fast (Miller–Rabin in practice; AKS proved polynomial time in 2002) | No known polynomial-time method on ordinary computers |
| Answer for a 600-digit number | Seconds | Far beyond any computer today |
| Used for | Generating cryptographic keys | Breaking them; so its difficulty is the security |
AN·06 Fractions
Arithmetic and Numbers
| Aspect | A fraction, | A ratio, 3 : 4 |
|---|---|---|
| What it is | One number | A comparison between two (or more) quantities |
| Equal forms | , always the same number | 3 : 4 = 6 : 8 as a comparison, but "3 boys and 4 girls" isn't "6 boys and 8 girls" |
| More than two parts | No | Yes: 2 : 1 : 1 |
| Adding | Not defined; combining groups adds the counts (the mediant) | |
| Turning one into the other | — | 3 : 4 means the first is of the second, or of the total |
| Studied in | This chapter | Chapter 8 |
AN·07 Decimals and Percentages
Arithmetic and Numbers
| Aspect | Percent (%) | Percentage points (pts) |
|---|---|---|
| Measures | A relative change, or a share of a base | The difference between two percentages |
| 8 % to 10 % is | A 25 % rise | A 2-point rise |
| Depends on the starting value | Yes | No |
| Adds up over successive changes | No (changes multiply) | Yes (differences add) |
| Used for | Price changes, growth, shares | Changes in rates: interest, unemployment, vote shares |
| Common confusion | "Up 2 %" said when 2 points is meant | Rarely confused the other way |
AN·08 Ratio, Proportion and Rates
Arithmetic and Numbers
| Aspect | Direct proportion, | Linear with a fixed part, |
|---|---|---|
| Example | Petrol at ₹104.80 a litre | A taxi: ₹50 plus ₹25 a km |
| Doubling | Doubles | Doesn't double (unless ) |
| Ratio | Constant, | Falls as grows, towards |
| Graph | Straight line through the origin | Straight line crossing the -axis at |
| Rule of three | Works | Gives wrong answers; subtract first |
| Average cost per unit | Same at every size | Lower at larger sizes (the fixed part is spread out) |
AN·09 Negative Numbers
Arithmetic and Numbers
| Aspect | Integers (mathematics) | -bit signed integers (computers) |
|---|---|---|
| Range | Unbounded in both directions | to |
| Every number has an opposite | Yes | All but |
| Always | Fails at , which wraps to | |
| Laws of arithmetic | All hold | , , hold modulo ; order doesn't survive the wrap |
| Division of negatives | One convention chosen by the writer | Fixed by the language (usually truncated) |
| What overflow does | Nothing; there is none | Wraps, saturates, traps or is undefined, by language |
AN·10 Powers, Roots, Scientific Notation and Logarithms
Arithmetic and Numbers
| Aspect | Exponential growth, | Polynomial growth, |
|---|---|---|
| Example | Compound interest, doubling bacteria, | Area of a square , comparisons in a simple sort |
| Doubling the input | Squares the growth factor () | Multiplies the output by |
| Adding 1 to the input | Multiplies the output by | Adds a shrinking proportion |
| On a log–linear chart | A straight line | A curve that flattens |
| On a log–log chart | A curve that steepens | A straight line of slope |
| Eventually | Overtakes every polynomial, however large | Overtaken by every exponential with |
AN·11 Estimation, Rounding, Error and Units
Arithmetic and Numbers
| Aspect | Precision | Accuracy |
|---|---|---|
| Meaning | How finely a value is stated or measured | How close a value is to the truth |
| Shown by | Significant figures, decimal places, the instrument's resolution | Comparison with a trusted reference |
| Example | A scale reading 72.384 kg is precise | If it's miscalibrated by 2 kg, it's inaccurate |
| Improved by | Better instruments, more digits | Calibration, removing systematic errors |
| Can mislead when | Many digits suggest a reliability the method lacks | A single check against a wrong reference |
| In software | Float digits printed | Whether the computation or data is right |
AN·12 The Real Number Line
Arithmetic and Numbers
| Aspect | Rational numbers | Irrational numbers |
|---|---|---|
| Written as | with whole | No fraction; a symbol (, ) or an infinite decimal |
| Decimal | Ends or repeats | Never ends, never repeats |
| Examples | , 0.125, , | , , , , |
| How many | Countably many | Uncountably many |
| Share of the line | Total length zero | Everything else |
| In a computer | Exactly (fraction types), or nearly (floats) | Only approximately |
IT·01 Start Here: What Information Is
Information Theory
| Aspect | A binary digit | A bit of information |
|---|---|---|
| What it is | A stored or sent symbol, 0 or 1 | A unit of resolved uncertainty |
| Counted by | Looking at the file or the signal | Probabilities: |
| One file of a million zeros | 8,000,000 of them | About none |
| Can be fractional | No | Yes: a die roll is 2.585 |
| Changed by compression | Yes: that's the point | No: compression keeps the information |
| Changed by a better model of the data | No | It's measured relative to the model; the true limit is the source's entropy (ch04) |
IT·02 Counting Possibilities: Bits, Logarithms and Questions
Information Theory
| Aspect | Counting possibilities () | Entropy (chapter 4) |
|---|---|---|
| Assumes | Every possibility equally likely | Possibilities have given probabilities |
| Measures | The most information a message from the set can carry | The average information it actually carries |
| For English letters | bits | About 4.19 bits (chapter 1's lab), less with context |
| Best code | Fixed-length, in blocks | Variable-length: short codes for likely symbols |
| Lower bound it gives | No code beats for every sequence | No code beats the entropy on average |
| When they agree | Uniform probabilities | Uniform probabilities |
IT·03 The Probability You Need
Information Theory
| Aspect | Independence | Disjointness |
|---|---|---|
| Meaning | Knowing one tells you nothing about the other | They can't both happen |
| Rule | ||
| , usually not 0 | 0 | |
| Two events with positive probability | Can be independent | If disjoint, they're dependent: one rules the other out |
| Example | Two different dice showing six | One die showing 1 and the same die showing 6 |
| In information terms | Surprises add | Knowing one happened gives full information about the other (it didn't) |
IT·04 Entropy: the Average Surprise of a Source
Information Theory
| Aspect | Entropy of a source | Surprise of a message |
|---|---|---|
| Belongs to | A probability model of everything that might be sent | One outcome |
| Formula | ||
| Can be larger than ? | No | Yes, for rare outcomes |
| Units | Bits per symbol, on average | Bits, for this outcome |
| Tells you | The average cost of the best code | The cost of this message under the best code, roughly |
| In the lab | 0.469 bits for a 90/10 coin | 0.152 bits for heads, 3.32 for tails |
IT·05 Codes: Prefix Codes, Kraft's Inequality and Huffman Coding
Information Theory
| Aspect | Prefix (instantaneous) code | Uniquely decodable code that isn't prefix |
|---|---|---|
| Decoding | Each codeword recognised as soon as it ends | May need to look ahead, sometimes far |
| Kraft's inequality | Holds | Also holds (McMillan) |
| Best average length | Same | Same |
| Example | 0, 10, 110, 111 | 1, 10, 100 (readable from the right) |
| Used in practice | Almost always | Rarely: no gain, more complexity |
| Why the distinction matters | Proves you lose nothing by choosing prefix codes | Shows unique decodability is the real requirement |
IT·06 The Source Coding Theorem: Why Entropy Is the Limit
Information Theory
| Aspect | Huffman coding | Arithmetic coding |
|---|---|---|
| Unit of coding | One codeword per symbol | One number for the whole message |
| Cost per symbol | Whole digits, at least 1 | , fractions included |
| Distance from entropy | Up to 1 bit per symbol | About 2 bits per message, plus tiny rounding |
| Changing probabilities | Rebuild the code | Free: any model, any symbol |
| Speed | Fast, table lookups | Slower; ANS closes the gap |
| Error spread | Often resynchronises | Everything after an error is lost |
IT·07 Joint and Conditional Entropy, Mutual Information
Information Theory
| Aspect | Mutual information | Correlation |
|---|---|---|
| Detects | Any dependence | Linear dependence only |
| Range | 0 to bits | −1 to 1 |
| Zero means | Independent | No linear relationship (could still be dependent) |
| Direction | None: symmetric, unsigned | Signed: says which way |
| Units | Bits | None |
| Data needed | A lot, especially for many values | Little |
| For , symmetric | 1 bit (fully dependent) | 0 |
IT·08 Channels and Noise
Information Theory
| Aspect | Detection (checks) | Correction (codes) |
|---|---|---|
| Redundancy needed | Small: 8 to 32 bits per block | Grows with the errors to fix |
| Needs a second chance | Yes: resend, reread or another copy | No |
| Typical tools | Parity, check digits, Adler-32, CRCs | Hamming, SECDED, Reed–Solomon, LDPC |
| Fails when | Damage happens to form another valid block (about ) | More errors than the code's distance allows |
| Failure looks like | Undetected damage | Wrong "corrections", possibly adding errors |
| Used in | Networks, files, typed identifiers | Memory, storage, radio, deep space |
IT·09 Channel Capacity and the Noisy-Channel Coding Theorem
Information Theory
| Aspect | Below capacity () | Above capacity () |
|---|---|---|
| Best block error, long blocks | Tends to 0 | Tends to 1 (strong converse) |
| Effect of longer blocks | Fewer errors (lab: 3.7 % to 0.24 % at rate 0.25) | More errors (lab: 49 % to 61 % at rate 0.75) |
| What limits it | Delay, decoding effort | Information: too little gets through |
| Fano's bound | No constraint | At least for long blocks |
| Engineering response | Longer, better codes | Lower the rate, raise the SNR, add bandwidth |
IT·10 Information Everywhere: Language, DNA, Randomness and Passwords
Information Theory
| Aspect | Shannon entropy | Min-entropy |
|---|---|---|
| Measures | Average surprise | Surprise of the most likely value |
| Question answered | How short can descriptions be on average? | How likely is the best single guess? |
| For a uniform distribution | (the same) | |
| One value with probability ½ | Can still be large | 1 bit |
| Estimated from samples | Biased low, badly for long tails | Stable: needs only the top value |
| Used for | Compression, communication | Keys, tokens, passwords, randomness sources |
IT·11 Information in Machine Learning: Cross-Entropy and KL Divergence
Information Theory
| Aspect | (forward) | (reverse) |
|---|---|---|
| Averages over | The data | The model |
| Punishes | Missing where data occurs | Putting probability where data doesn't occur |
| Infinite when | somewhere | somewhere |
| Fitting behaviour | Covers all modes, spreads out | Picks a mode, stays inside |
| Used by | Maximum likelihood, log loss, compression | Variational inference, some reinforcement learning penalties |
| Lab result (two bumps) | Centre 0, width 3.15 | Centre +3, width 1.00 |