RecapsKayavak

Kayavak / Recaps / Software Architecture

Recaps · Volume 13

Software Architecture

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

135

Clean Code

Key ideas

  • Maintainability is economics: most cost is reading and changing code.
  • Names carry design: intention-revealing, domain language, consistent.
  • Functions: small, one level of abstraction, few parameters, no hidden side effects; command-query separation.
  • Cohesion (functional best, coincidental worst) and coupling (data < stamp < control < common < content) types.
  • Modules and information hiding: hide what is likely to change behind stable interfaces.
  • Errors: explicit, at the right level; don't swallow; don't use exceptions for control flow.
  • Comments explain why, not what; delete commented-out code.
  • Refactoring: small behaviour-preserving steps with tests green; separate from behaviour changes.
  • Metrics with judgement: complexity, size, duplication, churn and hotspots point to where to look.

Numbers to remember

  • Common thresholds: CCN ≤ 10 per function; functions a screen or less.
  • Lab: 5.3% of requests functions had CCN > 10; top hotspot utils.py (110 commits × CCN 201).
  • Lab: random property testing missed a >= boundary bug; one explicit boundary example caught it.

Pitfalls

  • Refactoring and changing behaviour in one step.
  • Cleaning rarely changed code while hotspots rot.
  • Metric gaming (splitting functions mechanically without better names or boundaries).
  • Generic names (data, process, manager, util).
  • Flag parameters that make one function do two things.
  • Comments that restate code and drift out of date.

Glossary

  • Hotspot: complex code that changes often.
  • Characterization test: captures current behaviour before changing code.
  • CQS: command-query separation.
  • Information hiding: modules conceal design decisions likely to change.
  • Change coupling: files that tend to change together.

136

SOLID

Key ideas

  • S: a module answers to one actor/stakeholder; separate code that changes for different reasons.
  • O: design so common extensions are additions (new strategy, new handler), not edits.
  • L: subtypes honour the base contract: no stronger preconditions, no weaker postconditions, same invariants and error behaviour; verify with contract tests.
  • I: small, role-specific interfaces; let clients define the interfaces they need (Go's style).
  • D: policy depends on abstractions owned by the policy layer; infrastructure implements them; wire at the edge (composition root).
  • In functional code: S → small pure functions; O → higher-order functions; L → laws and contracts; I → minimal function signatures; D → passing functions/capabilities in.
  • Costs: indirection, more types, speculative abstraction; apply where change actually happens.

Numbers to remember

  • Lab: contract tests caught 2 of 5 implementations breaking the base contract.
  • Lab: 40% of Go's 221 exported interfaces have one method; 246 functions take an io.Reader.
  • Lab: injecting an in-memory store made 400 tests 12× faster.

Pitfalls

  • Inheritance for code reuse that breaks substitutability.
  • Interfaces mirroring a single class ("header interfaces") added "for testing" with no other use.
  • God interfaces and god classes.
  • Dependency injection containers used where plain constructor parameters suffice.
  • Applying OCP to code that never gets extended.

Glossary

  • Contract: preconditions, postconditions and invariants of an operation.
  • Composition root: the one place where concrete implementations are wired together.
  • Role interface: an interface defined by what one client needs.
  • Strategy: interchangeable behaviour behind an interface (chapter 137).
  • Speculative generality: abstraction for changes that never come.

137

Design Patterns

Key ideas

  • Patterns are named solutions with forces and trade-offs; use when the problem is present.
  • Creational: Factory Method, Abstract Factory, Builder, Prototype; Singleton mostly replaced by dependency injection.
  • Structural: Adapter, Decorator, Facade, Composite, Proxy, Bridge, Flyweight.
  • Behavioural: Strategy, Observer, Command, State, Template Method, Chain of Responsibility, Iterator, Visitor, Mediator, Memento.
  • Composition over inheritance: most structural/behavioural patterns compose objects behind interfaces.
  • Functional equivalents: higher-order functions (Strategy, Decorator, Command), closures, pattern matching (Visitor), iterators/generators.
  • Architectural cousins: middleware chains, plug-ins, pub/sub, repositories, unit of work.

Numbers to remember

  • Lab: Retry lifted success 70% → 98%; Cache cut supplier calls 1,370 → 12.
  • Lab: ≈50 ns per Python decorator layer; Go interface dispatch ≈ a direct call.

Pitfalls

  • Pattern-first design ("let's use a factory here").
  • Singletons hiding global state and blocking tests.
  • Deep inheritance hierarchies via Template Method.
  • Decorator stacks in an order nobody documented.
  • Visitor and Abstract Factory where a switch or a dict would do.

Glossary

  • Forces: the competing concerns a pattern balances.
  • Composite: treat a tree of objects like one object.
  • Proxy: stand-in controlling access (lazy, remote, protected).
  • Command: an operation as an object (queue, undo, log).
  • Chain of responsibility: pass a request along handlers until one handles it.

138

Domain-Driven Design

Key ideas

  • Strategic design: core, supporting and generic subdomains; invest design effort in the core; buy or simplify the rest.
  • Bounded contexts with their own ubiquitous language; one model per context; context maps describe relationships (partnership, shared kernel, customer–supplier, conformist, anticorruption layer, open host service, published language, separate ways).
  • Tactical design: entities, value objects, aggregates (root, invariants, small, reference others by ID), domain services, domain events, repositories, factories.
  • One aggregate per transaction; cross-aggregate rules via events and eventual consistency.
  • Discovery: event storming, domain storytelling, example mapping with domain experts.
  • Architecture fit: hexagonal/clean architecture keeps the domain free of infrastructure (chapter 139); contexts map to modules (140) or services (141).

Numbers to remember

  • Lab: Hypothesis found 2 invariant violations in the anemic model with 3-step counterexamples; the aggregate passed 300 sequences.

Pitfalls

  • Anemic models with rules scattered across services.
  • Huge aggregates that lock too much and contend.
  • One "enterprise model" shared across contexts.
  • DDD ceremony for CRUD-only or generic subdomains.
  • Tables-first design leaking database structure into the domain.
  • Contexts that share databases, making boundaries fiction.

Glossary

  • Core domain: where the business differentiates.
  • Aggregate root: the only entry point for changes to an aggregate.
  • Anticorruption layer: translation layer protecting your model.
  • Event storming: workshop technique for discovering domain events and boundaries.
  • Domain service: domain logic that doesn't belong to one entity.

139

Architecture Styles

Key ideas

  • Styles trade quality attributes: modifiability, testability, performance, scalability, deployability, simplicity.
  • Layered: closed vs open layers; sinkhole anti-pattern; database-centric drift.
  • Hexagonal / clean / onion: dependencies point inward; ports owned by the core; adapters at the edge; composition root wires them.
  • Event-driven: broker vs mediator topologies; decoupling at the cost of traceability.
  • Microkernel: stable core, plug-in contracts.
  • Pipes and filters, space-based, service-based, microservices: each with its sweet spot.
  • Fitness functions keep architecture from eroding: dependency rules, latency budgets, size limits, checked in CI.
  • Mixing styles is normal: hexagonal services inside an event-driven system, layered UI on top.

Numbers to remember

  • Lab: one core ran 100 tests in 0.23 s in memory and 2.15 s on PostgreSQL, unchanged.
  • Lab: a single new import broke the purity contract and was reported with its line number.
  • Sinkhole rule of thumb: more than ~20% pass-through requests.

Pitfalls

  • Hexagonal ceremony for trivial CRUD.
  • Ports shaped like the database ("findByXAndY") rather than the domain's needs.
  • Testing only through in-memory adapters and never the real ones.
  • Architecture rules in a wiki that nothing enforces.
  • Choosing microservices as a style before having the problems they solve.

Glossary

  • Port / adapter: core-owned interface / technology-specific implementation or driver.
  • Driving (primary) vs driven (secondary): adapters that call the core vs ones the core calls.
  • Composition root: where adapters are plugged into ports.
  • Fitness function: automated check of an architectural characteristic.
  • Architecture erosion: gradual divergence of code from intended structure.

140

Modular Monolith

Key ideas

  • One deployable, many modules: simple operations, in-process calls, local transactions.
  • Module boundaries from bounded contexts and business capabilities, not technical layers.
  • Public API per module (facade, commands, queries, DTOs); internals private; no cycles.
  • Data ownership: schema per module, no cross-module joins or writes; read models for cross-module queries.
  • Communication: direct API calls for queries/commands; in-process domain events for reactions; outbox if events leave the process.
  • Enforcement: import rules, cycle checks, schema permissions, architecture tests in CI (Spring Modulith, ArchUnit, Packwerk, import-linter, Nx).
  • Evolution: extract a module into a service only for a concrete driver; strangler-fig style, behind its existing API.

Numbers to remember

  • Lab: in-process module call 68 ns vs HTTP+JSON on localhost 273 µs (≈4,000×).
  • Lab: two everyday shortcuts broke both boundary contracts, each reported with file and line.

Pitfalls

  • Modules by technical layer (controllers/, services/, repositories/) instead of by capability.
  • Shared tables and cross-module joins.
  • "Utility" or "common" modules that everything depends on and that grow without bound.
  • Boundaries without enforcement; cycles tolerated "temporarily".
  • Extracting services before modules are clean (a distributed ball of mud).

Glossary

  • Big ball of mud: a system with no discernible structure.
  • Module facade: the public entry point of a module.
  • Read model / projection: data maintained from another module's events for querying.
  • Strangler fig: incrementally replacing parts of a system behind stable interfaces.
  • Package by feature: organising code by business capability.

141

Microservices

Key ideas

  • Microservices: independently deployable services owned by teams, each with its own data, around business capabilities.
  • Boundaries: bounded contexts, business capabilities, team cognitive load; avoid entity services (CRUD per table).
  • Organisation: Conway's law and the inverse Conway manoeuvre; Team Topologies (stream-aligned, platform, enabling, complicated-subsystem teams).
  • Communication: synchronous (REST/gRPC) for queries; asynchronous events for propagation; avoid long synchronous chains.
  • Data: database per service; sagas for cross-service workflows; CQRS/read models for queries spanning services.
  • Resilience: timeouts, budgets, breakers, bulkheads, hedging, graceful degradation.
  • Operations: CI/CD per service, observability (tracing essential), service mesh or libraries, platform engineering.
  • Migration: strangler fig from a monolith, module by module, behind stable APIs.

Numbers to remember

  • Lab: 10 parallel calls → ~10% of pages hit a 1%-per-service slow path; page success 94.7% with 99.5% services.
  • P(at least one slow among n) = 1 − (1 − p)ⁿ; success = sⁿ.
  • "The Tail at Scale": hedging after 10 ms cut p99.9 from ~1,800 ms to 74 ms for ~2% extra requests.

Pitfalls

  • Distributed monolith: services that must deploy together or share a database.
  • Chatty synchronous chains; entity services.
  • Splitting before boundaries are understood.
  • No platform: every team reinventing deployment, logging, auth.
  • Per-service dashboards hiding user-level failure.
  • Ignoring DORA metrics to judge whether the split helped.

Glossary

  • Distributed monolith: services coupled so tightly they behave as one deployment.
  • BFF: backend for frontend, aggregating calls for one client type.
  • Hedged request: duplicate request to cut tail latency.
  • Strangler fig: incremental replacement of a monolith.
  • DORA metrics: deployment frequency, lead time, change failure rate, time to restore.

142

Architecture Decision Making

Key ideas

  • Architectural decisions: costly to reverse, system-wide in effect (structure, technology, integration, data, deployment).
  • The architect's role: make trade-offs explicit, gather evidence, involve stakeholders, record decisions, keep them true; "last responsible moment" for irreversible choices.
  • Quality attribute scenarios: stimulus, environment, response, measure (e.g. "at 100 orders/s, p95 checkout < 200 ms").
  • Trade-off analysis: options × criteria with evidence; sensitivity analysis; ATAM's utility tree, sensitivity and trade-off points.
  • ADRs: context, decision, status, consequences, revisit conditions; immutable once accepted; superseded, not edited.
  • Fitness functions: automated checks of architectural properties in CI; ratchets for legacy code.
  • Reversibility: prefer decisions that are cheap to undo (two-way doors) and invest analysis in one-way doors.

Numbers to remember

  • Lab: base matrix 59 / 56 / 46; a single weight change 2 → 6 flipped the winner; team-heavy weights made it a near tie (77/76/74).
  • Lab: fitness suite 3 PASS / 2 FAIL (models.py 1,184 lines; _encode_files CCN 21).

Pitfalls

  • Decisions by fashion or résumé; missing alternatives.
  • Matrices treated as objective; no sensitivity check; double-counted criteria.
  • Decisions recorded nowhere, or in chat threads.
  • ADRs edited after the fact; no revisit conditions.
  • Rules without fitness functions (or fitness functions silenced when they fail).
  • Analysis paralysis on reversible decisions.

Glossary

  • ATAM: SEI's Architecture Tradeoff Analysis Method.
  • Utility tree: prioritised quality-attribute scenarios.
  • Sensitivity point: a parameter a quality attribute strongly depends on.
  • One-way / two-way door: irreversible / reversible decision.
  • Ratchet: a limit that may only tighten.

LLD

Low-Level Design Case Studies

Key ideas

  • Approach: clarify → entities and behaviours → interfaces → patterns where needed → concurrency → tests → extensions.
  • Parking lot: spots by type, allocation strategy, tickets and pricing strategy, concurrency on allocation.
  • LRU cache: map + doubly linked list; every operation mutates recency; sharding or approximate LRU for scale.
  • Rate limiter: token bucket, leaky bucket, fixed and sliding windows; injected clock; per-key buckets; distributed variants.
  • Elevator: state machine per car, request scheduling (SCAN/LOOK), dispatcher strategy.
  • Expense splitting: ledger of balances, simplification of debts, exact money arithmetic.
  • Quality bar: readable names, small classes, clear interfaces, tests for edge cases and concurrency.

Numbers to remember

  • Lab: token bucket with burst 10, 5/s → 19 of 200 requests allowed over 2 s.
  • Lab: unlocked LRU crashed 5/5 runs; -race reported 23 races.

Pitfalls

  • Coding before clarifying; gold-plated class hierarchies.
  • Ignoring concurrency until asked, then bolting on locks.
  • Calling time.Now() and rand directly, making tests flaky.
  • Floats for money in expense splitting.
  • No tests, or only happy-path tests.

Glossary

  • Machine coding: timed implementation of a small system.
  • Token bucket: limiter with refill rate and burst capacity.
  • Lock striping / sharding: several locks over partitions of data.
  • SCAN/LOOK: elevator scheduling algorithms.
  • Debt simplification: minimising settlements between participants.