RecapsKayavak

Kayavak / Recaps / The Backend

Recaps · Volume 3

The Backend

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

33

Language Foundations

Key ideas

  • Java compiles to bytecode for the JVM; static typing with local inference (var); classes in packages; main as the entry point (compact source files since JDK 25).
  • Primitives vs references: eight primitives hold values; everything else is a reference to a heap object; boxing bridges them (with caching and cost).
  • Numbers: fixed-width two's-complement integers that wrap; IEEE 754 doubles; Math.*Exact; BigDecimal for decimal money; long paise for amounts.
  • Equality: == for primitives and identity; equals/hashCode for value equality, which must be consistent (records generate both).
  • Strings: immutable, UTF-16 internally (compact Latin-1 storage when possible), StringBuilder for building, text blocks and formatted.
  • Data modelling: records for immutable data, enums for closed sets, sealed interfaces plus records for algebraic data types, pattern matching in switch.
  • Behaviour: classes with encapsulated state, interfaces (with default and static methods), lambdas implementing functional interfaces.
  • Errors: checked vs unchecked exceptions, try-with-resources, exception chaining; compared with Go's error values, Rust's Result, C#/Kotlin unchecked-only.
  • Annotations: metadata for compilers, frameworks and tools (retention, targets, processors).

Numbers to remember

  • int ±2.1 billion; long ±9.2 × 10¹⁸; Integer cache −128 to 127.
  • Lab: += in a loop was about 2,700× slower than StringBuilder for 20,000 appends; List<Integer> about 3× slower to sum than int[]; exceptions about 40× cheaper without stack traces.

Pitfalls

  • == on strings and boxed numbers; equals without hashCode.
  • Integer overflow in totals, counters and (int) casts; double for money.
  • String concatenation in loops; hand-built JSON without escaping.
  • Swallowed exceptions (catch (Exception e) {}); exceptions for control flow on hot paths.
  • Mutable fields in objects used as map keys.
  • Platform-default charsets when reading or writing bytes (use UTF-8 explicitly; it's the default since JDK 18).

Glossary

  • Bytecode: the JVM's portable instruction format.
  • Boxing: wrapping a primitive in its object type (int → Integer).
  • Record: a transparent, immutable data class with generated members.
  • Sealed type: a class or interface whose permitted subtypes are listed, enabling exhaustive pattern matching.
  • Checked exception: an exception the compiler requires you to catch or declare.
  • Functional interface: an interface with one abstract method, implementable by a lambda.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"\d and parseInt agree." parseInt reads ١٢٣ as 123; \d doesn't match it.
"Locales only affect currency display." Digits and case mapping change; ß uppercases to two letters.
"Java is pass-by-reference for objects." It passes references by value.
"Integer == works for small numbers, so it's fine." 127 == 127 is true, 128 == 128 false: true false true.
"Math.abs is never negative." Math.abs(Integer.MIN_VALUE) is -2147483648.
"new BigDecimal(0.1) is exact." It's exactly the double: 0.1000000000000000055511…; use BigDecimal.valueOf.
"A linter that finds nothing is wasted." It keeps careful code careful.

34

Object-Oriented Programming and Its Alternatives

Key ideas

  • OOP bundles state with the operations allowed to change it; the goal is protecting invariants and managing change in large codebases.
  • Encapsulation (private state, intention-revealing methods, defensive copies), abstraction (interfaces as capabilities), polymorphism (dynamic dispatch), inheritance (use sparingly, design for it or forbid it).
  • Composition over inheritance; delegation; small interfaces; dependency on abstractions.
  • Liskov substitution: subtypes must keep their parents' promises (preconditions no stronger, postconditions no weaker, invariants preserved).
  • Expression problem: interfaces make new kinds easy; sealed types plus pattern matching make new operations easy (with exhaustiveness checks); visitors and type classes are other answers.
  • Dispatch: single dispatch in Java/C#; multiple dispatch (Julia, CLOS); traits and type classes (Rust, Haskell); structural interfaces (Go, TypeScript).
  • Values vs entities: immutable value objects compared by value; entities with identity; records for values.
  • Other paradigms: procedural, functional (data + functions, immutability), actor model (Erlang/Akka), data-oriented design.

Numbers to remember

  • Lab: the HashSet subclass counted 6 for 3 additions; a mutated key made a map entry unreachable (size 1, lookups null); a Square produced area 16 instead of 20.

Pitfalls

  • Inheriting for code reuse; deep hierarchies; non-final classes not designed for extension.
  • Getters returning internal mutable collections; setters for everything (anaemic models).
  • Mutable fields in equals/hashCode; equals without hashCode.
  • instanceof chains where polymorphism or sealed switches belong.
  • God classes and "Manager"/"Util" classes with no cohesive responsibility.

Glossary

  • Invariant: a condition on an object's state that always holds.
  • Dynamic dispatch: selecting a method implementation by the receiver's runtime class.
  • Sealed type: a type whose permitted subtypes are fixed and known to the compiler.
  • LSP: the Liskov substitution principle.
  • Value object: an immutable object defined by its attributes.
  • Delegation: forwarding a call to a contained object.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Sealed types tell you every place to change." Only switches in the same compilation; strings, tests and contracts aren't checked.
"Records are immutable." Shallowly: a mutable component can change and move the hash.
"Record equals is field-by-field ==." Doubles compare like Double.compare: NaN equals NaN, 0.0 differs from -0.0.
"Refactoring is safe if the tests pass." Tests check what they assert; a golden master checks everything it recorded.
"Inheritance is for reuse." Composition reuses without the fragile base class; inherit for substitutability.
"OOP and pattern matching are rival styles." Most systems need both: data for closed domains, interfaces at open boundaries.
"A failing test after a valid change means the change is wrong." Sometimes the test encoded an assumption, not the rule.

35

Collections

Key ideas

  • Four shapes: List (ordered, indexed), Set (unique), Map (key → value), Queue/Deque (FIFO, both ends). Declare by interface.
  • ArrayList: a growable array (grows by 1.5×), O(1) get, amortised O(1) append, O(n) middle insert done by fast array copies. LinkedList rarely wins.
  • HashMap: an array of bins indexed by spread hash bits; load factor 0.75 triggers a doubling resize; bins with 8+ entries become red-black trees (when the table has 64+ bins).
  • LinkedHashMap keeps insertion (or access) order and makes an LRU cache with removeEldestEntry; TreeMap is a red-black tree with sorted keys and range queries (headMap, ceilingKey); PriorityQueue is a binary heap; EnumMap/EnumSet are arrays/bit sets.
  • equals/hashCode contract: equal objects, equal hashes; key fields immutable. Comparable is natural order; Comparator is any order, composed with comparing/thenComparing; must be consistent with equals for sorted sets.
  • Iteration: fail-fast iterators throw ConcurrentModificationException on structural change; use removeIf or Iterator.remove.
  • Immutability: List.of/copyOf are immutable copies (no nulls); Collections.unmodifiable* are read-only views; JDK 21 added SequencedCollection (getFirst, reversed).
  • Concurrent: ConcurrentHashMap (per-bin locking, compute/merge atomic per key), CopyOnWriteArrayList for read-mostly lists, BlockingQueues for producer/consumer, ConcurrentSkipListMap for sorted.
  • Other languages: Go slices and maps (randomised iteration order), Rust Vec/HashMap (SipHash by default)/BTreeMap, C++ vector/unordered_map/map, C# List<T>/Dictionary, Python list/dict (insertion ordered), persistent collections in Clojure, Scala and Haskell.

Numbers to remember

  • HashMap default capacity 16, load factor 0.75, treeify threshold 8.
  • Lab: LinkedList.get about 1,500× slower than ArrayList, and slower even at middle inserts; list contains about 1,700× slower than HashSet on 200k elements; a shared HashMap lost 28,064 of 800,000 entries.

Pitfalls

  • contains/linear search inside loops (accidental O(n²)).
  • Mutable or inconsistent keys; hashCode missing or using mutable fields.
  • Modifying a collection while iterating it.
  • Sharing non-thread-safe collections across threads; check-then-act on ConcurrentHashMap (if (!containsKey) put) instead of computeIfAbsent.
  • Returning internal collections, or unmodifiable views when a snapshot was needed.
  • Relying on HashMap iteration order; boxing overhead for large numeric collections.

Glossary

  • Bucket/bin: one slot of a hash table's array.
  • Load factor: entries per bin that triggers a resize.
  • Fail-fast iterator: one that throws on concurrent structural modification.
  • Amortised O(1): constant on average over many operations, despite occasional expensive ones (resizes).
  • Persistent collection: an immutable collection whose "modifications" return new versions sharing structure.
  • View: a collection backed by another, reflecting its changes.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Removing in a for-each always throws." Removing the second-to-last element ends the loop silently, skipping the last.
"Immutable collections keep the order I put things in." List.of does; Set.of and Map.copyOf randomise per run.
"PriorityQueue operations are O(log n)." Only at the head; remove(Object) and contains are O(n).
"unmodifiableList makes a list immutable." It's a read-only view of a list that can still change.
"List.copyOf always allocates." Not for an already-immutable list.
"A TreeSet uses equals." It uses the comparator: compare = 0 means duplicate.
"ConcurrentHashMap makes my code thread-safe." Each call is atomic; get-then-put isn't.

36

Generics and Type Parameters

Key ideas

  • Generics move type errors from run time to compile time and remove casts: type parameters on classes, interfaces and methods; inference and the diamond.
  • Bounds (T extends Comparable<? super T>, intersection bounds T extends A & B) grant operations on T.
  • Variance: Java generics are invariant; use-site wildcards (? extends to read, ? super to write: PECS); ? alone for "any". Kotlin and C# use declaration-site out/in; Scala +T/-T; arrays are covariant and checked at run time.
  • Erasure: type arguments are removed; casts inserted at use sites; bridge methods preserve overriding; declarations keep generic signatures readable by reflection (type tokens).
  • Consequences: no new T(), new T[], instanceof List<String>, primitives as type arguments (until Valhalla), or overloads differing only by type arguments.
  • Implementations elsewhere: C# reified generics, specialised for value types; C++ templates and Rust generics monomorphise; Go uses GC-shape stenciling with dictionaries; Haskell type classes and higher-kinded types; TypeScript's structural generics are erased entirely.

Numbers to remember

  • Lab: Go's generic sum was about 5× faster than interface dispatch and about 2.7× faster than []any.

Pitfalls

  • Raw types and ignored unchecked warnings (heap pollution surfacing far away).
  • @SuppressWarnings("unchecked") on whole classes.
  • Wildcards in return types (forces callers to deal with them); overly clever bounds that break inference.
  • Generic arrays and varargs of generic types (@SafeVarargs only when you don't store or expose the array).
  • Expecting List<Integer> to be a List<Number>.

Glossary

  • Type parameter / argument: T in the declaration / String at the use.
  • Invariance / covariance / contravariance: no subtyping between G<A> and G<B> / follows A <: B / reverses it.
  • Erasure: compiling generics away, leaving bounds (or Object).
  • Reification: keeping type arguments at run time.
  • Heap pollution: a variable of a parameterised type referring to an object of a different parameterisation.
  • Bridge method: a compiler-generated method that keeps overriding working after erasure.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Generics check types at run time." Only the compiler checks; at run time a Tag<String> is a Tag.
"An unchecked warning is noise." It marks the exact place the compile-time promise stops holding.
"Inference errors are unreadable." They list each overload's constraints; read the one you meant.
"A sealed switch must list every subtype." Not subtypes the type argument rules out.
"List<Object> accepts any list." Generics are invariant; List<?> or List<? extends Object> does.
"Typed keys make a container safe." Only if names (or numbers) are unique per type.
"Generics cost nothing in Java." No code cost, but boxing for primitives and a cast at each use.

37

Functional Programming

Key ideas

  • First principles: functions as values, higher-order functions, pure functions, immutability, referential transparency, composition; effects pushed to the edges ("functional core, imperative shell").
  • Java: lambdas implement functional interfaces (Function, Predicate, Supplier, Consumer, UnaryOperator, BiFunction, primitive specialisations); method references (static, bound, unbound, constructor); captured variables must be effectively final.
  • Streams: source → lazy intermediate operations → terminal operation; stateless (map, filter) vs stateful (sorted, distinct); short-circuiting (findFirst, anyMatch, limit); flatMap, takeWhile, mapMulti, Stream.toList() (JDK 16), gatherers (Stream.gather, final in JDK 24) for custom intermediate operations.
  • Collectors: toList, toMap (with merge function), groupingBy (with downstream collectors), partitioningBy, joining, teeing.
  • Optional: a return type for absence; map/flatMap/orElse/orElseGet/orElseThrow.
  • Parallel streams: fork-join common pool; require pure functions and splittable sources; pay off only for large CPU-bound work.
  • Elsewhere: Haskell (purity, laziness, type classes, monads for effects), Scala and Kotlin collections, Clojure's persistent data and transducers, Rust iterators (zero-cost), F#/OCaml pipelines, JavaScript array methods (eager).

Numbers to remember

  • Lab: parallel forEach into an ArrayList lost about 27% of 1M elements; Stream<Integer> about 90× slower than IntStream; parallel was slower for 1,000 cheap items and 2.0× faster on 2 cores for heavy work.

Pitfalls

  • Side effects in map/filter/peek; mutating shared state from parallel streams.
  • Boxed streams for numeric work; reduce into int overflowing.
  • parallel() in request handlers on a shared pool; parallel over LinkedList or iterate.
  • Optional.get() without checking; Optional fields and parameters; orElse(expensiveCall()) instead of orElseGet.
  • toMap throwing on duplicate keys; stream pipelines so long they're harder to read than a loop.

Glossary

  • Higher-order function: one that takes or returns functions.
  • Referential transparency: an expression can be replaced by its value without changing behaviour.
  • Lazy evaluation: computing only when, and as much as, needed.
  • Short-circuiting: stopping early once the result is known.
  • Collector: a mutable reduction (supplier, accumulator, combiner, finisher).
  • Gatherer: a user-defined intermediate stream operation (JDK 24).

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"No mutation means pure." Reading the clock, a static or a system property is a hidden input.
"Optional is a monad, so chains can be regrouped." Not when a mapped function returns null.
"A stream is a snapshot of its source." Most sources bind when the terminal operation starts.
"A ConcurrentModificationException stops the pipeline before damage." ArrayList's forEach checks once, at the end: every element was processed.
"this::m is a value; equal values are equal." Each evaluation may be a new object, and there's no equals.
"Parallel streams make pure code faster." Only for large, CPU-bound, splittable work.
"Side effects in map run once per element." They run when, whether and as often as the terminal operation pulls.

38

Concurrency

Key ideas

  • Concurrency vs parallelism; threads share the heap; the hazards are races, visibility, ordering, deadlock, livelock, starvation.
  • Java memory model: happens-before from locks, volatile, final fields, Thread.start/join, executors and concurrent collections; safe publication; double-checked locking needs volatile.
  • Primitives: synchronized (reentrant monitor), ReentrantLock/ReadWriteLock/StampedLock, atomics and LongAdder, Semaphore, CountDownLatch, CyclicBarrier, Phaser, BlockingQueues.
  • Executors: fixed/cached/scheduled pools, ForkJoinPool (work stealing), virtual-thread-per-task; Future, CompletableFuture composition, timeouts and cancellation (interruption).
  • Virtual threads (JDK 21): cheap, JVM-scheduled; for blocking I/O; pinning in synchronized fixed by JEP 491 (JDK 24); limit downstream concurrency with semaphores.
  • Structured concurrency (StructuredTaskScope, preview) and scoped values (final in JDK 25) for request-scoped data.
  • Other models: Go goroutines and channels, Erlang/Elixir actors, Rust ownership (Send/Sync) and async, C#/JS/Kotlin async-await and coroutines, the reactive model (Reactor).

Numbers to remember

  • Lab: a plain-field stop flag never stopped; 10,000 × 100 ms waits took 5,289 ms on 200 platform threads vs 158 ms on virtual threads; pinning: 2,581 ms on JDK 21 vs 149 ms on JDK 25; check-then-act built a cached value 8 times instead of 1.
  • Platform thread stack about 1 MB reserved by default; a virtual thread starts at a few hundred bytes.

Pitfalls

  • Shared mutable state without a lock or atomic; compound check-then-act operations.
  • Missing volatile on flags; publishing objects before construction finishes.
  • Nested locks in inconsistent order; holding locks during I/O or callbacks.
  • Swallowing InterruptedException (restore the interrupt flag).
  • Unbounded queues and pools; virtual threads overwhelming a connection pool; ThreadLocal caches multiplied by millions of virtual threads.
  • parallelStream and CompletableFuture.supplyAsync without an executor, sharing the common pool.

Glossary

  • Race condition: correctness depends on timing.
  • Happens-before: the JMM ordering that guarantees visibility.
  • CAS: compare-and-swap, an atomic hardware instruction.
  • Carrier thread: an OS thread running virtual threads.
  • Pinning: a virtual thread unable to unmount from its carrier while blocked.
  • Work stealing: idle threads take tasks from busy threads' queues.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Inject a Clock for everything time-related." Business time from a Clock; deadlines from nanoTime.
"nanoTime values can be compared with <." Compare differences; the counter can wrap.
"The JVM will tell me about a deadlock." Not among virtual threads, on JDK 21.
"A stress test that passes means the code is safe." Only if it can fail; check invariants.
"ReentrantLock serves threads in order." Only new ReentrantLock(true), at a large cost.
"Virtual threads remove the need for locks." They change the cost of blocking, not data races.
"cancel(true) stops a CompletableFuture's work." It doesn't interrupt the task.

39

Modern Java Through JDK 27

Key ideas

  • Cadence: a release every March and September; LTS every two years (8, 11, 17, 21, 25; next 29); features go through JEPs, previews (--enable-preview) and incubator modules before becoming final.
  • Language, by release: lambdas and streams (8); var (10); switch expressions (14); text blocks (15); records and pattern instanceof (16); sealed types (17); pattern switch and record patterns (21); unnamed variables _ (22); flexible constructor bodies, module imports, compact source files with instance main (25); primitive patterns in preview.
  • Libraries: HttpClient (11), sequenced collections (21), virtual threads (21), FFM API for native code (22), stream gatherers (24), scoped values (25), structured concurrency (preview), class-file API (24).
  • Withdrawn: string templates (previewed in 21–22, withdrawn in 23, redesign pending).
  • Runtime: G1 default, ZGC generational-only, Shenandoah generational; compact object headers (product in 25, default in 27); Leyden AOT cache (24+); Unsafe memory access deprecation; Security Manager permanently disabled (24); 32-bit x86 port removed.
  • Compatibility: --release; class file version = JDK + 44; upgrade runtime first; jdeps for internal-API use; strong encapsulation of JDK internals since 17.
  • Comparisons: C# (yearly, aggressive language evolution), Kotlin (features first, Java later), Go (1.x compatibility promise, generics in 1.18), Rust (editions), C++ (three-year standards), Python (yearly, deprecation cycles).

Numbers to remember

  • Class file versions: 52 = 8, 55 = 11, 61 = 17, 65 = 21, 69 = 25, 71 = 27.
  • Lab: a two-int record took 24 bytes, 16 with compact headers; AOT cache cut a small app's startup about 15%.

Pitfalls

  • -source/-target without --release (runtime NoSuchMethodError on old JDKs).
  • Deploying classes compiled for a newer JDK than the runtime.
  • Preview features in production code; relying on sun.misc.Unsafe or reflective access to JDK internals.
  • Sealing published library types that clients switch over (adding a subtype breaks them).
  • Upgrading compile target and runtime in one step across many services.

Glossary

  • JEP: JDK Enhancement Proposal.
  • LTS: long-term support release.
  • Preview feature: complete but not final; may change or be removed.
  • Record pattern: a pattern that deconstructs a record into its components.
  • AOT cache: an archive of loaded and linked classes (and profiles) produced by a training run.
  • Compact object headers: 8-byte object headers (Project Lilliput).

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"--release 21 makes any newer JDK build my code the same way." Same API; different lints and different class files.
"-Xlint:all -Werror is a fixed standard." It grows with each compiler.
"A version constant in the code is the version." Only if someone remembers to change it.
"Heap used shows memory savings." Only after a full GC; otherwise it shows GC timing.
"Adding a method to an interface is always compatible." Sources can clash (getFirst).
"Preview features are safe once they compile." They can change or be withdrawn next release.
"Upgrading the JDK means rewriting code." Most gains come with no code change.

40

JVM Internals and Other Runtimes

Key ideas

  • Runtimes spectrum: native AOT (C, Rust, Go, Zig), managed VMs with JIT (JVM, .NET, V8), interpreters (CPython); the JVM can also AOT-compile (GraalVM native-image) or cache startup work (Leyden).
  • Bytecode: a typed stack machine; invokestatic/virtual/interface/special/dynamic; invokedynamic underpins lambdas and string concatenation.
  • Class loading: load → verify → prepare → resolve → initialise (lazily, on first active use); loader delegation (bootstrap, platform, application); class identity is name plus loader.
  • Runtime areas: heap, per-thread stacks, metaspace (class metadata, native memory), code cache.
  • Execution: interpreter, tiered C1/C2 (or Graal JIT), on-stack replacement, profile-guided inlining, escape analysis, deoptimisation when assumptions break, safepoints for GC and deopt.
  • GC: tracing from roots; generational hypothesis; mark-sweep, mark-compact, copying; card tables and write barriers; Serial, Parallel, G1 (regions, pause target, default), ZGC (concurrent, coloured pointers, generational only since 23), Shenandoah, Epsilon (no-op).
  • Elsewhere: Go's concurrent non-moving GC, .NET generations, V8's Orinoco, CPython reference counting, Rust/C++ RAII, Swift ARC.

Numbers to remember

  • Lab: interpreter 35× slower than C2 code; C1-only plateau about 75% slower than C2; megamorphic call site 9× slower than monomorphic; GC max pauses on one workload: Serial 44 ms, Parallel 20 ms, G1 7 ms, ZGC 0.06 ms.
  • G1 default pause target 200 ms; default max heap 1/4 of physical (or container) memory.

Pitfalls

  • Benchmarking without warm-up; judging performance from the first requests after deploy.
  • Default heap sizing in containers without checking MaxRAMPercentage; untouched heap pages faulting during early GCs.
  • Classloader leaks in app servers and hot reload (metaspace growth).
  • Huge numbers of loaded classes and proxies slowing startup.
  • Choosing a GC by reputation instead of by the latency or throughput objective and measurement.

Glossary

  • JIT: just-in-time compilation during execution.
  • OSR: on-stack replacement, switching a running loop to compiled code.
  • Deoptimisation: discarding compiled code whose assumptions became false.
  • Safepoint: a point where all threads can be paused consistently.
  • Megamorphic: a call site that has seen more than two receiver types.
  • Write barrier: code run on reference stores so the GC can track changes.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"When main throws, the program exits." Not while a non-daemon thread runs.
"The GC will close what a failed constructor opened." Maybe, someday; locks and descriptors stay until then.
"Checking source catches every call." Method references and code without source need the class files.
"A class's constant pool shows what it calls at run time." It shows what it names.
"Ready means fast." The first requests run interpreted and load classes.
"A shutdown hook can report failure with System.exit." That hangs the JVM; use halt.
"Changing a library constant updates its users." Constants are inlined at compile time.

41

Memory and Performance

Key ideas

  • Method: goal (latency percentile, throughput, memory budget) → measure → hypothesis → one change → measure; check I/O and external calls first; use the USE and RED methods for systems (Volume 9).
  • Object layout: 12-byte header (8 with compact headers), compressed 4-byte references under 32 GB heaps, 8-byte alignment; boxing and wrapper objects; collection overheads (HashMap.Node 32 bytes).
  • Allocation: TLAB bump-pointer allocation; escape analysis and scalar replacement; cheap young collection; avoid object pools for small objects.
  • Hardware: cache lines (64 B), prefetching, locality, branch prediction, false sharing (@Contended), NUMA; data-oriented layout (structure of arrays).
  • Strings: compact strings (Latin-1), deduplication (G1), interning cautions.
  • Measuring: JMH (forks, warm-up, Blackhole, modes), JFR and Mission Control, async-profiler flame graphs (CPU, allocation, lock, wall-clock), heap histograms and dumps (MAT), GC logs.
  • Tuning: heap sizing in containers (MaxRAMPercentage), GC choice by objective, -XX:+AlwaysPreTouch, AOT cache for startup, connection pools and thread pools sized from Little's law.

Numbers to remember

  • Lab: column-order traversal 17× slower; array of scattered objects 14× slower than double[]; escape analysis removed 60 GCs; an unused computation measured 0.0 ms.
  • Memory per element: int[] 4 B, List<Integer> about 20 B, HashMap<Integer,Integer> about 70 B.
  • Main-memory access about 100 ns vs L1 about 1 ns.

Pitfalls

  • Optimising without a goal or profile; micro-optimising code that isn't on the hot path.
  • Hand-rolled benchmarks (dead code, no warm-up, single run).
  • Boxed collections for large numeric data; huge object graphs as caches.
  • Memory leaks through static collections, listeners, ThreadLocals and unbounded caches.
  • Profiling an idle service, or only in development.

Glossary

  • TLAB: thread-local allocation buffer.
  • Scalar replacement: replacing a non-escaping object with its fields in registers.
  • False sharing: threads contending on one cache line through different variables.
  • Flame graph: stacked visualisation of sampled call stacks.
  • Heap dump: a snapshot of every object on the heap.
  • Little's law: concurrency = throughput × latency.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"A cache that grows with the data isn't a leak." It can still keep far more than it needs, and serve stale answers.
"Immutable objects make caching safe." Safe to share, but a cached version is still an old version.
"The allocation profile shows what's slow." It shows what allocates; a scan that allocates nothing is invisible to it.
"Bytes per object at a small size predict the large size." Fixed costs dominate small runs.
"420 samples is a big sample." Not when ten of them carry 81% of the weight.
"Two profiles that disagree mean the code changed." Not necessarily: the same build can rank differently.
"String replacement is cheap." On a whole page it copies the page each time, and changes what you didn't mean to.
"A regex that runs once a request is fine." It's compiled once a request too.

42

Modules, Packaging and Dependency Conflicts

Key ideas

  • Artifacts: JARs (classes, resources, manifest), coordinates (group:artifact:version), sources and javadoc JARs, WARs, repositories (Maven Central).
  • Finding classes: class loader delegation (bootstrap → platform → application); classpath order (first wins); module path with readability and exports; service loading (META-INF/services, provides/uses).
  • Executable JARs: Main-Class, Class-Path; fat/uber JARs (assembled or Spring Boot's nested-JAR loader); layered JARs for container caching.
  • Dependency conflicts: transitive dependencies; Maven nearest-wins vs Gradle highest-wins; BOMs and platforms for alignment; exclusions; dependency locking; duplicate classes; relocation (shading); class loader isolation.
  • Errors to recognise: NoClassDefFoundError, ClassNotFoundException, NoSuchMethodError, NoSuchFieldError, AbstractMethodError, IncompatibleClassChangeError, LinkageError, ClassCastException between same-named classes.
  • JPMS: module-info (requires, exports, opens, provides, uses), strong encapsulation of JDK internals, --add-exports/--add-opens, automatic modules, jdeps, jlink.
  • Across languages: Go modules (minimal version selection, static binaries), Cargo (semver, lock files, multiple major versions coexisting), npm (nested node_modules, lock files), Python wheels and virtual environments, .NET NuGet (nearest wins), C/C++ (package managers like vcpkg and Conan, ABI concerns).

Numbers to remember

  • Lab: a jlinked runtime for a small app was 52 MB vs 286 MB for the full JDK.

Pitfalls

  • Trusting that the compile classpath equals the run-time classpath.
  • Ignoring duplicate classes and same-library-different-coordinates (javax vs jakarta).
  • Fat JARs that merge META-INF/services files incorrectly (lost service registrations).
  • Shading without relocating reflection strings and resources; unpatched shaded copies.
  • Depending on JDK internals; upgrading the JDK without running jdeps --jdk-internals.
  • Version ranges and unlocked dependencies producing different builds from the same source.

Glossary

  • Transitive dependency: a dependency of a dependency.
  • BOM: bill of materials, a curated set of aligned versions.
  • Shading/relocation: copying a dependency into your artifact under a renamed package.
  • Split package: one package spread over two modules or JARs.
  • Automatic module: a plain JAR on the module path, named from its manifest or file name.
  • Minimal version selection: Go's rule of using the lowest version that satisfies all requirements.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Fixed timestamps make a JAR reproducible." Only with the same compiler; JDK 25 changed 13 of 106 classes.
"--release 21 gives the same class files on any JDK." It fixes the API and class file version, not the bytes.
"A jlink image is the JDK, smaller." It drops the CDS archive unless asked, and every module you didn't list.
"module-info makes my internals private." Only for users who put you on the module path.
"Binary compatible means users can upgrade without changes." Until they recompile, or reflect over your record.
"Changing a method's return type is safe if callers ignore it." The descriptor changes, so old callers fail with NoSuchMethodError.
"jdeps lists every module the service needs." Not the ones only operations use, like jdk.jfr.

43

Build Systems

Key ideas

  • Jobs: resolve dependencies, compile, test, package, publish; do the minimum work; be reproducible.
  • Maven: POM, coordinates, scopes (compile, provided, runtime, test), the default life cycle (validate … compile … test … package … verify … install … deploy) with plugins bound to phases, parent POMs, BOMs and dependencyManagement, nearest-wins resolution, reactor multi-module builds, wrapper.
  • Gradle: tasks in a directed acyclic graph, configurations (implementation, api, compileOnly, runtimeOnly, testImplementation), highest-wins resolution with constraints and platforms, version catalogs, convention plugins, incremental compilation with ABI tracking, build cache, configuration cache, daemon, build scans, toolchains.
  • Correctness: hermetic tasks, declared inputs and outputs, constant inlining, clean CI builds, dependency locking and verification (checksums, signatures).
  • Reproducibility: fixed timestamps and file order, pinned tools and dependencies.
  • Other ecosystems: go build (content-addressed cache), Cargo (crates, features, workspaces, lock file), npm/pnpm and Vite, Python uv/Poetry, .NET dotnet build/MSBuild, CMake/Ninja, Bazel/Buck2/Pants for monorepos.

Numbers to remember

  • Lab: 400-class clean compile 5.6 s; no-change 1.1 s (UP-TO-DATE); one-method edit recompiled 3 classes in 0.1 s; build cache turned a clean build into FROM-CACHE; Go no-change build 61 ms.

Pitfalls

  • Building outside the wrapper; unpinned plugin and dependency versions.
  • Undeclared task inputs (environment, time, files read by scripts) breaking caching.
  • api instead of implementation everywhere (leaking dependencies, recompiling everything).
  • Public constants changed in libraries without rebuilding dependents.
  • Treating a green incremental local build as proof; not running a clean CI build.
  • Build logic copy-pasted across projects instead of convention plugins or parent POMs.

Glossary

  • Life cycle phase: a named step in Maven's build (compile, test, package).
  • Configuration (Gradle): a named set of dependencies for a purpose.
  • ABI: the public signatures other code compiles against.
  • Hermetic build: one whose outputs depend only on declared inputs.
  • Build cache: stored task outputs keyed by input hashes.
  • BOM / platform: an aligned set of versions applied to many dependencies.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Gradle always runs the tests when something changed." Only when something it knows about changed.
"A system property pointing at a file makes the file an input." Only the path is. Declare the file.
"Compiler arguments are just strings." Paths in them are inputs; Gradle refuses the ones it can't track.
"A new lint rule is a cheap change." It changes every compile task's inputs.
"Content hashing needs nothing from the outputs." It needs them reproducible, or every rebuild cascades.
"If it compiles, the API didn't change." Record components and new members change it; only a recorded API shows that.
"A method body edit recompiles the callers." Not with compile avoidance; only ABI changes do.
"A cached result is always right." Only if every input was declared.

44

Backend Fundamentals

Key ideas

  • Shape: listener → middleware chain → router → controller → service → repository → database/other services; the same in Spring, ASP.NET Core, Express/Fastify, Django/FastAPI, Gin/Echo, Axum, Phoenix.
  • Request handling models: thread per request (now virtual threads), event loop (Node, Netty/WebFlux, Vert.x), goroutines, BEAM processes, async/await runtimes (Tokio, .NET).
  • Middleware: request ids, logging, timing, authentication, CORS, compression, rate limiting, error mapping; ordering matters.
  • Dependency injection: wire objects from the outside; constructors; scopes.
  • Serialisation and validation: JSON mapping (Jackson), bean validation, all errors at once, size limits, unknown-field policy.
  • Layering: thin controllers, services with rules and transactions, repositories hiding storage; hexagonal/ports-and-adapters as the generalisation (Volume 13).
  • Configuration: environment variables and profiles, secrets from a vault, validated at startup.
  • Errors: domain exceptions mapped centrally to status codes; Problem Details (RFC 9457); never leak internals; log with request ids.
  • Lifecycle: health (liveness, readiness), graceful shutdown, startup checks.

Numbers to remember

  • Lab: 8 threads × 100 ms waits = 78 req/s (Little's law); a virtual thread per request served 400 concurrent requests in about 320 ms; no timeout means waiting forever; stop(0) failed an in-flight request, stop(5) completed it.
  • Tomcat's default max threads: 200. Kubernetes' default termination grace period: 30 s.

Pitfalls

  • Business logic in controllers; HTTP types in services.
  • Unbounded request bodies, lists and page sizes.
  • No timeouts on outbound calls; pools sized without Little's law.
  • Different error shapes per endpoint; stack traces in responses.
  • Logs without request ids or structure; logging secrets or personal data.
  • Hard shutdowns during deploys.

Glossary

  • Controller/handler: maps HTTP requests to application calls.
  • Service: application logic and rules.
  • Repository: storage abstraction for one kind of entity.
  • Middleware/filter: code wrapped around every request.
  • Problem Details: the RFC 9457 error format.
  • Graceful shutdown: stop accepting work, finish in-flight work, then exit.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Graceful shutdown waits for requests in flight." It may also wait for idle connections, unless it closes them.
"Slow tests are slow code." Here they were five times slower because of a shutdown wait.
"Asynchronous logging is always faster." Only against a slow destination; a contended queue can cost more than it saves.
"An async appender never loses logs." Full queues drop (or block); know which, and count it.
"The MDC follows the request." Not across threads; an inheritable one can name the wrong request.
"The top of the stack trace is where it failed." Not for wrapped exceptions from other threads.
"Middleware order doesn't matter." It decides what the request id, logging and error mapping can see.

45

HTTP API Design

Key ideas

  • Resources: nouns, plural collections, stable ids, sub-resources for ownership, actions modelled as resources (/orders/42/cancellation) when they don't fit CRUD.
  • Semantics: safe (GET, HEAD) vs idempotent (PUT, DELETE) vs neither (POST, PATCH by default); status codes with their real meanings; Location, Allow, Retry-After; Problem Details for errors.
  • Collections: pagination (cursor/keyset preferred, offset for small admin lists), capped limits, filtering and sorting parameters, sparse fieldsets, include expansions, batch lookups.
  • Concurrency and retries: ETags with If-None-Match (caching) and If-Match (optimistic concurrency, 412/428); idempotency keys for creates; retry with backoff on 429/503.
  • Evolution: additive changes, tolerant readers, versioning in the path, header or media type; deprecation (Deprecation and Sunset headers) and migration windows; OpenAPI as the contract, with breaking-change checks in CI.
  • Beyond REST: GraphQL (client-shaped queries, N+1 resolvers, caching harder), gRPC (Protobuf, HTTP/2, streaming, deadlines; internal services), webhooks (signed, retried, idempotent receivers), async APIs (events, AsyncAPI), JSON:API and HAL conventions.

Numbers to remember

  • Lab: page 50,000 cost 107 ms with OFFSET vs 0.24 ms with keyset; 50 sequential calls over 40 ms RTT took 2.3 s vs 50 ms batched; JSON gzipped 94% smaller; Nagle plus delayed ACK added about 45 ms per request.

Pitfalls

  • Verbs in URLs, RPC disguised as REST, 200 with an error body.
  • Unbounded lists; OFFSET pagination for feeds, syncs and exports.
  • No idempotency for payments and order creation; retrying non-idempotent calls blindly.
  • Last-write-wins updates without versions.
  • Breaking changes without a new version or deprecation period; leaking database schema into the API.
  • Chatty APIs designed per table rather than per client use case.

Glossary

  • Idempotent: repeating the request has the same effect as doing it once.
  • ETag: an opaque version identifier for a representation.
  • Keyset pagination: paging by the last seen sort key instead of a row offset.
  • Idempotency key: a client-generated id that lets the server deduplicate retries.
  • Tolerant reader: a client that ignores fields it doesn't understand.
  • OpenAPI: a standard description format for HTTP APIs.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Every client speaks HTTP/1.1." A default nginx speaks HTTP/1.0 to its upstream.
"Responses without caching headers aren't cached." Shared caches apply their own defaults.
"no-cache means don't cache." It means revalidate; nginx won't store it at all.
"max-age=0 stops everything from caching." s-maxage overrides it for shared caches.
"Removing an optional field is safe." Readers that used it when present lose it.
"Adding an enum value is compatible." Only for clients that tolerate unknown values.
"A 304 is free." It still costs a round trip to the origin.

46

Spring Core

Key ideas

  • IoC and DI: the framework calls your code and supplies dependencies; constructor injection preferred; depend on interfaces.
  • Container: ApplicationContext (BeanFactory plus events, resources, environment, i18n); bean definitions vs instances; BeanFactoryPostProcessor, BeanPostProcessor, BeanRegistrar (Spring 7); configuration by component scanning, @Configuration/@Bean, or functional registration.
  • Resolution: by type, then @Primary, @Qualifier, parameter name; List/Map of all candidates; ObjectProvider for optional and lazy lookups; fail fast on ambiguity.
  • Lifecycle: instantiate → inject → aware callbacks → @PostConstruct → post-processors (proxies created here) → ready → @PreDestroy; SmartLifecycle for start/stop ordering.
  • Scopes: singleton (default), prototype, request, session, application, websocket; scoped proxies.
  • Environment: property sources, profiles, @Value placeholders, @ConfigurationProperties (chapter 47); application events (@EventListener, @TransactionalEventListener).
  • AOP: advice, pointcuts, join points; Spring AOP is proxy-based (JDK dynamic proxies for interfaces, CGLIB subclasses for classes); powers @Transactional, @Cacheable, @Async, @PreAuthorize, @Retryable, @ConcurrencyLimit; AspectJ weaving for full AOP.
  • Elsewhere: ASP.NET Core DI (transient/scoped/singleton), Guice, Dagger (compile time), Micronaut and Quarkus (build-time DI), NestJS, Go Wire/Fx, Python dependency-injector, FastAPI Depends.

Numbers to remember

  • Lab: a cached method ran once for three external calls but twice for two self-calls; 1,000 beans took about 2.2 s to refresh (about 2 ms per bean).

Pitfalls

  • Self-invocation of proxied methods; annotations on private or final methods; final classes.
  • Reading fields through proxies.
  • Prototype or request-scoped beans injected into singletons.
  • Mutable state in singleton beans.
  • Field injection hiding dependencies; circular dependencies.
  • Overusing component scanning across huge packages (slow startup, surprise beans).

Glossary

  • Bean definition: metadata describing how to create a bean.
  • Post-processor: a hook that modifies definitions or instances.
  • Proxy: an object standing in for a bean to add behaviour.
  • Advice / pointcut: the extra behaviour / where it applies.
  • Profile: a named set of beans and properties for an environment.
  • Scoped proxy: a proxy that looks up the right scoped instance on each call.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"A bad setting fails at startup." Only if its type refuses bad values; TimeZone turns them into GMT.
"IST is India Standard Time." In Java's TimeZone; elsewhere it's also Israel and Ireland. Use regions.
"A constant isn't a dependency." If it can differ between deployments or tests, it is.
"DI needs a container." A composition root does the same job by hand.
"Spring tells you where a property came from." Spring Boot does; the core resolver only logs it at debug level.
"Every day has 24 hours." Not in zones with daylight saving.
"Annotations work on any call." Not on calls from inside the bean (self-invocation).

47

Spring Boot

Key ideas

  • Boot 4 (November 2025; 4.1 in 2026): Spring Framework 7, Jakarta EE 11, Java 17+ (25 recommended), Jackson 3 default, Hibernate 7.1, Tomcat 11, modular auto-configuration and technology-named starters.
  • Startup: SpringApplication.run → environment prepared → context created → bean definitions loaded (including auto-configuration via AutoConfiguration.imports) → refresh → web server started → runners → ready events.
  • Auto-configuration: @AutoConfiguration classes with @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty, ordering; customisers rather than replacements; conditions report.
  • Configuration: property sources and precedence; profiles and profile groups; relaxed binding; @ConfigurationProperties records with validation; config trees for Kubernetes secrets; spring.config.import.
  • Production: embedded Tomcat/Jetty; Actuator (health with liveness/readiness groups, info, metrics, prometheus, loggers, conditions); Micrometer metrics, tracing and OpenTelemetry starter; structured logging; graceful shutdown default.
  • Testing: @SpringBootTest, slices (@WebMvcTest, @DataJpaTest, @JsonTest), Testcontainers @ServiceConnection, RestTestClient.
  • Startup and images: Spring AOT, GraalVM native images, JVM AOT cache (Leyden), CDS, layered JARs and Buildpacks images.
  • Peers: Quarkus, Micronaut, Helidon, ASP.NET Core, NestJS, Django, Rails, Phoenix.

Numbers to remember

  • Lab: Boot app started in about 3.1 s with 160 MB RSS vs 0.24 s and 49 MB for a JDK HttpServer; the JDK 25 AOT cache cut startup to 1.45 s; graceful shutdown completed a 3 s request, immediate shutdown dropped it.
  • Graceful shutdown phase timeout default 30 s.

Pitfalls

  • Replacing auto-configured beans instead of customising them (losing Boot's settings).
  • Mystery values from higher-precedence sources (env vars, system properties).
  • Reading configuration as raw strings at use sites; secrets in application.properties in git.
  • Exposing all Actuator endpoints publicly.
  • Heavy @SpringBootTest for everything instead of slices and plain unit tests.
  • Shutdown timeouts longer than the platform's kill timeout.

Glossary

  • Starter: a curated dependency for one capability.
  • Auto-configuration: conditional configuration contributed by Boot or libraries.
  • Relaxed binding: mapping CAFE_NAME, cafe.name and cafe-name to the same property.
  • Actuator: Boot's operational endpoints.
  • Spring AOT: build-time processing of bean definitions into generated code.
  • Layered JAR: a JAR organised so container image layers change rarely.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Started means ready means fast." The first requests run cold code.
"A readiness probe makes deploys safe." Only if the server waits for it to be seen before stopping.
"Graceful shutdown means no failed requests." It finishes requests that arrived; others may still be on their way.
"Warm-up warms the application." It warms the code it runs.
"Small pages are fast pages." A page just over a buffer size can wait for a delayed ACK.
"Relaxed binding catches typos." A misspelt property or variable matches nothing, silently.

48

Spring Web — MVC and WebFlux

Key ideas

  • DispatcherServlet flow: filters → handler mapping → interceptors' preHandle → argument resolvers and message converters → controller → return-value handlers → exception resolvers (advice) → afterCompletion; errors otherwise forwarded to /error.
  • Controllers: @RestController, mapping annotations, @PathVariable, @RequestParam, @RequestHeader, @RequestBody, ResponseEntity; API versioning support in Spring 7.
  • Validation and errors: @Valid with Bean Validation; @RestControllerAdvice; ProblemDetail and ErrorResponse; spring.mvc.problemdetails.enabled.
  • Hooks: servlet filters (everything, raw), HandlerInterceptor (handler-aware), advice (exceptions, bodies).
  • Serialisation: HttpMessageConverters, content negotiation by Accept, Jackson 3 with JsonMapper customisers.
  • Clients: RestClient (sync, fluent), HTTP service interfaces (@HttpExchange), WebClient (reactive), RestTemplate (maintenance); timeouts via request factories.
  • Reactive: Reactive Streams (publisher, subscriber, subscription, backpressure); Reactor Mono/Flux, operators, schedulers; WebFlux on Netty's event loop; never block the loop; virtual threads as the simpler alternative for blocking stacks.
  • Elsewhere: ASP.NET Core controllers and minimal APIs, NestJS, FastAPI, JAX-RS/Quarkus, Ktor, Express/Fastify; reactive equivalents in RxJS, Kotlin Flow, Akka Streams, Rust async streams.

Numbers to remember

  • Lab: 20 Tomcat threads capped a 100 ms endpoint at 188 req/s (Little's law: 200); virtual threads reached 465 req/s on 2 cores; a RestClient with no timeout waited 20 s, with 500 ms it failed in 563 ms; 20 blocking calls on a 2-thread event loop took 1,012 ms vs 106 ms on boundedElastic.
  • Tomcat default max threads 200; Reactor limitRate(n) replenishes at 75%.

Pitfalls

  • Two error formats (framework errors not mapped to ProblemDetail).
  • Business logic in controllers; entities exposed directly as request/response bodies.
  • HTTP clients without connect and read timeouts.
  • Blocking calls (JDBC, RestClient, Thread.sleep) inside WebFlux handlers.
  • Subscribing twice to a cold publisher and repeating side effects.
  • Platform-thread pools sized without Little's law; virtual threads without downstream limits.

Glossary

  • Handler: the controller method chosen for a request.
  • Message converter: converts between HTTP bodies and objects.
  • Interceptor: hook around handler execution inside Spring MVC.
  • Backpressure: consumers signalling how much they can take.
  • Cold publisher: one that starts work anew for each subscriber.
  • Event loop: a few threads multiplexing many connections with non-blocking I/O.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Validation makes any input format safe." Only what the format names can be checked.
"Duplicate JSON keys are harmless." Parsers disagree on which one wins.
"Now is now." Each reading is a different time; a request needs one.
"Problem details are always better." For clients that read them; others display them.
"Deprecation headers tell clients to move." They label; counting and changing the clients moves them.
"Controllers are the architecture." They translate; the rules live in a service you can test without HTTP.

49

Persistence — JDBC, JPA, Hibernate and Spring Data

Key ideas

  • Stack: JDBC → JdbcClient/JdbcTemplate → JPA (Hibernate 7) → Spring Data repositories; all share connections, transactions and SQL.
  • JDBC: connections from a pool, prepared statements, result sets, try-with-resources, SQLSTATE codes, batching, COPY.
  • JPA: entities, ids and generators, associations (owning side, mappedBy), embeddables, inheritance strategies; entity states (transient, managed, detached, removed); the persistence context as identity map and unit of work; flush modes; dirty checking.
  • Loading: lazy by default for collections; N+1; fetch joins, entity graphs, batch fetching; projections (interfaces, records, DTO queries) for reads; pagination with joins (two-step queries).
  • Transactions: @Transactional propagation, read-only hints, rollback rules (unchecked by default), isolation levels; keep them short; no remote calls inside.
  • Concurrency: optimistic locking (@Version), pessimistic locks (FOR UPDATE, SKIP LOCKED for queues), atomic updates.
  • Pools: HikariCP sizing (small, per-core), timeouts, leak detection; PgBouncer modes.
  • Elsewhere: Go database/sql with sqlc or GORM, .NET EF Core and Dapper, Python SQLAlchemy and Django ORM, Rust sqlx and Diesel, Node Prisma, Drizzle and Knex, Ecto in Elixir.

Numbers to remember

  • Lab: N+1 (201 queries) 47.6 ms vs one join 1.1 ms on localhost; 10,000 inserts: 2,275 ms autocommit, 89 ms batched, 20 ms COPY; opening a connection 7.2 ms vs 0.03 ms per query reused; read-modify-write lost 85% of concurrent increments.
  • PostgreSQL error codes: 23505 unique, 23503 foreign key, 23514 check, 40001 serialisation failure, 40P01 deadlock.

Pitfalls

  • Lazy associations touched in loops or during serialisation (N+1); open-session-in-view hiding it (disable spring.jpa.open-in-view).
  • IDENTITY ids preventing insert batching; saving entities one by one in big loops.
  • @Transactional on private methods or self-invoked methods; catching exceptions inside and committing partial work.
  • Long transactions holding locks and connections (remote calls inside them).
  • Read-modify-write without versions or locks; entities with mutable equals/hashCode on generated ids.
  • Oversized pools; no connectionTimeout; no statement timeouts.

Glossary

  • Persistence context: the set of managed entities in a unit of work.
  • Flush: synchronising pending changes to the database (before commit or queries).
  • Fetch join: a join that loads an association in the same query.
  • Optimistic locking: detecting concurrent changes with a version check at write time.
  • Connection pool: reusable open database connections.
  • Projection: querying only the fields a use case needs.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"A file is just bytes; read it." Arrays and buffers stop at 2 GiB; read in windows.
"An append-only log is simple storage." Its restart time and memory grow with history until you add checkpoints.
"Compaction solves growth." It removes superseded records; live state still grows.
"fsync makes a file durable." It makes its contents durable; a new or renamed name needs the directory fsynced.
"Autocommit is fine for bulk writes." Each commit waits for a flush: batch them (TiffinBox's group commit).
"The ORM loads what I use." It loads what you touch, one query at a time, unless you say otherwise.

50

Spring Security and Modern Identity

Key ideas

  • Authentication vs authorisation; 401 (with WWW-Authenticate) vs 403; deny by default; object-level checks (ownership), not just roles (broken access control is OWASP's top risk).
  • Spring Security: SecurityFilterChain beans (ordered, matched by request), AuthenticationManager/providers, SecurityContextHolder, UserDetailsService, PasswordEncoder (delegating, bcrypt default; Argon2id preferred), authorities and roles (ROLE_ prefix), method security (@PreAuthorize), passkeys/WebAuthn (6.4+), MFA (7).
  • Sessions: server-side session plus cookie (HttpOnly, Secure, SameSite); session fixation protection; CSRF tokens for cookie-authenticated state changes.
  • CORS: browsers block reading cross-origin responses unless allowed; preflights for non-simple requests; explicit origin allow-lists; credentials never with *.
  • OAuth 2.0: roles (resource owner, client, authorisation server, resource server); authorisation code flow with PKCE for all clients; client credentials for services; refresh tokens; scopes. Implicit and password grants are deprecated (OAuth 2.1).
  • OpenID Connect: identity layer (ID token, userinfo, discovery, JWKS).
  • JWT: header, payload, signature; validate algorithm (server-chosen), signature, exp/nbf, iss, aud; short lifetimes; asymmetric keys from JWKS; opaque tokens with introspection as the alternative.
  • Browser apps: the BFF pattern keeps tokens server-side, giving the browser only a SameSite session cookie.
  • Service to service: client credentials, mTLS, workload identity (SPIFFE), token exchange.

Numbers to remember

  • Lab: salted SHA-256 about 2.2 million guesses per second per core vs 7 for PBKDF2 at 600,000 iterations, 14 for bcrypt cost 10, 34 for Argon2id (19 MiB).
  • OWASP minimums: Argon2id m=19 MiB, t=2, p=1; PBKDF2-HMAC-SHA256 600,000 iterations; bcrypt cost 10+. bcrypt input limit 72 bytes.

Pitfalls

  • 401/403 confusion; endpoints left public by forgetting a rule (no deny-by-default).
  • Fast hashes, unsalted hashes, encrypted passwords.
  • JWT verification trusting the header's alg; weak HS256 secrets; no aud/iss checks; long-lived tokens without revocation strategy.
  • Tokens in localStorage (readable by any XSS); SameSite=None session cookies without CSRF protection.
  • CORS reflecting any origin with credentials; state-changing GET endpoints.
  • Role checks without ownership checks (IDOR).

Glossary

  • Principal: the authenticated identity.
  • Authority: a granted permission or role.
  • PKCE: proof key for code exchange, binding a code to the client that requested it.
  • ID token: OpenID Connect's token describing the user's authentication.
  • CSRF: tricking a browser into sending authenticated requests from another site.
  • Preflight: the browser's OPTIONS check before a non-simple cross-origin request.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Logged-in users can only see their own data." Only if every object lookup checks ownership.
"403 is the honest answer." For objects, 404 avoids confirming they exist.
"Turn on security, then fix what breaks." Report first; the breakage is measurable in advance.
"A valid signature means valid claims." Claims can be ambiguous, for another audience, or expired.
"Tokens belong in headers." Browsers' EventSource, images and navigations only send cookies.
"Rotating a key logs everyone out." Not if old keys still verify until their tokens expire.

51

Asynchronous Work, Jobs and Messaging

Key ideas

  • Where work runs: in the request (the user needs the result), in-process async (best effort), durable jobs (must happen, same service), messaging (other services react).
  • In-process: executors (virtual threads for I/O), @Async, CompletableFuture, @Scheduled (and the single-instance problem: ShedLock, leader election), graceful draining.
  • Durable jobs: job tables with FOR UPDATE SKIP LOCKED, leases, run_after, attempts, backoff with jitter, dead states; JobRunr, db-scheduler, Quartz.
  • Messaging models: point-to-point queues vs publish/subscribe; queues (RabbitMQ exchanges and bindings, SQS) vs logs (Kafka topics, partitions, offsets, consumer groups, retention, compaction).
  • Guarantees: at-most-once, at-least-once (the practical default), effectively-once via idempotency; Kafka idempotent producers and transactions within Kafka.
  • Patterns: transactional outbox (polling or CDC with Debezium), inbox/idempotent consumer, dead-letter queues, retry topics, ordering by key/partition, sagas (choreography vs orchestration) and durable workflow engines (Temporal).
  • Elsewhere: Celery/RQ/Dramatiq (Python), Sidekiq/Solid Queue (Ruby), BullMQ (Node), Oban (Elixir), river/asynq (Go), Hangfire/MassTransit (.NET).

Numbers to remember

  • Lab: a crash lost 64 of 100 in-memory tasks; unlocked competing workers ran 890 of 1,000 jobs more than once (2,695 side effects); one redelivery doubled an SMS without deduplication; a poison job retried at 50/100/200/400 ms then went dead without blocking others.

Pitfalls

  • Business-critical work in memory only; @Async methods losing exceptions.
  • Dual writes to the database and a broker; publishing inside a transaction that may roll back.
  • Non-idempotent consumers; deduplication records committed separately from the effects.
  • Unbounded retries, retries without backoff or jitter, poison messages blocking partitions.
  • Assuming global ordering; changing partition keys; large messages instead of references.
  • Scheduled jobs running on every instance.

Glossary

  • At-least-once: every message is delivered one or more times.
  • Idempotency key: an identifier that lets a receiver ignore repeats.
  • Outbox: a table of events written in the business transaction, published later.
  • Dead-letter queue: where messages go after failing too often.
  • Consumer group: consumers sharing a topic's partitions, each partition read by one member.
  • Saga: a sequence of local transactions with compensating actions instead of a distributed transaction.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Background work doesn't affect requests." It shares locks, CPU and disk with them.
"A job runs until it's stopped." On the JDK's scheduler, until it throws once.
"Logging every event is enough to act on." Someone needs the counts, by who and what.
"Async means fire and forget." It means someone else must remember: a queue, a log, a retry.
"Exactly-once delivery is a setting." Delivery is at-least-once; effects are made once by idempotent consumers.

52

Resilience

Key ideas

  • Failure is normal: partial failures, slow responses (worse than errors), correlated failures, cascading failures through shared resources.
  • Timeouts: connect vs read vs overall; derived from the caller's deadline; deadline propagation (gRPC, headers).
  • Retries: transient errors only, idempotent operations only; exponential backoff with full jitter; bounded attempts; one layer; retry budgets; honour Retry-After.
  • Circuit breakers: closed → open (failure rate or slow-call rate over a window) → half-open trial; fail fast with fallbacks; expose state as metrics.
  • Bulkheads: semaphores, separate pools per dependency, @ConcurrencyLimit.
  • Rate limiting: token bucket, leaky bucket, fixed and sliding windows, GCRA; per client and global; 429 with Retry-After.
  • Overload: bounded queues, load shedding, priorities, adaptive concurrency limits, CoDel-style queue-time limits.
  • Degradation and tail latency: fallbacks, cached or default responses, feature switches; hedged requests for idempotent reads.
  • Implementations: Spring Framework 7 (@Retryable, @ConcurrencyLimit, RetryTemplate), Resilience4j, Polly (.NET), tower (Rust), Go libraries, service-mesh policies.

Numbers to remember

  • Lab: three layers of 3 retries → 64 calls; full jitter cut the retry peak from 1,000 to 154 per 10 ms; a breaker turned 100 × 200 ms timeouts (20 s) into 1 s; a bulkhead kept menu latency at 5 ms instead of 6 s; shedding held p99 at 121 ms vs 3.1 s with an unbounded queue.
  • Availability compounds: 20 dependencies at 99.9% each ≈ 98% all up.

Pitfalls

  • No timeouts, or timeouts longer than the caller's.
  • Retrying non-idempotent operations or 4xx errors; retrying at every layer; retries without jitter.
  • Fallbacks that hide outages (no metrics, no alerts) or that call the same failing dependency.
  • Shared pools with no bulkheads; unbounded queues.
  • Circuit breakers with thresholds never tested under real failure (no game days).

Glossary

  • Backoff: increasing delay between retries.
  • Jitter: randomness added to delays.
  • Retry storm: synchronised or amplified retries overwhelming a recovering service.
  • Half-open: the breaker state that admits trial calls.
  • Bulkhead: isolation of capacity per dependency or workload.
  • Load shedding: rejecting excess work early to protect latency.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"One bad instance out of two halves capacity." It can take everything, if clients wait on it.
"Measure queue depth to detect overload." Measure the age of the oldest waiter, where it waits.
"Readiness should follow the instant's health." Without hysteresis it flaps faster than checks.
"Retrying a 503 is always safe." Only when the server guarantees nothing was done.
"Timeouts on calls are enough." Background work needs deadlines too.
"Retries make systems more reliable." Uncapped, they multiply load on the struggling part.

53

Caching

Key ideas

  • Why: temporal locality and skewed (power-law) popularity; cost is staleness, memory, complexity and new failure modes.
  • Layers: browser/HTTP and CDN, in-process (Caffeine), distributed (Redis/Valkey, Memcached), database buffer pool and materialised views.
  • Patterns: cache-aside (most common), read-through, write-through, write-behind; @Cacheable/@CacheEvict; key design (namespaces, versions), serialisation.
  • Lifetimes: TTLs with jitter; eviction (LRU, LFU, W-TinyLFU, random; Redis maxmemory-policy).
  • Consistency: delete-after-commit invalidation, races and leases, CDC-driven invalidation, versioned keys, per-data staleness budgets.
  • Failure modes: stampedes (single-flight, locks, early refresh), hot keys (local caching, key replication), negative caching, penetration, cache as a hidden dependency (cold start after a flush).
  • Redis: single-threaded command execution, data structures, persistence options, replication and cluster sharding, Valkey fork.
  • Elsewhere: Caffeine/Ehcache (JVM), IMemoryCache/HybridCache (.NET), groupcache/ristretto (Go), moka (Rust), functools.lru_cache and cachetools (Python), Cachex (Elixir).

Numbers to remember

  • Lab: a cache of 1% of keys gave 50.6% hits on Zipf traffic vs 1% uniform; in-process 0.03 µs vs Redis 14 µs vs PostgreSQL PK lookup 20 µs on localhost; plain cache-aside sent 50 concurrent misses to the database vs 1 with single-flight or a lock; a stale price survived an invalidation for the full 300 s TTL.

Pitfalls

  • Caching cheap queries; caching without measuring hit rate.
  • No TTLs (permanent staleness); identical TTLs (synchronised expiry).
  • Updating cached values instead of deleting; invalidating before commit.
  • Unbounded local caches; caching per-user data under shared keys (data leaks).
  • Redis as a cache with noeviction; mixing cache and durable data in one instance.
  • Treating the cache as required: the system must survive a cold or failed cache.

Glossary

  • Hit rate: fraction of requests answered by the cache.
  • Cache-aside: the application loads and stores cache entries itself.
  • TTL: time to live before expiry.
  • Eviction: removing entries to make room.
  • Single-flight: collapsing concurrent loads of one key into one.
  • Negative caching: caching the absence of a value.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"Caches are for databases." They're for any repeated work, especially under a lock.
"Every cache needs a TTL." With a version in the key, entries are never stale, just unused.
"Cache the response." Cache what's shared; add what's per request.
"Hit rate measures a cache." What it protects does: latency, load, contention.
"Deleting the key fixes staleness." A racing reader can write the old value back.

54

Backend Testing

Key ideas

  • Purpose: fast, trustworthy feedback that lets you change code; executable documentation.
  • Shape: many unit tests, fewer integration tests, few end-to-end tests (pyramid, or "trophy" with more integration for glue-heavy services); test behaviour through public APIs.
  • Unit level: JUnit 5/6 (@Test, lifecycle, @Nested, @ParameterizedTest, dynamic tests, extensions), AssertJ, test doubles (dummy, stub, fake, spy, mock) with Mockito used sparingly.
  • Beyond examples: property-based testing (jqwik) with shrinking; mutation testing (PIT) as a measure of assertion strength; coverage as a map of untested code, not a target.
  • Integration: Spring test slices (@WebMvcTest, @DataJpaTest, @JsonTest, @RestClientTest), context caching, @SpringBootTest with RestTestClient; Testcontainers with @ServiceConnection; transactions rolled back per test.
  • Dependencies: WireMock for HTTP stubs; consumer-driven contract tests (Pact, Spring Cloud Contract) or OpenAPI-based checks (Specmatic); ArchUnit for architecture rules.
  • System level: end-to-end tests of critical journeys, performance tests (Gatling, k6, JMeter) with SLO-based assertions, chaos and fault injection.
  • Flakiness: timing, shared state, order, time, randomness, network; quarantine and fix.
  • Elsewhere: pytest and Hypothesis, Go testing with table tests and fuzzing, xUnit/NUnit with Moq/NSubstitute, Jest/Vitest, Rust #[test] and proptest, ExUnit with StreamData.

Numbers to remember

  • Lab: a suite with 100% line coverage killed 1 of 6 mutants (a stronger one killed 6); a property found a bill-splitting bug on the first random case; sleep-based waiting failed 51% of 200 runs; unit test 0.09 ms, database test 0.9 ms, Spring Boot start about 3 s.

Pitfalls

  • Coverage targets driving assertion-free tests.
  • Over-mocking (tests that mirror implementation and break on every refactor).
  • In-memory databases (H2) standing in for PostgreSQL in repository tests.
  • Thread.sleep in tests; shared mutable state; dependence on time zones and the current date.
  • Many unique Spring contexts per suite; @DirtiesContext everywhere.
  • End-to-end tests for every edge case; no tests for error paths.

Glossary

  • Test double: anything standing in for a real dependency in a test.
  • Mutant: a deliberately altered program used to check that tests notice changes.
  • Property: a statement that must hold for all valid inputs.
  • Shrinking: reducing a failing random input to a minimal one.
  • Test slice: a Spring test loading only one layer's beans.
  • Flaky test: a test that passes and fails without code changes.

Practise: Exercises · Companion · TiffinBox stage

Misconceptions (from the companion)

Misconception What's actually true
"100% of mutants killed: great tests." Or a suite that always fails; check the control.
"Every path has a test." Every path someone remembered; mutation finds the rest.
"Each route has its own security test." A loop over all routes catches the one nobody wrote.
"It passed, so it's not flaky." Flakiness is a failure rate; one run can't show it.
"High coverage means well tested." Lines ran; nothing says a wrong line would fail a test.