RecapsKayavak

Kayavak / Recaps / Foundations of Computing

Recaps · Volume 1

Foundations of Computing

The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.

Open the volume

02

Programming Fundamentals & Paradigms

Key ideas

  • A program is source text that is translated (compiled, interpreted, or both) into instructions a machine runs; the stages and their errors are in chapter 10.
  • A variable is a name bound to a value stored somewhere; its type decides how the bits are interpreted and which operations are allowed.
  • Value vs reference semantics: assigning a primitive copies it; assigning an object (Java, Python, Go maps/slices, JS objects) copies a reference, so both names see changes.
  • Expressions produce values; statements do things. Operator precedence and integer vs float division differ by language (Python 7 // 2 == 3, -7 // 2 == -4; C/Java/Go truncate: -7 / 2 == -3).
  • Control flow: sequence, selection (if, switch/match), iteration (for, while), plus early exit (break, continue, return) and exceptions.
  • Functions take parameters and return results; each call gets a stack frame with its locals; recursion needs a base case and progress toward it.
  • Abstraction hides how behind what: interfaces, traits and protocols let code depend on capabilities rather than concrete types (polymorphism).
  • Errors are handled by exceptions (Java, Python, C++), error values (Go, C), or result types (Rust Result, Zig error unions). Whatever the mechanism, decide where each error is handled and never silently ignore one.
  • Immutability and ownership reduce bugs: values that can't change can be shared freely; Rust makes ownership explicit and checks it at compile time.
  • Static typing catches type errors before running; dynamic typing finds them when the line executes. Strong vs weak is about implicit conversions, a separate axis.
  • Testing: unit tests check small pieces against known answers and properties; a debugger or well-placed prints show the actual state when reality and expectation differ.

Numbers to remember

  • Default thread stack: about 8 MB on Linux (main thread), 1 MB typical for JVM threads (-Xss); deep recursion runs out around tens of thousands of frames.
  • Python's default recursion limit: 1,000.
  • Java int is 32-bit (about ±2.1 billion), long 64-bit; Python int is unbounded.

Pitfalls

  • = (assignment) vs == (comparison); == vs .equals() for Java strings and objects.
  • Off-by-one: range(1, n) stops at n − 1; the last index is len − 1.
  • Mutating a list while iterating over it; mutable default arguments in Python (def f(x=[])).
  • Integer division where you meant real division (5 / 2 is 2 in C and Java).
  • Swallowing exceptions (catch (Exception e) {}) hides the bug instead of fixing it.
  • Comparing floats with == (chapter 6).

Glossary

  • Binding: the association between a name and a value or storage location.
  • Scope: the region of code where a name is visible.
  • Side effect: any change a function makes beyond returning a value (printing, writing a file, mutating an argument).
  • Pure function: same inputs, same output, no side effects.
  • Stack frame: the block of stack memory holding one call's parameters, locals and return address.
  • Heap: memory for values that outlive the call that created them.
  • Interface / trait: a named set of operations a type promises to provide.
  • Serialization: turning in-memory data into bytes or text (JSON, binary) and back.
  • Paradigm: a style of organising programs: imperative, object-oriented, functional, declarative.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Java passes objects by reference." It passes references by value (call by sharing). The callee can't make your variable point elsewhere.
"final makes an object immutable." It makes the variable unassignable. The object it refers to can still change (a final List can still be added to).
"Records are immutable." Records are shallowly immutable. A record holding a List is only as immutable as that list (the TiffinBox build, stage 2, copies it).
"Removing from a list while looping always throws ConcurrentModificationException." Not always: removing the second-to-last element makes the loop end quietly and skip the last element.
"== compares values for small numbers, so it's safe for IDs." It compares references. It only looks right for Integer values from −128 to 127, and that range is configurable.
"Go's go vet catches loop-variable capture." It flags captures in go and defer statements, but not closures stored for later.
"Recursion is always slower than a loop." With tail calls optimised, it compiles to the same loop. Without them, it costs a frame per call. Clarity, not speed, usually decides.

03

Data Structures

Key ideas

  • A data structure is a way of arranging data in memory so that the operations you need are cheap; every structure trades some operations off against others.
  • Arrays store items contiguously: O(1) access by index, cache-friendly scanning, O(n) insertion in the middle. Dynamic arrays (Java ArrayList, Python list, Go slices, Rust Vec) double their capacity when full, giving amortised O(1) append.
  • Linked lists give O(1) insert/remove at a known node but O(n) search and poor cache behaviour; in practice arrays usually win.
  • Stacks (last in, first out) model calls, undo and parsing; queues (first in, first out) model waiting work and BFS; a deque does both ends.
  • Hash tables map keys to buckets with a hash function: O(1) average lookup, insert and delete; O(n) worst case under bad hashing or attack. Needs a good hash, correct equality, and resizing at a load factor (Java HashMap: 0.75).
  • Binary search trees keep keys sorted for O(log n) operations only when balanced (red-black, AVL); B-trees are wide balanced trees designed for disks and databases.
  • Heaps give the minimum (or maximum) in O(1) and insert/remove in O(log n): the structure behind priority queues and scheduling.
  • Graphs are vertices plus edges, stored as adjacency lists (sparse) or matrices (dense).
  • Advanced: tries for prefixes, union-find for connectivity, Bloom filters for "definitely not / maybe" membership, skip lists, segment trees.
  • Choose by asking: which operations, how often, how big, ordered or not, concurrent or not, memory budget.

Numbers to remember

Structure Access Search Insert Delete
Array (by index) O(1) O(n) O(n) (append amortised O(1)) O(n)
Sorted array O(1) O(log n) O(n) O(n)
Linked list O(n) O(n) O(1) at a known node O(1) at a known node
Hash table — O(1) average O(1) average O(1) average
Balanced BST — O(log n) O(log n) O(log n)
Binary heap min O(1) O(n) O(log n) O(log n) (min)
  • A Java object header is 8–16 bytes depending on JVM version and settings; a boxed Integer in a collection costs about 16 bytes plus a 4–8 byte reference, which is why int[] can be several times smaller than List<Integer>.

Pitfalls

  • Choosing a linked list for "fast inserts" and then searching it every time.
  • Mutating an object used as a hash key so its hash changes: the entry becomes unreachable.
  • Overriding equals without hashCode in Java (or __eq__ without __hash__ in Python).
  • Assuming hash map iteration order (Go deliberately randomises it).
  • Forgetting the worst case: an unbalanced BST built from sorted input is a linked list.

Glossary

  • Amortised cost: average cost per operation over a long sequence, even if a few are expensive.
  • Load factor: entries ÷ buckets in a hash table.
  • Collision: two keys landing in the same bucket; resolved by chaining or open addressing.
  • Balanced tree: one whose height stays O(log n).
  • Locality: placing data used together close together in memory.
  • Persistent structure: one where updates create new versions and old versions stay valid.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"O(1) means fast." It means the cost doesn't grow with n. Hashing a long key, or a cache miss, can make an O(1) step slower than several O(log n) ones.
"A trie makes prefix search instant." Reaching the prefix's node is instant; collecting and sorting everything under it isn't.
"A PriorityQueue is a sorted list." It's heap-ordered and unstable.
"Sorted means numeric order." A TreeMap<String, …> sorts k12 before k7, character by character.
"Arrays.asList turns any array into a list." Not a primitive array: Arrays.asList(int[]) is a list of one element, the array itself.
"A subList is a smaller list." It's a view of the original: it shares storage, keeps the whole original alive, and breaks if the original is structurally modified.
"Bloom filters never give false negatives." True only if items are never removed. Deleting by clearing bits creates false negatives; counting Bloom filters exist for that.

04

Algorithms

Key ideas

  • Judge an algorithm by correctness (every valid input), termination, and cost in time and space as a function of input size.
  • Big-O gives an upper bound on growth, Big-Ω a lower bound, Big-Θ a tight bound. Analyse worst, average and amortised cases separately.
  • Searching: linear O(n) on anything; binary O(log n) on sorted data; hashing O(1) average.
  • Sorting: comparison sorts can't beat Ω(n log n). Merge sort is O(n log n) and stable; quicksort O(n log n) on average, O(n²) worst; heapsort O(n log n) in place; insertion sort wins on tiny or nearly sorted input. Counting/radix sort beat n log n by not comparing. Libraries use hybrids (Timsort for Python and Java objects, introsort in C++ standard libraries, pdqsort-style sorts in Go and Rust).
  • Divide and conquer: split, solve recursively, combine; costs follow recurrences like T(n) = 2T(n/2) + n = O(n log n).
  • Dynamic programming: when subproblems overlap and the best answer is built from best sub-answers, solve each subproblem once (memoised top-down or tabulated bottom-up).
  • Greedy: take the locally best choice; correct only with a proof (exchange argument, matroid structure).
  • Graphs: BFS gives shortest paths in unweighted graphs; DFS gives reachability, cycles, topological order; Dijkstra handles non-negative weights; Bellman-Ford handles negative edges; minimum spanning trees by Kruskal or Prim.
  • Strings: naive matching O(nm); KMP and Z-algorithm O(n + m); Rabin-Karp by rolling hash.

Numbers to remember

  • log₂ of 1 thousand ≈ 10, 1 million ≈ 20, 1 billion ≈ 30.
  • A modern core does very roughly 10⁸–10⁹ simple steps per second: O(n²) on n = 10⁵ is about 10¹⁰ steps, too slow for interactive use; O(n log n) on 10⁷ is fine.
  • Dijkstra with a binary heap: O((V + E) log V). BFS/DFS: O(V + E).

Pitfalls

  • Binary search midpoint (lo + hi) / 2 overflows fixed-size ints; use lo + (hi - lo) / 2.
  • Quicksort with a fixed pivot on sorted input degrades to O(n²).
  • Greedy without a proof (coins 1, 3, 4 for amount 6).
  • Recursion depth on large inputs: convert deep recursion to iteration or an explicit stack.
  • Dijkstra with negative edge weights gives wrong answers silently.
  • Forgetting that hidden constant factors and cache behaviour decide between algorithms of the same Big-O.

Glossary

  • Invariant: a condition true before and after every loop iteration, used to prove correctness.
  • Stable sort: equal keys keep their original relative order.
  • In place: uses O(1) (or O(log n)) extra memory.
  • Memoisation: caching a function's results by argument.
  • Topological order: an ordering of a directed acyclic graph's vertices with every edge pointing forward.
  • Relaxation: improving a distance estimate via an edge, the core step of shortest-path algorithms.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"An O(n log n) algorithm is always faster than an O(n²) one." Only beyond some n. Library sorts use insertion sort below 32–44 elements.
"Sorted input is the worst case for quicksort." For naive first-element pivots. Library quicksorts choose pivots from samples and fall back to heapsort; TimSort is fastest on sorted input.
"A DP solution is polynomial." It's polynomial in the table size, which may be exponential in the input's length.
"If the heap holds an object, updating the object updates the heap." The heap doesn't know you changed it; order breaks silently.
"binarySearch returns −1 when not found." It returns -(insertion point) - 1, which is −1 only when the key would go first. Any negative means not found.
"Memoisation makes recursion safe." It removes repeated work, not depth.

05

Discrete Mathematics

Key ideas

  • Sets and their operations (union, intersection, difference, complement, power set, Cartesian product) are the language of databases, types and specifications.
  • A relation is a set of pairs; properties (reflexive, symmetric, transitive, antisymmetric) define equivalence relations (partitions) and partial orders (dependencies, versions).
  • A function maps each input to exactly one output; injective (one-to-one), surjective (onto), bijective (both, so invertible). The pigeonhole principle follows: hashing n + 1 keys into n buckets forces a collision.
  • Propositional logic: and, or, not, implication, equivalence; De Morgan's laws; predicate logic adds "for all" (∀) and "there exists" (∃), the language of preconditions and invariants.
  • Proof techniques: direct, contrapositive, contradiction, cases, construction, and induction (ordinary and strong), the basis of reasoning about loops and recursion.
  • Counting: product and sum rules, permutations n!/(n−k)!, combinations n!/(k!(n−k)!), inclusion–exclusion, binomial theorem.
  • Graph theory: degree, paths, cycles, connectivity, trees (n vertices, n − 1 edges, no cycles), bipartite graphs, planarity and colouring.
  • Probability: sample spaces, independence, conditional probability and Bayes' rule, expected value and its linearity, variance; the birthday paradox.
  • Recurrences describe recursive cost; solve by unrolling, recursion trees or the master theorem.
  • Boolean algebra is logic as algebra on 0 and 1, the basis of circuits and condition simplification.

Numbers to remember

  • 2¹⁰ = 1,024; 2²⁰ ≈ 1 million; 2³² ≈ 4.3 billion; 2⁶⁴ ≈ 1.8 × 10¹⁹.
  • Birthday paradox: with 23 people, P(shared birthday) ≈ 0.5; for a b-bit hash, collisions become likely around 2^(b/2) items (about 77,000 for 32 bits).
  • C(n, 2) = n(n − 1)/2 pairs: 1,000 items have 499,500 pairs.

Pitfalls

  • Reading "if A then B" as also meaning "if B then A" (the converse).
  • Treating events as independent when they share a cause (correlated failures in one data centre).
  • Induction without a base case, or a step that silently assumes something beyond n.
  • Confusing permutations (order matters) with combinations.
  • Base-rate neglect: a 99%-accurate test for a 1-in-1,000 condition is mostly false positives.

Glossary

  • Cardinality: the number of elements in a set.
  • Contrapositive: "if not B then not A", logically equivalent to "if A then B".
  • Invariant: a property that stays true throughout a process.
  • Expected value: the probability-weighted average outcome.
  • Bijection: a one-to-one correspondence between two sets.
  • DAG: directed acyclic graph.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"x % n is always in 0…n−1." In Java, C, C++, Go and Rust it's negative for negative x. Use Math.floorMod.
"Math.abs returns a non-negative number." Math.abs(Integer.MIN_VALUE) is Integer.MIN_VALUE: there's no positive 2³¹ in an int.
"NOT IN and NOT EXISTS are the same." Only when the subquery can't produce NULL.
"A join just adds columns." A join of relations multiplies rows when keys repeat: customer 1 with 2 orders becomes 2 rows, and SUM after the join double-counts.
"java.util.Random is random enough for tokens." It's a public recurrence; two outputs predict the third.
"Passing 1,000 random tests proves it." It's evidence about the cases tried. Exhaustive checking of a finite space, or a proof, says something about all cases.

06

Number Systems & Data Representation

Key ideas

  • All data is bits; the type decides the meaning. The same 8 bits 11111011 are 251 unsigned, −5 signed, or a byte of a UTF-8 sequence.
  • Positional notation in base b; binary for hardware, hex as 4-bit shorthand, octal for Unix permissions.
  • Unsigned n-bit integers cover 0 to 2ⁿ − 1; two's complement signed integers cover −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1, and negate by "invert and add 1".
  • Overflow behaviour differs: C/C++ unsigned wraps, signed overflow is undefined behaviour; Java and Go wrap; Rust panics in debug and wraps in release unless you choose checked_, wrapping_ or saturating_ operations; Zig traps in safe modes; Python ints never overflow.
  • Bitwise operations (AND, OR, XOR, NOT, shifts) manipulate flags and masks; arithmetic right shift keeps the sign, logical shift fills with zeros.
  • IEEE 754 floating point: sign, exponent, fraction; doubles carry 53 significant bits (about 15–17 decimal digits). Most decimal fractions are inexact; results round at every step; special values ±0, ±∞ and NaN (NaN ≠ NaN).
  • Money and exact quantities: integers in the smallest unit or decimal types (BigDecimal, Python decimal).
  • Text: Unicode assigns code points; UTF-8 encodes them in 1–4 bytes, ASCII-compatible; UTF-16 (Java, JavaScript strings) uses 2 or 4 bytes. "Length" may mean bytes, UTF-16 units, code points or user-perceived characters (grapheme clusters).
  • Byte order: little-endian on x86 and usual ARM; big-endian on the network. Alignment: types sit at multiples of their size, so structs gain padding.

Numbers to remember

  • int8 −128..127; uint8 0..255; int32 about ±2.15 × 10⁹; int64 about ±9.22 × 10¹⁸.
  • Doubles represent every integer exactly up to 2⁵³ = 9,007,199,254,740,992 (JavaScript's Number.MAX_SAFE_INTEGER is 2⁵³ − 1).
  • Float32 has about 7 significant decimal digits.
  • UTF-8 lengths: U+0000–007F 1 byte, to U+07FF 2, to U+FFFF 3, beyond 4.

Pitfalls

  • 0.1 + 0.2 == 0.3 is false; compare with a tolerance.
  • (int) casts truncate toward zero; rounding is a separate operation.
  • Mixing signed and unsigned in C comparisons: -1 < 1u is false.
  • Decoding bytes with the wrong encoding (mojibake like é); always state the encoding.
  • Reversing or slicing strings by bytes or UTF-16 units breaks emoji and combining marks.
  • Writing raw structs to files or the network: padding and byte order differ between machines.

Glossary

  • Bit / byte / word: 1 binary digit / 8 bits / the CPU's natural integer size (64 bits today).
  • Sign extension: copying the sign bit when widening a signed integer.
  • Mantissa (significand): the fraction digits of a floating-point number.
  • Code point: Unicode's number for a character, written U+XXXX.
  • Grapheme cluster: what a reader sees as one character, possibly several code points.
  • Endianness: the order bytes of a multi-byte value are stored in.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Only addition and multiplication overflow." Negation, abs, and MIN_VALUE / -1 overflow too; in C the division kills the process.
"A cast to a smaller type keeps the low part." For integers. For floating point, Java saturates and NaN becomes 0.
"Character.isDigit and [0-9] agree." isDigit accepts hundreds of Unicode digits.
"Rounding is symmetric." Math.round(-2.5) is −2 while Math.round(2.5) is 3.
"A char in an expression is a character." In arithmetic it's promoted to an int code: 'A' + 1 is 66.
"Formatting with the locale's grouping is a one-liner." DecimalFormat can't produce Indian grouping.

07

Computer Architecture

Key ideas

  • Transistors make gates; gates make adders, multiplexers and registers; those make an ALU, a control unit and a register file.
  • Stored-program machines keep instructions and data in the same memory; the program counter drives the fetch–decode–execute cycle.
  • The ISA (x86-64, ARM64, RISC-V) is the contract: instructions, registers, memory model, calling conventions. Microarchitecture is how a particular chip implements it.
  • Pipelining overlaps instruction stages; hazards (data, control, structural) cause stalls. Superscalar out-of-order cores issue several independent instructions per cycle and retire them in order.
  • Branch prediction guesses outcomes; a misprediction flushes the pipeline (about 15–20 cycles). Speculative execution made attacks like Spectre possible.
  • The memory hierarchy (registers, L1, L2, L3, RAM, SSD) trades size for speed; caches exploit temporal and spatial locality, move 64-byte lines, and are kept coherent across cores (MESI-style protocols).
  • False sharing: independent variables on one cache line make cores fight over it.
  • Virtual memory hardware (MMU, page tables, TLB) translates addresses per process (chapter 8).
  • SIMD instructions (SSE/AVX, NEON) operate on several values at once; multicore gives parallelism only to programs that split their work.

Numbers to remember

Event Approximate latency
L1 hit ~1 ns (4–5 cycles)
L2 hit ~4 ns
L3 hit ~10–15 ns
Branch mispredict ~5 ns
RAM access ~80–100 ns
NVMe SSD read ~20–100 µs
Same-region network round trip ~0.5 ms
  • Cache line: 64 bytes on x86 and most ARM (Apple M-series chips report 128 bytes). Page: 4 KB by default (16 KB on Apple silicon).

Pitfalls

  • Traversing memory against its layout (column order in row-major arrays): about 10× slower in this chapter's measurement.
  • Linked structures scattered across the heap defeat prefetching.
  • Unpredictable branches in hot loops; consider branchless code or sorted data.
  • Two threads updating counters in the same cache line (false sharing).
  • Benchmarking without warming caches or repeating runs.

Glossary

  • Clock cycle: one tick; at 3 GHz about 0.33 ns.
  • IPC: instructions per cycle.
  • Register: a tiny, fastest storage slot in the CPU.
  • Cache miss: the requested line isn't in that cache level.
  • TLB: a cache of address translations.
  • RISC / CISC: reduced (simple, fixed-length) vs complex instruction sets.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"An instruction has a fixed cost." It depends on data: subnormals, cache misses and mispredictions change it by 10–100×.
"Division and modulo are cheap." Tens of cycles for a variable divisor; constants and powers of two are rewritten by the compiler.
"volatile makes it thread-safe." It makes reads and writes visible and ordered; count++ is still three steps and still races.
"Parallel is faster." Only with enough work per task and idle cores.
"Faster clock, faster program." Clocks stalled around 2005; performance now comes from width, caches and cores (theoretical gap 4).
"A microbenchmark result is the cost." The JIT may have deleted or folded the code (Gaps 3's 0.03 ns).

08

Operating Systems

Key ideas

  • The OS shares hardware, isolates programs and provides abstractions (processes, threads, files, sockets, virtual memory).
  • Kernel mode vs user mode, enforced by the CPU; programs enter the kernel by system calls, faults and interrupts.
  • A process has an address space, file descriptor table, credentials and at least one thread; Unix creates processes with fork + exec and reaps them with wait (an unreaped child is a zombie).
  • The scheduler time-slices ready threads across cores (Linux: CFS, and from 6.6 EEVDF); states: running, ready, blocked, exited. Context switches cost microseconds plus cache disruption.
  • Threads share memory; races occur when unsynchronised accesses include a write. Tools: mutexes, read-write locks, condition variables, semaphores, atomics, message passing. Deadlock needs mutual exclusion, hold-and-wait, no preemption and circular wait; break any one.
  • Virtual memory: per-process page tables, 4 KB pages, demand paging, copy-on-write after fork, page faults, swapping, memory-mapped files.
  • Filesystems: inodes hold metadata; directories map names to inodes; hard vs symbolic links; journaling for crash consistency; fsync for durability.
  • I/O models: blocking, non-blocking, multiplexed (select/poll/epoll, kqueue), asynchronous (io_uring); the basis of event loops, Go's netpoller and Java virtual threads.
  • Permissions: user/group/other rwx bits, root, capabilities; checks happen inside system calls.

Numbers to remember

  • System call overhead: roughly 50–500 ns depending on the call and mitigations; context switch: about 1–5 µs.
  • Linux default time slice granularity: a few milliseconds.
  • File descriptors 0, 1, 2 = stdin, stdout, stderr; default soft limit often 1,024 open files (ulimit -n).
  • Permission octal: r = 4, w = 2, x = 1 (644 files, 755 directories and executables, 600 secrets).

Pitfalls

  • Reading or writing one byte per system call; buffer instead.
  • Assuming write returned means data is on disk (it's in the page cache until fsync).
  • Forgetting to close descriptors or reap children; leaking threads.
  • Holding a lock while doing I/O or calling unknown code.
  • Taking locks in inconsistent orders (deadlock).
  • Treating kill -9 as a normal shutdown: no cleanup, no flush.

Glossary

  • PID / PPID: process ID / parent's process ID.
  • File descriptor: a small integer naming an open file, pipe or socket in a process.
  • Page fault: an access to a page not currently mapped; the kernel loads or allocates it (or kills the process).
  • Copy-on-write: sharing pages until one side writes, then copying.
  • Signal: an asynchronous notification to a process (SIGINT, SIGTERM, SIGKILL).
  • Critical section: code that must not run in more than one thread at a time.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Virtual threads make blocking free." Pinned in synchronized on JDK 21: back to a pool the size of the core count.
"A file lock protects the file." It protects it from processes that also lock (advisory).
"Two processes appending to a file is safe." Only with O_APPEND, on a local filesystem.
"File errors are IOExceptions." Through mmap, they're InternalErrors (or crashes).
"close() flushes to disk." It flushes Java's buffers to the kernel; the page cache still isn't on disk.
"A POSIX lock belongs to the file descriptor." It belongs to the process: closing any descriptor for the file releases them all.

09

Networking Fundamentals

Key ideas

  • Layering: application (HTTP, DNS), transport (TCP, UDP, QUIC), internet (IP), link (Ethernet, Wi-Fi). Each layer adds a header (encapsulation).
  • IP delivers packets best-effort between addresses; routing forwards by longest-prefix match; CIDR notation (10.0.0.0/8); NAT lets private networks share public addresses; ARP (IPv4) / NDP (IPv6) map IP to MAC on a link.
  • TCP: three-way handshake, sequence numbers and acknowledgements, retransmission, flow control (receive window), congestion control (slow start, CUBIC, BBR), four-way close and TIME_WAIT. It's a byte stream: applications must frame messages.
  • UDP: datagrams, no connection or reliability; QUIC builds reliable, multiplexed, encrypted streams over UDP and underlies HTTP/3.
  • DNS: hierarchical, cached by TTL; record types A, AAAA, CNAME, MX, TXT, NS; resolution via recursive resolvers.
  • TLS 1.3: one round-trip handshake, ephemeral key exchange (forward secrecy), certificates chained to trusted roots, SNI and ALPN.
  • HTTP: methods, status codes, headers, bodies; HTTP/1.1 keep-alive, HTTP/2 multiplexing over one TCP connection, HTTP/3 over QUIC.
  • Sockets: the OS API (socket, bind, listen, accept, connect, send, recv) every language wraps.

Numbers to remember

  • Ethernet MTU 1,500 bytes; minimum IPv4 header 20 bytes, TCP header 20 bytes.
  • Ports: 22 SSH, 53 DNS, 80 HTTP, 443 HTTPS, 5432 PostgreSQL, 6379 Redis; ephemeral range on Linux 32768–60999.
  • Light in fibre: about 200 km per millisecond, so Mumbai to London (~7,200 km) is at least ~36 ms one way, ~72 ms round trip.
  • New HTTPS connection over TCP + TLS 1.3: about 2 round trips before the first request byte (1 with QUIC, 0 with resumption).

Pitfalls

  • Assuming one send equals one recv on TCP.
  • No timeouts on connects and reads: one slow peer hangs your threads.
  • Forgetting DNS caching and TTLs during migrations.
  • Disabling certificate verification "temporarily".
  • Opening a new connection per request instead of pooling (handshake cost, TIME_WAIT buildup).
  • Ignoring Nagle's algorithm and delayed ACK interaction for small request/response protocols.

Glossary

  • MTU: maximum transmission unit, the largest packet a link carries.
  • RTT: round-trip time.
  • Head-of-line blocking: one lost packet stalling everything behind it in the same ordered stream.
  • SNI: the hostname a client sends in the TLS handshake so one IP can serve many sites.
  • Ephemeral port: the temporary local port the OS picks for an outgoing connection.
  • Anycast: one IP address announced from many locations; packets go to the nearest.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Lowering the DNS TTL makes failover fast." Only for clients that honour it; the JVM caches for 30 s, and pools keep old connections.
"The port answers, so the service is healthy." The kernel completes handshakes into the backlog without the program.
"write() succeeded, so they got it." It reached your send buffer; failure shows up on a later call.
"A write error means the request failed." The server may have answered (413, 401) and closed early.
"HTTPS means the server is who I think it is." Only if the hostname is verified against the certificate; raw SSLSockets don't by default.
"Bandwidth decides how fast a transfer is." For one TCP connection over a long path, the window and the round-trip time decide.

10

Compilers & Runtimes

Key ideas

  • Pipeline: lexing (tokens) → parsing (syntax tree) → semantic analysis (names, types) → intermediate representation (IR, often SSA) → optimisation → code generation → assembly → linking.
  • Ahead-of-time compilation (C, C++, Rust, Go, Zig), interpretation (CPython's bytecode loop), JIT (HotSpot, V8), and mixtures (GraalVM native image is AOT Java).
  • Grammars define syntax; recursive descent and Pratt parsing handle precedence; parser generators exist but most production compilers hand-write parsers.
  • Type checking and type inference (local in Java/Go, Hindley-Milner style in ML/Haskell, bidirectional in Rust) happen before code generation.
  • Optimisations: constant folding, inlining, dead-code elimination, common subexpression elimination, loop-invariant motion, vectorisation, escape analysis. Undefined behaviour licenses C/C++ compilers to assume it never happens.
  • Linking: object files with symbols and relocations; static vs dynamic libraries; Java and .NET link lazily at class-load time.
  • Runtimes provide start-up, stacks, threads, exceptions and memory management. Garbage collectors: reference counting (CPython, Swift), tracing mark-sweep/compact, generational collection; concurrent low-pause collectors (Java ZGC, Shenandoah; Go's concurrent mark-sweep). Ownership/RAII frees deterministically without a collector.
  • JITs profile at run time, compile hot methods with speculative assumptions, and deoptimise when assumptions break; hence warm-up in benchmarks.

Numbers to remember

  • HotSpot compiles a method with C1 after a few thousand invocations or loop iterations and with C2 after roughly 10,000+ (tiered compilation; exact thresholds vary by version and flags).
  • Go GC targets: GOGC=100 lets the heap grow to about twice the live set before collecting.
  • ZGC pause times: typically under a millisecond, independent of heap size.

Pitfalls

  • Benchmarking JIT-compiled code without warm-up (use JMH in Java).
  • Relying on undefined behaviour because "it works at -O0".
  • Assuming a GC language can't leak: anything still reachable (caches, listeners, static maps) stays alive.
  • Mixing incompatible library versions at link or class-load time (NoSuchMethodError).
  • Reading optimised assembly without -g or source interleaving and misattributing time.

Glossary

  • Token: the smallest meaningful unit of source text.
  • AST: abstract syntax tree.
  • IR: intermediate representation, the compiler's internal language between source and machine code.
  • SSA: static single assignment, an IR where every variable is assigned exactly once.
  • Symbol / relocation: a named address in an object file / a place the linker must patch.
  • Safepoint: a point where a managed thread can be paused safely, e.g. for GC.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"If the grammar accepts it, the parser handles it." Deep nesting exhausts a recursive parser's stack: bound the depth.
"A regex in Java is compiled once." String.matches, replaceAll and multi-character split compile on every call.
"Operator precedence is common sense." It differs between languages (**, unary minus, & and ==).
"Higher optimisation levels give the same results, faster." Flags that relax floating-point rules change results.
"Interpreted means slow, compiled means fast." A JIT compiles with run-time information and can beat AOT code on hot paths; an AOT binary starts faster.
"Garbage collection means no memory leaks." Anything still referenced is kept; leaks are references you forgot.