Design Patterns & Architecture Study
Original study notes, runnable examples, and architecture tutorials.
Inspiration: refactoring.guru catalog and GeeksforGeeks catalog (coverage only — all prose, diagrams, and code here are original). See CONTRIBUTING.
Single source of truth: all study content lives under
content/— see content/MAPPING.md for the symlink map (patterns/,architecture/,principles/,practice/at root and underdocs/are views ontocontent/).
1. Design Patterns
Per-pattern study pages grouped by category, plus a unified selection guide.
- Creational (5): Factory Method · Abstract Factory · Builder · Prototype · Singleton — overview: Creational
- Structural (7): Adapter · Bridge · Composite · Decorator · Facade · Flyweight · Proxy — overview: Structural
- Behavioral (11): Chain of Responsibility · Command · Interpreter · Iterator · Mediator · Memento · Observer · State · Strategy · Template Method · Visitor — overview: Behavioral
- Each pattern page now includes its complex scenario, edge cases, and expanded anti-pattern guidance (merged from the former depth pages).
2. Architecture (Application / System)
Two tracks: how code is structured inside one project vs how services communicate at scale. Overview and decision guidance: architecture tutorial and selection guide §2.
- Application (6): Layered · Hexagonal · Onion · Clean · Vertical Slice · MVC / MVVM / MVP
- System (7): Monolithic · Modular Monolith · Microservices · Event-Driven · Serverless · SOA · CQRS & Event Sourcing
- Each architecture page now includes its complex scenario, edge cases, and expanded failure-mode guidance (merged from the former depth pages).
3. Principles
Study catalog of 110 principles across 11 categories — see principles index and selection guide §3.
- SOLID (1–5) · General Design (6–20) · Architecture (21–33) · Distributed Systems (34–52) · Performance (53–61) · Security (62–69) · Testing (70–77) · API (78–84) · Development (85–92) · Functional (93–100) · BEAM/OTP (101–110)
4. Practice
Capstone exercises combining patterns and architecture — see practice index.
- Resilient E-Commerce Order Pipeline · Concurrent Multi-Format Report Generator · Moderated Multi-Room Chat Router · Extraction-Ready Modular Monolith · Replayable Event-Driven Payments · Isolated Multi-Tenant SaaS
5. Guides
- Selection guide — patterns, architecture, and principles in one place (problem → 2–3 candidates + confused-pair tables)
- Contributing — originality rules and page templates
- GitHub Pages — local preview and deploy
Suggested study order
- Strategy, Observer, Factory Method — core vocabulary.
- Decorator, Adapter, Facade, Command, State.
- Builder, Abstract Factory, Composite, Iterator, Template Method.
- Layered, Monolithic — the baseline everything else reacts to.
- Vertical Slice, Modular Monolith — first escapes from pure layering.
- Hexagonal, Onion, Clean — ports, rings, and dependency rules as a group.
- Singleton, Bridge, Proxy, Chain of Responsibility, Mediator.
- Microservices, Event-Driven — distribution and async as a group.
- Prototype, Flyweight, Memento, Interpreter, Visitor.
- SOA, Serverless, CQRS & Event Sourcing — enterprise, functions, and data separation last.
Running examples
./run.sh elixir strategy # or dart / go / rust
./run.sh all # run all 92 examples
make run LANG=elixir PATTERN=strategy
make run-all
- Elixir:
cd examples/elixir/strategy && elixir main.exs - Dart:
cd examples/dart/strategy && dart main.dart - Go:
cd examples/go/strategy && go run main.go - Rust:
cd examples/rust/strategy && cargo run --quiet
Each pattern folder has the same scenario in all four languages.
Pattern Page Template (Shared Explanation Shape)
Every file under patterns/<category>/<pattern>.md MUST follow this order.
Do not copy prose or diagrams from reference sites — write from scratch.
See content/MAPPING.md for single-source rules and guides/selection.md for the canonical chooser.
Intent
One or two sentences: what problem this pattern solves, in your own words.
Motivation
A small concrete scenario (3-6 sentences). Name the actors and the pain without the pattern (rigid branching, duplication, tight coupling, etc.).
Structure
Original diagram only. Use Mermaid (preferred) or ASCII. Example:
flowchart LR Client --> Context Context --> StrategyA Context --> StrategyB
List roles under the diagram:
- Role A — what it owns.
- Role B — what it owns.
Consequences
- Benefit: …
- Cost / trade-off: …
Basic Recap
3-5 sentences restating the pattern’s intent and core roles in your own words.
Complex Scenario
A work-like situation with at least two edge cases and a non-runnable pseudocode sketch.
When to Use / When Not to Use
Use when:
- …
Avoid when:
- …
Examples
Links to runnable code (same scenario, four languages):
examples/elixir/<pattern>/examples/dart/<pattern>/examples/go/<pattern>/examples/rust/<pattern>/
Expected outcome: one line describing what running any of them prints or proves.
Anti-pattern / Failure Mode
One misuse symptom plus one review signal, followed by the expanded failure-mode guidance and edge cases formerly kept in the depth page.
Related
Links to 2-4 neighbors: at least one same-pillar pattern and at least one cross-pillar link (architecture page, principle, or practice capstone) with one line on how they differ or combine.
Exercise
A small task (extend or break the example).
Self-check
2-3 questions. Answers in <details> collapsed block or answers.md next to the page.
Creational Patterns
Part of the unified study index: Home · canonical comparisons in selection guide.
Ways to make objects without tangling the code that uses them.
- Factory Method — one flow, subclasses pick the product kind.
- Abstract Factory — one doorway for a matching family of parts.
- Builder — step-by-step assembly with a final validity check.
- Prototype — clone a tuned example, then tweak the copy.
- Singleton — one shared owner for a single resource.
Abstract Factory
Intent
Provide one doorway that builds a whole matching set of related parts so clients never mix incompatible pieces.
Motivation
A UI kit ships buttons and checkboxes that must match: light theme parts go
together, dark theme parts go together. Scattering if theme == dark through
the app mixes light buttons with dark boxes. An abstract factory returns a
theme-consistent family from one call, and the app only talks to abstract
button and checkbox roles.
Structure
flowchart LR App --> Factory[Theme Factory] Factory --> Light[Light Theme Factory] Factory --> Dark[Dark Theme Factory] Light --> LB[Light Button] Light --> LC[Light Checkbox] Dark --> DB[Dark Button] Dark --> DC[Dark Checkbox]
- Abstract factory — creates button + checkbox without naming concrete kinds.
- Concrete factories — Light and Dark factories returning matching pairs.
- Abstract products — Button, Checkbox roles; concrete products fill each theme.
Consequences
- Benefit: theme consistency by construction; swapping themes swaps one factory.
- Cost: adding a new product kind (e.g., slider) touches every factory.
Basic Recap
Abstract Factory creates a compatible family of products without exposing their concrete classes to the client. One factory supplies related objects, such as a queue, storage bucket, and network policy for the same platform. The client depends on the family interfaces and avoids mixing implementations that cannot work together. This is broader than Factory Method: the central guarantee is consistency across several created products.
Complex Scenario
A deployment service provisions an isolated environment for each customer. A cloud-specific factory creates the network, message queue, and artifact store, and an environment planner wires them into one topology. Selecting each resource independently could pair a private network from one provider with credentials or endpoints from another. The factory should return a validated bundle whose region, encryption policy, and identity model agree.
Edge cases
- Partial failure: The network may exist when queue creation fails; the planner needs a provisioning journal and cleanup policy rather than treating factory return as an atomic transaction.
- Retries: Re-running creation must reuse environment-scoped names and idempotency tokens so it adopts existing resources instead of duplicating them.
- Concurrency: Two planners must not independently initialize a shared factory cache and publish half-initialized client bundles to other threads.
Family validation belongs before any remote calls where possible, because an abstract factory cannot make distributed provisioning atomic.
Sketch (illustrative pseudocode, not runnable):
EnvironmentPlanner.provision(request):
factory = factories.for(request.platform, request.region)
plan = factory.describeFamily(request.environmentKey)
validateCompatibility(plan)
journal = ProvisioningJournal.open(request.environmentKey)
network = factory.createNetwork(plan, journal)
queue = factory.createQueue(plan, journal)
store = factory.createArtifactStore(plan, journal)
bind(network, queue, store, journal)
return Environment(network, queue, store, journal)
When to Use / When Not to Use
Use when:
- Several related parts must vary together as a family.
Avoid when:
- Only one product kind exists or families never change together.
Examples
examples/elixir/abstract-factory/examples/dart/abstract-factory/examples/go/abstract-factory/examples/rust/abstract-factory/
Expected outcome: rendering light then dark prints a matched button + checkbox line per theme.
Anti-pattern / Failure Mode
-
Misuse: Forcing a family abstraction over products that never need to match.
-
Review signal: Families where callers mix parts from different variants.
-
Misuse symptom: A factory returns unrelated utilities, or callers routinely combine products from different factories and patch incompatibilities with conditionals. Another symptom is one implementation and one product, where a whole family abstraction merely mirrors constructors.
-
Review signal: Watch for provider names appearing in client branches, cross-family casts, and configuration tests that only check individual objects rather than their compatibility. Provisioning logs containing repeated resource names after retries indicate that the factory is hiding construction but not preserving environment identity.
Related
- Factory Method — one kind vs a family.
- Builder — family selection vs step-by-step assembly.
Exercise
Add a high-contrast factory producing its own button + checkbox without editing client render code.
Self-check
- What breaks if you mix factories?
Answer
Theme mismatch — a light button with a dark checkbox — which the pattern prevents by sourcing both from one factory. - How is this different from Builder?
Answer
Factory delivers a ready family at once; Builder assembles one complex thing step by step.
Builder
Intent
Assemble a complex thing step by step through a guided sequence so the same steps can yield different results.
Motivation
A monthly report has a header, a body table, and a footer, rendered as PDF for managers and CSV for analysts. A constructor with ten flags becomes unreadable and half-built reports slip through. A builder exposes one step per part and a final check that refuses incomplete reports, while a director reuses the same step order for each format.
Structure
flowchart LR Client --> Director[Report Director] Director --> Builder[Report Builder] Builder --> PDF[PDF Report Builder] Builder --> CSV[CSV Report Builder] PDF --> Product[Finished Report] CSV --> Product
- Director — runs the fixed step order without knowing the format.
- Builder — step contract (add header, body, footer) plus finish check.
- Concrete builders — PDF and CSV builders producing their own product.
- Product — the validated report.
Consequences
- Benefit: step reuse plus validation; new formats add a builder, not new branching.
- Cost: extra types for simple objects; overkill when two fields suffice.
Basic Recap
Builder constructs a complex object through a sequence of meaningful steps while keeping the final representation independent from that assembly process. It is useful when optional parts, defaults, and validation would otherwise produce a telescoping constructor or an invalid half-configured object. A director may reuse a recipe, but clients can also drive the steps directly. The finished product should be complete; the builder itself is the mutable assembly aid.
Complex Scenario
A CI service assembles pipeline definitions containing checkout, cache, test,
security-scan, approval, and deployment stages. Different product teams choose
optional stages, while required ordering and environment-specific defaults stay
consistent. A PipelineBuilder collects intent and validates dependencies before
producing an immutable definition. Compilation to the CI vendor’s YAML happens
only after validation, so construction does not trigger deployments or allocate
runners.
Edge cases
- Ordering: Deployment depends on tests and approval even if the caller adds it first; the builder must either topologically order stages or reject the missing predecessor with a useful error.
- Concurrency: A cached builder reused across requests can leak one team’s credentials into another pipeline, so each assembly needs isolated state.
- Partial failure: If semantic validation succeeds but artifact generation fails, no earlier step should have created remote jobs that require rollback.
Build locally and validate at the boundary; side effects belong to a separate pipeline submission operation.
Sketch (illustrative pseudocode, not runnable):
builder = PipelineBuilder(defaultsFor(team))
builder.checkout(repository)
builder.cache(dependencyLockfiles)
builder.tests(testTargets)
builder.deploy(cluster, requires = [tests, approval])
builder.approval(requiredRole)
definition = builder.build()
# build checks required stages, resolves order, freezes values,
# and performs no network operations
submit(definition) # separately authorized and observable
When to Use / When Not to Use
Use when:
- An object needs several ordered parts, variants, or validation before use.
Avoid when:
- Objects are flat or fully described by one or two arguments.
Examples
examples/elixir/builder/examples/dart/builder/examples/go/builder/examples/rust/builder/
Expected outcome: building a monthly report prints header + rows + footer lines for the chosen format.
Anti-pattern / Failure Mode
-
Misuse: A builder for a flat object with two optional fields and no validation.
-
Review signal: Build steps that can run in any order with no final check — a plain constructor would do.
-
Misuse symptom: A fluent builder becomes a differently spelled constructor with one setter per field, while callers can still obtain malformed products. Reusing one mutable builder as a singleton is another common failure that turns convenience into cross-request corruption.
-
Review signal: Look for
buildmethods with no invariant checks, public setters on the supposedly immutable product, and builders retained in fields beyond one assembly operation. Tests should cover omitted optional parts and contradictory steps, not merely prove that method chaining compiles.
Related
- Factory Method — product choice vs ordered assembly.
- Prototype — clone a tuned example vs build step by step.
- Order Pipeline — builder separates order assembly from payment variants.
Exercise
Add a summary step that counts rows. Leave existing builders compiling by defaulting the step.
Self-check
- Who enforces completeness?
Answer
The builder’s finish step — director runs steps, builder validates. - Builder vs Factory Method?
Answer
Builder assembles one complex object over steps; Factory Method picks which single product to return.
Factory Method
Intent
Let a parent define the steps of making something while children decide which exact kind to produce.
Motivation
A notifier sends alerts, but the channel varies: email needs an SMTP client, SMS needs a carrier gateway. If the alert code news up concrete senders, every new channel edits it. Factory Method keeps the alert flow fixed and pushes the “which sender” choice into small creator units — one per channel.
Structure
flowchart LR App[Alert App] --> Creator[Notifier Creator] Creator --> EmailCreator[Email Notifier Creator] Creator --> SmsCreator[SMS Notifier Creator] EmailCreator --> EmailSender[Email Sender] SmsCreator --> SmsSender[SMS Sender]
- Creator — declares the factory step and owns the alert flow.
- Concrete creators — Email/SMS creators that return their sender.
- Products — EmailSender, SmsSender with a shared send step.
Consequences
- Benefit: adding a channel adds a creator, never edits the alert flow.
- Cost: one creator type per product; simple one-off creation becomes heavier.
Basic Recap
Factory Method lets a creator defer construction of one collaborator to an overridable step. The creator keeps the surrounding workflow stable, while a subclass or supplied implementation chooses the concrete product. Callers use the product through a common interface rather than learning each constructor. The pattern separates a recurring process from the decision about which object that process needs.
Complex Scenario
A multi-tenant ingestion service validates and imports uploaded records with the
same job workflow, but each tenant supplies a different storage connector. An
ImportJob creator opens the upload, obtains a connector through
createConnector, normalizes records, and commits the batch. Connector creation
includes tenant credentials and endpoint selection, yet those details must not
leak into validation or batch accounting. The useful boundary is therefore one
connector per job, not an unconstrained object factory for every record.
Edge cases
- Concurrency: Two jobs for one tenant may create connectors simultaneously; connection-pool initialization must be safe, and job-specific cursors must not be shared between products.
- Retries: A retry after commit ambiguity must reuse the import idempotency key, while a fresh connector attempt must not reset the job’s source offset.
- Partial failure: If connector creation fails after credentials are opened, the creator must close temporary resources before reporting a retryable error.
Keep product selection separate from execution policy so the workflow can decide whether creation failure is retryable without understanding a vendor API.
Sketch (illustrative pseudocode, not runnable):
ImportJob.run(upload):
connector = this.createConnector(upload.tenant)
try:
validated = validate(upload.records)
result = connector.writeBatch(validated, upload.importKey)
return reconcile(result, upload.importKey)
finally:
connector.close()
TenantAJob.createConnector(tenant):
return ConnectorA(tenant.credentials, perJobPool())
TenantBJob.createConnector(tenant):
return ConnectorB(tenant.endpoint, tenant.credentials)
When to Use / When Not to Use
Use when:
- One flow works with several product kinds chosen at runtime or config time.
Avoid when:
- The product kind never varies or construction is a single
newwith no flow around it.
Examples
examples/elixir/factory-method/examples/dart/factory-method/examples/go/factory-method/examples/rust/factory-method/
Expected outcome: sending via email then SMS prints two lines naming each channel.
Anti-pattern / Failure Mode
-
Misuse: Hiding every
newbehind a creator hierarchy even when construction has no surrounding flow. -
Review signal: Constructors with no common product interface, or a factory chosen by a long type-switch.
-
Misuse symptom: Every simple
newis hidden behind a creator hierarchy, and adding a connector requires edits to job logic as well as a new subclass. The factory then adds indirection without protecting a stable workflow. -
Review signal: Look for constructors with no meaningful common product interface, factory methods selected by long type-switch statements, or tests that must instantiate the entire job hierarchy just to obtain one connector. Creation metrics that spike per record instead of per job also reveal a boundary drawn at the wrong granularity.
Related
- Abstract Factory — one product kind per creator vs a matching family.
- Builder — choose Builder when assembly needs ordered steps plus validation.
- Open/Closed — extend by adding creators, not editing the flow.
Exercise
Add a push-notification creator without touching the alert flow. Show the two-line output.
Self-check
- Who decides the concrete kind?
Answer
The concrete creator — the app asks the creator, never news the product directly. - Factory Method vs Abstract Factory?
Answer
Factory Method makes one product kind per creator; Abstract Factory makes families of related products.
Prototype
Intent
Copy a ready-made example instead of rebuilding the same setup from scratch.
Motivation
A game spawns dozens of goblins sharing base stats with small tweaks (one is faster, one hits harder). Constructing each through the full setup repeats asset loads and risks drift. A prototype keeps one tuned goblin and clones it, then adjusts only what differs.
Structure
flowchart LR Client --> Proto[Prototype Registry] Proto --> Goblin[Base Goblin] Goblin --> CloneA[Clone A: faster] Goblin --> CloneB[Clone B: stronger]
- Prototype — cloning contract returning an independent copy.
- Concrete prototype — base goblin knowing how to duplicate itself.
- Clones — copies tweaked after cloning without touching the original.
Adaptation note: in Elixir prefer copying immutable maps/structs; in Rust derive Clone; the lesson is clone-then-tweak, not a clone keyword.
Consequences
- Benefit: fast varied copies without rerunning heavy setup; new variants need no new classes.
- Cost: deep vs shallow copy mistakes; hidden sharing when nested state stays linked.
Basic Recap
Prototype creates a new object by copying a configured exemplar instead of rebuilding its state from scratch. The exemplar captures a useful starting point, and each clone receives the variations needed for its own use. The hard design decision is copy depth: immutable values can be shared, but mutable collaborators often need independent copies. A clone operation should make that ownership boundary explicit.
Complex Scenario
A document editor offers complex page templates containing nested text blocks, style objects, comment threads, and references to large image assets. Creating a page from a template should duplicate the editable block tree and comments while sharing immutable asset blobs. A prototype registry stores approved templates, and each clone receives fresh identifiers so later edits do not alter the exemplar. Simple field copying is unsafe because two pages would otherwise share mutable descendants.
Edge cases
- Memory pressure: Deep-copying every image blob multiplies memory use; content-addressed immutable assets should be shared, with reference lifetimes managed independently from the editable page tree.
- Concurrency: Two users cloning one template must not observe a temporary identifier remap or mutate shared clone bookkeeping.
- Partial failure: Failure while copying one nested object must discard the incomplete clone and any newly allocated native resources, leaving the source template untouched.
Use a copy context to preserve cycles and repeated references deliberately, rather than letting each object recursively clone without coordination.
Sketch (illustrative pseudocode, not runnable):
TemplateRegistry.instantiate(templateId, owner):
source = registry.approved(templateId)
context = CopyContext(idAllocator, memo = {})
draft = source.cloneUsing(context)
draft.owner = owner
draft.status = DRAFT
return draft
Page.cloneUsing(context):
copy = newPageSkeleton(freshId())
context.memo[this] = copy
copy.blocks = deepCopyMutable(blocks, context)
copy.assets = shareImmutableReferences(assets)
copy.comments = deepCopyMutable(comments, context)
return copy
When to Use / When Not to Use
Use when:
- Many similar objects differ slightly and setup is costly or repetitive.
Avoid when:
- Copies must stay linked to the original or construction is already trivial.
Examples
examples/elixir/prototype/examples/dart/prototype/examples/go/prototype/examples/rust/prototype/
Expected outcome: cloning a base goblin twice prints base plus two tweaked copies with independent stats.
Anti-pattern / Failure Mode
-
Misuse: Cloning shared mutable state so copies interfere with each other.
-
Review signal: Clones that need deep-copy fixes on every use — the prototype is not self-contained.
-
Misuse symptom: A generic clone method silently mixes shallow and deep copies, and prototypes are used mainly to avoid understandable constructors. Mutable caches, database sessions, or listeners accidentally survive cloning and connect the new object to the source’s lifetime.
-
Review signal: Check whether clone tests edit nested values in both objects and verify identity remapping. Fields copied by reflection without an explicit ownership policy, increasing resident memory after repeated clones, and source objects receiving clone events are all warning signs.
Related
- Builder — build fresh vs clone then tweak.
- Flyweight — share repeatable state vs copy a tuned example.
- Memento — snapshot for restore vs clone for reuse.
Exercise
Add a third clone with different health and prove editing it leaves the base unchanged.
Self-check
- Shallow vs deep copy risk?
Answer
Nested mutable parts may stay shared after a shallow copy; deep copy duplicates them. - Prototype vs Factory?
Answer
Prototype copies an existing instance; Factory builds a new one from parameters.
Singleton
Intent
Ensure one shared instance owns a resource and give every caller the same access point to it.
Motivation
An app writes audit events to a single log file. If each module opens its own writer, entries interleave, handles leak, and rotation breaks. A single coordinator that opens the file once and serializes writes removes that drift, but it only helps if every caller truly reaches the same coordinator.
Structure
flowchart LR CallerA --> GetInstance[Get Instance] CallerB --> GetInstance GetInstance --> Sole[The One Instance] Sole --> Resource[(Shared Resource)]
- Client callers — request the instance instead of building their own.
- Get Instance — single access point that creates once and returns the same handle.
- The One Instance — holds shared state and guards it.
- Shared Resource — file, registry, or connection pool behind the instance.
Adaptation note: in Elixir prefer a named GenServer or application config over a Java-style static holder; the lesson is single ownership, not a keyword.
Consequences
- Benefit: one place controls lifecycle, cleanup, and ordering of a shared resource.
- Cost: global reach hides dependencies, complicates tests, and invites overuse for things that should be passed explicitly.
Basic Recap
Singleton guarantees that one instance of a type exists within a defined scope and provides a common access point to it. It centralizes lifecycle and coordination for a resource whose independent copies would be incorrect. Its value comes from single ownership, not from making every dependency globally reachable. In practice, dependency injection, a process registry, or application composition can express the same constraint more explicitly.
Complex Scenario
An API gateway needs one process-wide token-bucket registry so all request handlers enforce the same per-client limits. Handlers may arrive on many worker threads, and creating a separate registry for each worker would multiply the allowed traffic. A singleton coordinator owns bucket creation, clock access, and cleanup, while the gateway’s composition root installs it during startup. Tests receive an explicitly scoped registry instead of resetting hidden production state.
Edge cases
- Concurrency: Lazy initialization must publish exactly one fully initialized coordinator; token updates also need atomicity, because single construction alone does not make the instance’s methods thread-safe.
- Memory pressure: Unlimited client keys grow buckets forever, so ownership includes expiry and capacity policy rather than merely shared access.
- Partial failure: If clock or persistent snapshot initialization fails, callers must not receive a partially usable singleton that later fails in unpredictable places.
Define what “one” means: per process, per tenant, per test, or per cluster. A process singleton cannot by itself enforce a distributed rate limit.
Sketch (illustrative pseudocode, not runnable):
Gateway.start(config):
registry = RateLimitRegistry.initializeOnce(
clock = config.clock,
snapshot = loadSnapshotOrFail(config.snapshot),
eviction = config.bucketEviction
)
router = Router(rateLimits = registry)
return Gateway(router)
Router.handle(request):
decision = rateLimits.take(request.clientKey, request.cost)
if decision.allowed:
return upstream(request)
return tooManyRequests(decision.retryAfter)
When to Use / When Not to Use
Use when:
- Exactly one coordinator must exist (log writer, ID allocator, device handle).
Avoid when:
- Callers could receive the dependency directly, tests need isolation, or lifetime differs per request.
Examples
examples/elixir/singleton/examples/dart/singleton/examples/go/singleton/examples/rust/singleton/
Expected outcome: two requests for the instance return the same identity and one write counter reaches 2.
Anti-pattern / Failure Mode
-
Misuse: A singleton as a global grab-bag for unrelated state.
-
Review signal: Tests that must reset global state between cases, or order-dependent suites.
-
Misuse symptom: Singleton becomes a service locator for configuration, repositories, loggers, and business services simply to avoid passing arguments. Tests then depend on execution order, and request code conceals its real collaborators behind static access.
-
Review signal: Watch for global
resethelpers in production paths, constructors replaced by static lookups, and mutable singleton fields without synchronization or eviction. A class called a singleton whose lifecycle is actually managed by a container should usually be injected as a normal scoped dependency instead.
Related
- Factory Method — one shared owner vs one product kind per creator.
- Test Isolation — singletons fight isolation; prefer injection.
- Dependency Inversion — depend on an abstraction, not the shared instance.
Exercise
Add a reset operation that clears the counter. Decide who may call it and document why it stays test-only.
Self-check
- How do you prove two callers share one instance?
Answer
Compare identity (same pid, same object hash, pointer equality, orOnceaddress) and observe shared counter. - Why is Singleton risky in tests?
Answer
Shared mutable state leaks between tests unless reset or injected. - What is the Elixir-idiomatic alternative?
Answer
A named GenServer or supervised process registered once, not a static field.
Structural Patterns
Part of the unified study index: Home · canonical comparisons in selection guide.
Structural patterns explain how objects and classes fit together into larger assemblies without tangling them. Where creational patterns handle making objects and behavioral patterns handle who does what, these seven handle how pieces connect.
- Adapter — translates one interface into another so old and new code cooperate.
- Bridge — splits controls from devices so each side grows independently.
- Composite — treats single items and groups through one contract for uniform trees.
- Decorator — wraps objects in combinable add-on layers without subclassing.
- Facade — offers one simple entry step over a multi-device routine.
- Flyweight — shares heavy repeated state so large collections stay cheap.
- Proxy — stands a lightweight stand-in in front of a costly object for lazy or guarded access.
Quick picker: mismatched interfaces → Adapter; two growing dimensions → Bridge; part-whole trees → Composite; combinable add-ons → Decorator; routine simplification → Facade; massive repetition → Flyweight; costly or guarded access → Proxy.
Adapter
Intent
Let a client written against one interface reuse a class built for a different interface by placing a translator between them, so neither side needs rewriting.
Motivation
A report sender knows a single step: print(doc). The office printer, however, is an older model that only understands old_print(text) with its own setup quirks. Rewriting the sender for one machine is wasteful, and replacing a working printer is expensive. An adapter offers the print(doc) shape the sender expects and forwards each call to the legacy machine in the form it understands, so the new code and the old device cooperate.
Structure
flowchart LR Client --> Target Target --> Adapter[Adapter] Adapter --> Adaptee[Adaptee]
- Client — the report sender; only knows the
print(doc)shape. - Target — the
print(doc)contract the client depends on. - Adapter — implements the target contract and translates each call for the old device.
- Adaptee — the legacy printer with the mismatched
old_print(text)step.
Consequences
- Benefit: existing, tested code gets reused through a new interface without editing either side.
- Cost / trade-off: one more layer to follow when debugging; translating awkward mismatches can add noticeable overhead or complexity.
Basic Recap
Adapter exposes the interface a client expects while translating calls and data to an incompatible collaborator. It allows existing code and a legacy or vendor component to cooperate without changing either one’s core model. Translation can include parameter shapes, error categories, and protocol details, but the client-facing contract must remain meaningful. An adapter is a boundary, not a new home for unrelated business workflow.
Complex Scenario
A warehouse fulfillment service reserves stock through a small InventoryPort,
but an acquired warehouse only offers a legacy SOAP client with compound keys
and numeric status codes. An InventoryAdapter converts the reservation command,
adds correlation metadata, invokes the client, and maps its reply into a domain
result. The fulfillment service continues to speak in stock units and reservation
identifiers. Vendor-specific throttling and XML remain confined to the boundary.
Edge cases
- Retries: A timeout may occur after the legacy system reserved stock; retry logic must send the same correlation key and query ambiguous outcomes before issuing another reservation.
- Partial failure: A reply containing accepted and rejected lines must not be flattened into one success boolean; the port needs an explicit partial result.
- Ordering: Status codes and line numbers may arrive out of request order, so results should be matched by stable line identifiers rather than list position.
The adapter may translate failure semantics, but it should not silently invent strong guarantees the legacy API cannot provide.
Sketch (illustrative pseudocode, not runnable):
InventoryAdapter.reserve(command):
legacyRequest = toLegacyLines(command)
legacyRequest.correlation = command.reservationKey
reply = legacyClient.reserveOrQuery(legacyRequest)
if reply.outcome == UNKNOWN:
return ReservationPending(command.reservationKey)
return ReservationResult(
accepted = mapByLineId(reply.accepted),
rejected = mapByLineId(reply.rejected),
reservationKey = command.reservationKey
)
When to Use / When Not to Use
Use when:
- A working class has the behavior you need but speaks a different interface than your client expects.
- You want to isolate third-party or legacy quirks behind your own interface.
Avoid when:
- Both sides are new and yours to design — agree on one interface instead of planning an adapter.
- The mismatch is behavioral, not just spelling — a translator cannot fix different meanings.
Examples
Links to runnable code (same scenario, four languages):
examples/elixir/adapter/examples/dart/adapter/examples/go/adapter/examples/rust/adapter/
Expected outcome: printing one document through the adapter shows the client call plus the legacy printer receiving it.
Anti-pattern / Failure Mode
-
Misuse: Wrapping everything in adapters instead of fixing the contract once.
-
Review signal: Chains of adapters translating between adapters.
-
Misuse symptom: The adapter grows allocation rules, pricing decisions, and orchestration for several systems until fulfillment behavior can only be understood by reading vendor translation code. Another misuse is adapting an interface mechanically while leaking its exceptions and sentinel values.
-
Review signal: Look for domain services importing legacy types, adapter methods with many unrelated responsibilities, or callers catching SOAP faults directly. Tests should include ambiguous replies and partial results; a suite that only verifies one-to-one field mapping misses the risky part of the seam.
Related
- Facade — fit an old interface vs simplify a subsystem.
- Proxy — different interface vs same interface with control.
- Postel’s Law — tolerant readers pair well with adapters.
Exercise
Add a second legacy device whose step is fax(number, text). Wrap it in a new adapter behind the same print(doc) contract (send to a fixed number) without touching the client. Both adapters must print their two lines.
Self-check
- Who owns the translation?
Answer
The adapter — the client keeps its interface and the adaptee keeps its implementation. - Adapter vs rewriting the old class: what changed?
Answer
The old class stays untouched; compatibility logic lives in a separate, replaceable unit. - When is an adapter the wrong fix?
Answer
When the two sides mean different things by the call — translation only bridges shape, not semantics.
Bridge
Intent
Split a control hierarchy from the device hierarchy it drives, so remotes and devices can each grow without forcing a new class for every combination.
Motivation
A shop sells two device brands — a Sony TV and an LG speaker — and two remotes — a basic remote and a mute remote. Encoding every pair as its own class (basic-remote-for-Sony, mute-remote-for-LG, and so on) means each new brand multiplies the remote code. The bridge keeps one remote side that delegates to a device contract, so adding a brand means writing one device, and adding a remote feature means writing one remote.
Structure
flowchart LR Basic[Basic Remote] --> Device Mute[Mute Remote] --> Device Device --> Sony[Sony TV] Device --> LG[LG Speaker]
- Abstraction (Basic Remote) — owns the power flow; delegates brand-specific steps to the device.
- Refined abstraction (Mute Remote) — extends the remote with a mute step, still delegating.
- Implementor (Device) — the shared brand contract (
turn_on,mute). - Concrete implementors — Sony TV and LG Speaker with brand-specific behavior.
Consequences
- Benefit: remotes and brands vary independently — one new unit per addition instead of a combination explosion.
- Cost / trade-off: an extra delegation layer; simple one-remote-one-device setups gain indirection they do not need.
Basic Recap
Bridge separates an abstraction’s user-facing behavior from the implementation mechanism it delegates to. The two sides can vary independently, avoiding a subclass for every combination of feature and platform. An abstraction defines the workflow, while an implementor supplies the primitive operations. Unlike an adapter, a bridge is usually designed up front around two dimensions that are expected to evolve.
Complex Scenario
A signing platform supports single-document and batch-signing workflows, and it
can use either a local hardware security module or a cloud signing provider. A
SigningFlow abstraction handles documents, user consent, and completion rules;
a Signer implementor performs provider-specific signing primitives. Adding a
new workflow should not require provider subclasses, and adding a provider
should not duplicate consent policy. The bridge boundary uses portable signing
requests and results rather than vendor response objects.
Edge cases
- Retries: Repeating a batch after a timeout must carry stable request keys; the flow can resume completed items without assuming every provider call was rolled back.
- Partial failure: Some documents may be signed before another fails, so the abstraction needs item-level status and a policy for acceptable partial completion.
- Concurrency: A flow object should not switch its signer mid-operation; concurrent jobs may use separate bridge instances with isolated credentials.
Keep orchestration above the bridge and primitive capabilities below it. Moving vendor-specific batch workflow into both sides erodes the independence.
Sketch (illustrative pseudocode, not runnable):
BatchSigningFlow.execute(documents, consent):
verifyConsent(consent)
results = ResultSet()
for document in documents:
request = portableRequest(document, consent.batchKey)
prior = results.completed(request.key)
if prior exists:
continue
outcome = signer.signOrResume(request)
results.record(document.id, outcome)
return summarize(results)
SingleSigningFlow.execute(document, consent):
verifyConsent(consent)
return signer.signOrResume(portableRequest(document, consent.key))
When to Use / When Not to Use
Use when:
- Two dimensions (controls × devices, views × renderers) would otherwise multiply into combined classes.
- Either side is expected to grow on its own release cycle.
Avoid when:
- Only one remote and one device exist with no growth foreseen — direct calls are simpler.
- The two sides never change independently; the split buys nothing.
Examples
Links to runnable code (same scenario, four languages):
examples/elixir/bridge/examples/dart/bridge/examples/go/bridge/examples/rust/bridge/
Expected outcome: a basic remote powers on the Sony TV and a mute remote silences the LG speaker.
Anti-pattern / Failure Mode
-
Misuse: Splitting one dimension that never varies into two hierarchies.
-
Review signal: Abstraction and implementation changing in lockstep anyway.
-
Misuse symptom: Every abstraction method is a one-line pass-through to an identical implementor method, and the two hierarchies always change together. The bridge then doubles types without separating genuine axes of variation.
-
Review signal: Watch for parallel class names added in lockstep, vendor types crossing the implementor interface, and conditionals in the abstraction that select provider behavior. Tests should combine each flow with each signer through contracts rather than requiring a bespoke test class for every pair.
Related
- Adapter — grow both sides independently vs fit one side to the other.
- Strategy — vary implementation of one step vs vary both dimensions.
- Composition over Inheritance — the principle behind the split.
Exercise
Add a Philips TV device (no remote edits) and a sleep-timer remote that wraps any device. Both new units must work with the existing opposite side untouched.
Self-check
- What does the remote hold?
Answer
A reference to the device contract, not a concrete brand — it delegates brand steps. - Bridge vs Adapter: what differs?
Answer
Bridge is designed up front to separate two growing dimensions; Adapter retrofits one fixed mismatch. - When does Bridge pay off?
Answer
When either dimension grows — each addition costs one unit, not a full cross-product.
Composite
Intent
Treat single items and groups of items through one shared contract, so client code handles a whole tree the same way it handles one leaf.
Motivation
A backup tool must total the size of a small file tree: a root folder holds file-a (100 KB) and a subfolder docs holding file-b (250 KB). Special-casing files versus folders at every step litters the code with type checks, and each new grouping rule edits them all. The composite gives files and folders one size step — a file returns its own size, a folder sums its children — so totaling the tree is one uniform call.
Structure
flowchart TD Client --> Node[Entry Contract] Node --> File[File Leaf] Node --> Folder[Folder Composite] Folder --> Node
- Component (Entry) — the shared contract with a
sizestep. - Leaf (File) — a single item; reports its own size.
- Composite (Folder) — holds child entries and sums their sizes recursively.
- Client — calls
sizeonce, unaware whether it holds a file or a folder.
Consequences
- Benefit: tree operations stay uniform — new operations and deeper nesting need no client branching.
- Cost / trade-off: the shared contract can leak odd steps onto leaves (a file has no children); keeping every node honest takes discipline.
Basic Recap
Composite represents individual objects and groups of objects behind one common component interface. Clients perform an operation on a whole structure without constantly testing whether they hold a leaf or a container. A composite typically forwards work to its children and combines their results. The model fits true whole-part hierarchies; shared children, cycles, and cross-links need additional rules rather than pretending every graph is a tree.
Complex Scenario
A CI runner models a pipeline as stages, sequential groups, and parallel groups.
The scheduler can request execution, cancellation, or a status summary through
the same PipelineComponent interface at any depth. Leaves run individual jobs,
while composites coordinate their children and reduce job outcomes into a group
outcome. This lets a nested optional test suite behave like any other stage from
the scheduler’s perspective.
Edge cases
- Ordering: Sequential groups must stop or continue after failure according to an explicit policy, while dependency links between branches must not be mistaken for ordinary parent-child containment.
- Concurrency: Parallel groups need bounded fan-out and cancellation that reaches running descendants without corrupting the shared result reducer.
- Partial failure: A group with cancelled, failed, and successful children must preserve each outcome instead of returning an ambiguous single failure.
Traversal needs a visited set if the configuration format permits reused nodes; otherwise a cycle turns one uniform call into unbounded recursion.
Sketch (illustrative pseudocode, not runnable):
ParallelGroup.run(context):
children.ready(context).forEach(scheduleWithLimit)
for completion in completions:
outcomes.record(completion.childId, completion.result)
if policy.shouldCancel(completion.result):
context.cancelRemaining()
return reduceOutcomes(outcomes, policy)
JobLeaf.run(context):
return runner.execute(this.jobSpec, context.cancellation)
Pipeline.status():
return root.summarizeUsing(visited = {})
When to Use / When Not to Use
Use when:
- Data forms a part-whole tree (files, menus, org charts) and clients should treat one item and a group alike.
- Operations like size, render, or export must recurse without client-side type checks.
Avoid when:
- The structure is flat or leaves and groups need wholly different operations — the shared contract becomes misleading.
- Ordering or distinct child roles matter more than uniform treatment.
Examples
Links to runnable code (same scenario, four languages):
examples/elixir/composite/examples/dart/composite/examples/go/composite/examples/rust/composite/
Expected outcome: listing the tree contents and printing the total size of 350 KB.
Anti-pattern / Failure Mode
-
Misuse: Forcing leaf and container to share operations that make no sense for leaves.
-
Review signal: Leaves throwing ‘unsupported’ for half the interface.
-
Misuse symptom: Leaf classes inherit meaningless child-management methods, or every caller still downcasts components to discover what they can do. A composite is also misused when a many-to-many dependency graph is forced into a parent-child tree to obtain recursive convenience.
-
Review signal: Look for
isGroupbranches in client code, empty add/remove implementations on leaves, and recursive operations with no cycle or depth protection. Production traces that lose child failures behind one group error indicate that uniform treatment has erased necessary diagnostic detail.
Related
- Decorator — uniform trees vs combinable wrappers.
- Iterator — walk the tree without exposing storage.
- Visitor — add operations over the structure without editing it.
Exercise
Add a count step returning the number of files in a subtree (folders count 0 themselves). Root must report 2 without any client branching on file versus folder.
Self-check
- Where does the recursion live?
Answer
In the folder composite — it callssizeon each child, which recurses for subfolders. - What does the client skip?
Answer
Type checks — it calls one step on the contract and never asks file-or-folder. - When is Composite wrong?
Answer
When leaves and groups share no meaningful operation; forcing one contract then confuses both.
Decorator
Intent
Wrap an object in add-on layers that extend its description and cost, keeping the base untouched and add-ons freely combinable.
Motivation
A cafe sells black coffee for $2, with milk and sugar as add-ons. Baking every combination into subclasses (milky coffee, sweet coffee, milky-sweet coffee) explodes with each new extra, and editing the base for every topping risks breaking the plain drink. A decorator wraps any coffee: milk adds its label and price around the inner drink, sugar does the same, so plain and loaded drinks share one composable chain.
Structure
flowchart LR Client --> Drink[Coffee Contract] Drink --> Plain[Black Coffee] Drink --> Milk[Milk Add-on] Drink --> Sugar[Sugar Add-on] Milk --> Drink Sugar --> Drink
- Component (Coffee) — the shared drink contract with description and cost steps.
- Concrete component (Black Coffee) — the plain $2 base drink.
- Decorators (Milk, Sugar) — hold an inner coffee and extend its description and cost.
Consequences
- Benefit: add-ons combine in any order at runtime with no subclass explosion; the base never changes.
- Cost / trade-off: long chains are harder to inspect than one flat object, and order-sensitive add-ons can surprise.
Basic Recap
Decorator adds behavior around an object while preserving the interface callers already use. Decorators can be layered, so independent capabilities such as metrics, authentication, or caching compose without a subclass for every stack. Each wrapper normally delegates to an inner component and contributes work before or after that call. Composition order becomes part of the behavior and must be designed rather than treated as incidental wiring.
Complex Scenario
An internal HTTP client starts with a minimal transport and is decorated with authentication, retries, caching, and metrics. Application services see only the standard client interface regardless of the stack selected for an endpoint. The team must decide whether retries sit outside authentication so refreshed headers are generated per attempt, and whether metrics measure each attempt or the whole logical request. Those semantics come from wrapper placement, not from the base transport.
Edge cases
- Retries: A retry decorator inside a cache may bypass caching on later attempts, while one outside it may repeat cache failures; the desired behavior needs an explicit sequence.
- Concurrency: Reusing one decorator with per-request mutable fields can mix headers and timing data, so request state belongs in invocation context.
- Partial failure: A response received before a metrics backend fails should not turn into a failed business request unless observability is deliberately made mandatory.
A composition root should name the full stack and document its order instead of letting each module add another invisible wrapper.
Sketch (illustrative pseudocode, not runnable):
transport = HttpTransport()
attempts = MetricsDecorator(
AuthDecorator(transport, tokenSource),
scope = PER_ATTEMPT
)
logical = MetricsDecorator(
RetryDecorator(attempts, retryPolicy),
scope = PER_REQUEST
)
client = CacheDecorator(logical, cachePolicy)
response = client.send(request)
# Authentication is refreshed per attempt; request metrics surround retries.
When to Use / When Not to Use
Use when:
- Features layer onto a base in arbitrary combinations chosen at runtime.
- You want to extend behavior without subclassing or editing the base.
Avoid when:
- Combinations are fixed and few — plain variants or parameters are clearer than chains.
- Add-on order silently changes meaning and callers cannot be trusted to order correctly.
Examples
Links to runnable code (same scenario, four languages):
examples/elixir/decorator/examples/dart/decorator/examples/go/decorator/examples/rust/decorator/
Expected outcome: the plain coffee prints at $2 and the milk-plus-sugar drink prints at $3.
Anti-pattern / Failure Mode
-
Misuse: Stacking decorators until no one knows the effective behavior.
-
Review signal: Order-dependent decorator stacks with surprising interactions.
-
Misuse symptom: Critical business rules hide in long wrapper stacks, and changing one decorator’s position silently changes security or consistency. Decorators that expose new required methods also force callers to downcast, defeating transparent substitution.
-
Review signal: Look for anonymous chains assembled in several places, decorators with different interface behavior, and tests that exercise only one wrapper at a time. Duplicate metric counts, surprising cache hits, and authentication traces with stale tokens are operational clues that ordering assumptions were never made explicit.
Related
- Composite — wrappers vs trees.
- Proxy — add duties vs control access to the same interface.
- Open/Closed — extend behavior without editing the component.
Exercise
Add a whipped-cream decorator costing $2. A black coffee with cream must print $4, and stacking cream twice must print $6, with no edits to existing add-ons.
Self-check
- Where does the extra price live?
Answer
In each decorator — it adds its own amount around the inner drink’s cost. - Decorator vs subclassing: what changed?
Answer
Combinations compose at runtime by nesting instead of being frozen as classes. - What is the main debugging risk?
Answer
Deep chains hide which layer contributed what; order and identity get harder to trace.
Facade
Intent
Offer one simple entry step that sequences a handful of subsystem steps, so callers start a complex job without learning each device.
Motivation
Movie night needs three gadgets driven in order: dim the lights, lower the screen, then play picture with sound. Every viewer who drives the projector, screen, and speakers directly must remember the order and each device’s quirks, and guests simply give up. A home-theater facade exposes one start_movie step that runs the dim-lower-play sequence, so the living room behaves like one machine.
Structure
flowchart LR Viewer --> Theater[Home Theater Facade] Theater --> Lights Theater --> Screen Theater --> Sound
- Facade (Home Theater) — owns the
start_moviesequence and hides device order. - Subsystems (Lights, Screen, Sound/Projector) — each performs its own single step.
- Client (Viewer) — calls one step instead of coordinating three devices.
Consequences
- Benefit: the common path becomes one memorable call; subsystem ordering lives in exactly one place.
- Cost / trade-off: the facade can hide power features — unusual sequences still need direct subsystem access.
Basic Recap
Facade offers a focused entry point to a set of subsystem operations. It captures a common coordination sequence so clients do not need to know every collaborator or low-level detail. The subsystems remain available for specialized use, and the facade does not have to hide them completely. Its purpose is a simpler boundary for a recurring task, not universal ownership of all application behavior.
Complex Scenario
A customer account service provides an AccountClosure facade for a support
workflow. Closing an account involves identity sessions, active subscriptions,
ledger holds, data-export eligibility, and an audit record. Support code calls
one operation and receives a structured closure status instead of coordinating
five APIs. The facade establishes the required sequence and translates subsystem
results into a consistent decision about what still needs attention.
Edge cases
- Partial failure: Subscriptions may be cancelled before the ledger rejects closure; the result must record completed work and required compensation rather than pretending the whole operation rolled back.
- Retries: A repeated request should use the same closure key so session revocation and cancellation are resumed or safely recognized as already done.
- Concurrency: Two support agents closing one account need a version check or per-account lock to prevent contradictory decisions based on stale balances.
A distributed facade coordinates progress; it is not automatically a transaction. A durable workflow may be needed when closure must survive process restarts.
Sketch (illustrative pseudocode, not runnable):
AccountClosure.close(accountId, requestKey):
progress = closureJournal.beginOrResume(accountId, requestKey)
assertAccountVersionUnchanged(progress)
progress.runStep(revokeSessions)
progress.runStep(cancelSubscriptions)
ledgerDecision = progress.runStep(releaseEligibleHolds)
if ledgerDecision.blocked:
return ClosureBlocked(progress.completedSteps, ledgerDecision)
progress.runStep(writeAuditRecord)
return ClosureCompleted(progress.id)
When to Use / When Not to Use
Use when:
- One routine sequence covers most callers and subsystem order is easy to get wrong.
- You want a stable entry point while subsystems keep evolving underneath.
Avoid when:
- Callers mostly need custom orders or fine-grained control — the facade becomes a pass-through they bypass.
- The “simplification” keeps growing until it mirrors every subsystem knob.
Examples
Links to runnable code (same scenario, four languages):
examples/elixir/facade/examples/dart/facade/examples/go/facade/examples/rust/facade/
Expected outcome: one start_movie call prints the dim, lower, and play steps in order.
Anti-pattern / Failure Mode
-
Misuse: A facade that grows every subsystem method — a new god object.
-
Review signal: Callers bypassing the facade because it hides what they need.
-
Misuse symptom: Every subsystem call and every business rule migrates into one facade until it becomes a god service with hundreds of dependencies. Callers then bypass it unpredictably because its broad contract no longer matches any focused task.
-
Review signal: Watch for unrelated methods sharing one facade, constructor lists that continually grow, and tests requiring the entire subsystem graph for a simple branch. Closure dashboards that report only success or failure, with no durable step progress, reveal that the friendly API is concealing partial completion rather than managing it.
Related
- Adapter — simplify vs translate.
- Mediator — one call driving a subsystem vs peers talking through a hub.
- API Consistency — facades should stay uniform.
Exercise
Add a shut_down step that reverses the sequence (stop playback, raise screen, brighten lights). Callers must still use one call, and the start order must stay unchanged.
Self-check
- What does the facade own?
Answer
The ordering and coordination of subsystem steps — not the device behavior itself. - Facade vs Adapter: what differs?
Answer
Facade simplifies many steps into one; Adapter translates one interface into another. - When should callers bypass it?
Answer
For unusual sequences or fine control the single routine does not cover.
Flyweight
Intent
Share one copy of heavy repeated state across many small objects, keeping per-item data tiny so large collections stay cheap.
Motivation
A text view renders 1000 glyphs, but only two font styles appear: bold and italic. Storing a full font description inside every glyph repeats the same heavy data a thousand times and bloats memory. A flyweight factory keeps one shared record per style and hands the same record to every glyph using it, so 1000 glyphs reference just 2 shared styles and reuse the font data 998 times.
Structure
flowchart LR View --> Factory[Style Factory] Factory --> Bold[Shared Bold Style] Factory --> Italic[Shared Italic Style] View --> Glyph[Glyph x1000] Glyph --> Bold Glyph --> Italic
- Flyweight (Font Style) — the shared, heavy, reusable state.
- Factory — hands out one record per style and reuses it on repeat requests.
- Context (Glyph) — a lightweight item holding its position plus a reference to a shared style.
- Client (View) — requests styles through the factory instead of building new copies.
Consequences
- Benefit: memory drops sharply when shared state dominates and repeats — 1000 glyphs cost 2 style records.
- Cost / trade-off: shared records must stay unchangeable (or carefully guarded); splitting shared from per-item state adds design effort.
Basic Recap
Flyweight reduces memory use by sharing immutable state common to many small objects. The shared intrinsic state lives in a flyweight, while varying extrinsic state is supplied by the context or caller. A factory usually interns flyweights by a value key so equivalent requests receive the same instance. Correctness depends on keeping shared objects immutable and separating identity from the reusable representation.
Complex Scenario
A logistics dashboard renders hundreds of thousands of vehicle markers on map
tiles. Markers share icon images, color palettes, and label fonts, but each has a
different position, heading, and vehicle identifier. An IconStyleFactory
returns one immutable style per visual key, and lightweight marker contexts hold
only dynamic values. Rendering passes the extrinsic state to the shared style
instead of storing a full icon and font description in every vehicle.
Edge cases
- Memory pressure: An unbounded style cache can recreate the problem it was meant to solve, especially when keys include tenant-specific colors; capacity and eviction must account for native image resources.
- Concurrency: Simultaneous requests for one style should not leak duplicate native allocations, and publishing a style must happen only after it is fully decoded.
- Partial failure: If an icon cannot load, markers need a bounded fallback style rather than caching a broken object forever or retrying once per marker.
Profile before applying the pattern: shared keys and object lifetime determine whether flyweights save memory or merely add cache coordination.
Sketch (illustrative pseudocode, not runnable):
styleKey = StyleKey(iconHash, paletteId, fontId)
style = styles.intern(styleKey, factory = loadImmutableStyle)
Marker.render(canvas):
style.draw(
canvas,
position = this.position,
rotation = this.heading,
label = this.vehicleId
)
Styles.evictWhenOverBudget():
removeUnreferencedStyles()
releaseNativeImagesForRemovedEntries()
When to Use / When Not to Use
Use when:
- Many items repeat a small set of heavy states (glyphs, tiles, particles with shared textures).
- Shared state can be kept immutable and looked up cheaply.
Avoid when:
- Items barely repeat — the factory and lookup cost outweigh the savings.
- The “shared” state keeps changing per item, forcing copies anyway.
Examples
Links to runnable code (same scenario, four languages):
examples/elixir/flyweight/examples/dart/flyweight/examples/go/flyweight/examples/rust/flyweight/
Expected outcome: rendering 1000 glyphs reports 2 shared styles and the reuse count.
Anti-pattern / Failure Mode
-
Misuse: Sharing state that is rarely repeated, adding lookup cost for no gain.
-
Review signal: Shared state mutated through one user affecting others.
-
Misuse symptom: Vehicle position, selection, or other mutable state is put into the shared style to make drawing calls shorter, causing unrelated markers to change together. Another symptom is interning values that are almost never equal, producing a large cache with little actual reuse.
-
Review signal: Look for setters on flyweights, cache keys containing unique request data, and factory dictionaries without eviction or concurrency tests. Memory profiles should distinguish shared intrinsic bytes from the growing key and context population; an object-count reduction alone is not proof of a smaller heap or native footprint.
Related
- Prototype — share repeatable state vs clone a tuned copy.
- Singleton — one shared owner vs many shared values.
- Bounded Resource — share to bound memory.
Exercise
Add a third style (underline) used by 50 of the glyphs. The factory must still hold exactly 3 shared records, and the reuse count must update accordingly.
Self-check
- What is shared vs per-glyph?
Answer
Font style records are shared; each glyph keeps only its own position and a style reference. - Why must shared state stay immutable?
Answer
One edit would leak into every glyph using that record — sharing requires stability. - When does Flyweight lose?
Answer
When states rarely repeat; then the cache saves little and adds lookup overhead.
Proxy
Intent
Stand a lightweight stand-in in front of a costly object so loading, access, or bookkeeping happens only when actually needed.
Motivation
A gallery shows thumbnails for large photos. Loading every full image up front stalls the page, yet skipping the load breaks the display step callers expect. An image proxy offers the same display step, loads the real file on the first view, and serves later views from its cached copy — so scrolling back is instant and the disk is touched exactly once.
Structure
flowchart LR Gallery --> Photo[Photo Contract] Photo --> Proxy[Image Proxy] Photo --> Real[Real Image] Proxy --> Real
- Subject (Photo) — the shared display contract.
- Real subject (Real Image) — the costly file load plus display.
- Proxy — holds the same contract, loads the real image lazily on first display, caches afterward.
- Client (Gallery) — displays through the contract, unaware of the lazy load.
Consequences
- Benefit: expensive work is deferred and done once — startup stays fast and repeats are free.
- Cost / trade-off: first access still pays full price (a visible pause), and caching adds staleness risk if the file changes.
Basic Recap
Proxy stands in for another object while preserving its interface, adding a reason for indirection such as lazy loading, access control, remote access, or resource management. Clients can use the proxy as they would the real subject, subject to the proxy’s documented failure and lifecycle behavior. The real subject may be created or contacted only when needed. Transparency has limits: network errors and initialization cost cannot always be hidden honestly.
Complex Scenario
An ORM session returns a proxy for a customer’s large preference document rather than fetching it with every customer row. The proxy exposes the same document methods and loads the real value on first property access. Authorization is checked before the fetch, and successful initialization is reused within the session. This delays expensive work, but the boundary between an in-memory property and a database operation must remain visible to performance tooling.
Edge cases
- Concurrency: Two threads accessing an uninitialized proxy should trigger at most one load, or use an explicit single-flight policy, without publishing a partially filled document.
- Partial failure: Access after the session closes cannot lazy-load; the proxy should report that lifecycle error rather than opening a hidden session.
- Retries: Retrying a timed-out query must be bounded and must not discard an already committed initialization while another caller is consuming it.
Initialization failure should leave a coherent state that either permits a controlled retry or consistently reports the same terminal failure.
Sketch (illustrative pseudocode, not runnable):
DocumentProxy.read(field):
assertSessionOpen()
assertReadAllowed(currentPrincipal)
document = loader.loadOnce(documentKey)
return document.read(field)
Loader.loadOnce(key):
if initialized:
return realDocument
return singleFlight(key, function:
loaded = repository.fetchDocument(key) # bounded policy
publishAtomically(loaded)
return loaded
)
When to Use / When Not to Use
Use when:
- Construction or loading is costly and often unnecessary (large images, remote resources).
- You need access control, counting, or caching around an object without changing its callers.
Avoid when:
- The object is cheap — the stand-in adds indirection for no gain.
- Freshness matters more than speed and cached copies would silently go stale.
Examples
Links to runnable code (same scenario, four languages):
examples/elixir/proxy/examples/dart/proxy/examples/go/proxy/examples/rust/proxy/
Expected outcome: the first display loads the file from disk; the second display is served from cache.
Anti-pattern / Failure Mode
-
Misuse: A proxy that duplicates the subject’s logic instead of delegating.
-
Review signal: Proxies stacked so latency and failure modes are opaque.
-
Misuse symptom: Proxies surround every property and repository call, making routine object access perform hidden queries, authorization changes, or remote retries. Lazy proxies returned beyond their session lifetime turn ordinary reads into unpredictable runtime failures.
-
Review signal: Watch for interfaces whose proxy adds surprising checked failures, double-checked initialization without safe publication, and loops that touch one lazy property per entity. Query counts growing with row count, repeated load exceptions, and closed-session errors are strong operational evidence that the proxy boundary is being ignored.
Related
- Decorator — control access vs add duties.
- Adapter — same interface with control vs translated interface.
- Zero Trust — verify on every access, including through proxies.
Exercise
Add an access check: displaying a photo named private.png must print a denial line and never load the file, while normal photos keep the load-once behavior.
Self-check
- When does the disk get touched?
Answer
Once, on the first display through the proxy — later displays use the cache. - Proxy vs Decorator: what differs?
Answer
Proxy manages access to the real object (lazy load, cache); Decorator adds features around it. - What is the staleness risk?
Answer
If the underlying file changes, the proxy keeps serving its cached copy unless invalidated.
Behavioral Patterns
Part of the unified study index: Home · canonical comparisons in selection guide.
How objects talk, share work, and evolve over time. All behavioral pages follow the same template: intent, a concrete scenario, structure diagram, trade-offs, usage guidance, runnable examples, an exercise, and a self-check.
Members
- Strategy — swap one step of an algorithm at runtime by delegating to a chosen variant.
- Chain of Responsibility — pass a request along handlers until one claims it.
- Command — package requests as objects so they can be queued, logged, and undone.
- Interpreter — evaluate tiny languages with composable expression objects.
- Iterator — traverse a collection without exposing its storage.
- Mediator — route peer messages through one hub instead of a mesh.
- Memento — snapshot private state for later restore without exposing it.
- Observer — broadcast one subject’s changes to many subscribers.
- State — change behavior with internal status by delegating to the active state.
- Template Method — fix an algorithm’s skeleton, let subclasses vary steps.
- Visitor — add operations over stable element types without editing them.
Confusable trio
| Question | Strategy | State | Template Method |
|---|---|---|---|
| Who picks the active variant? | The caller, at wiring time | The object itself, as status evolves | Nobody at runtime — the subclass fixed at build time |
| How does it change? | Swap the delegated object | Transition between state objects | Override the primitive step |
| Varies what? | One whole step implementation | Behavior per status plus transitions | One step inside a fixed skeleton |
| Use the shop example | Checkout picks card vs cash | Player moves stopped → playing → paused | CSV vs PDF share fetch/save, differ in format |
Rule of thumb: caller picks → Strategy; status evolves → State; skeleton fixed with one open step → Template Method.
Chain of Responsibility
Intent
Pass a request along a chain of handlers until one of them handles it, so the sender never picks the receiver directly.
Motivation
A help desk gets tickets with severity 1, 2, or 3. Level 1 staff solve easy tickets, level 2 takes harder ones, and the manager takes the rest. Hard-coding “if severity then route” in the ticket form means every staffing change edits the form. Chaining handlers instead lets each level either resolve the ticket or forward it, and the form just hands the ticket to the head of the chain.
Structure
flowchart LR Client[Client Ticket Form] --> L1[Level1 Handler] L1 --> L2[Level2 Handler] L2 --> Mgr[Manager Handler]
- Client — submits the request to the head of the chain only.
- Handler (Level1, Level2, Manager) — checks whether it can handle the request; handles it or forwards to the next link.
- Successor link — each handler holds the next handler; the tail either handles everything or reports failure.
Consequences
- Benefit: sender and receivers stay decoupled; the chain can be reordered or extended without touching the sender.
- Cost: a request can fall off the end unhandled, and long chains are harder to trace when debugging.
Basic Recap
Chain of Responsibility passes a request along a sequence of handlers, allowing one to handle it, transform it, or forward it. The sender knows the entry point rather than the eventual handler, and the chain can be assembled for a context. Handlers share a contract but retain independent decisions. The design needs a clear termination rule and a defined outcome when nobody accepts the request.
Complex Scenario
A content publishing platform runs submitted posts through moderation handlers for malformed input, spam scoring, privacy checks, legal holds, and final acceptance. Each handler can reject, annotate and forward, or escalate for human review. Editorial teams configure different chains for comments and long-form articles without teaching the upload endpoint about every rule. The request carries a submission identifier and collected findings so later handlers can make decisions without repeating earlier work.
Edge cases
- Ordering: Running privacy redaction after spam analysis may be intentional, but reversing legal escalation and acceptance could publish held content; chain order must be validated and visible.
- Retries: Re-entering the chain after a transient model failure must not duplicate audit events or charge twice for completed external checks.
- Partial failure: If an optional spam provider is unavailable but legal screening is mandatory, each handler needs an explicit fail-open or fail-closed policy rather than one chain-wide guess.
An unhandled or exhausted chain should return a typed outcome, not silently accept the content by falling off the end.
Sketch (illustrative pseudocode, not runnable):
ModerationChain.submit(post):
context = ModerationContext(post, findings = {})
outcome = firstHandler.handle(context)
return outcome # Accepted, Rejected, or NeedsReview; never implicit null
Handler.handle(context):
checkpoint = journal.completed(context.submissionId, this.name)
if not checkpoint:
checkpoint = this.evaluate(context)
journal.record(context.submissionId, this.name, checkpoint)
return route(checkpoint, nextHandler, terminalPolicy)
When to Use / When Not to Use
Use when:
- More than one unit could handle a request and the right one depends on runtime data like severity.
- The set or order of handlers changes often.
Avoid when:
- Exactly one receiver is known at send time, or every request must be guaranteed handled by a specific unit.
Examples
examples/elixir/chain-of-responsibility/examples/dart/chain-of-responsibility/examples/go/chain-of-responsibility/examples/rust/chain-of-responsibility/
Expected outcome: a severity-2 ticket passes Level1 and is handled at Level2, printing two lines.
Anti-pattern / Failure Mode
-
Misuse: A chain where no handler claims the request and the drop is silent.
-
Review signal: Requests falling through with no observability on who saw them.
-
Misuse symptom: A fixed routing table is turned into a long mutable chain, and developers must debug every handler to discover why a request disappeared. Handlers that both perform business side effects and secretly rebuild their successors make behavior depend on invocation history.
-
Review signal: Look for handlers returning null when they decline, missing terminal handlers, runtime link mutation, and no tests for exhausted chains. Dashboards should expose the last completed handler and final outcome; a spike in requests with neither indicates that flexibility has removed accountability.
Related
- Command — pass along vs package as an object.
- Mediator — chain vs hub routing.
- Complete Mediation — check on every access in the chain.
Exercise
Add a severity-3 ticket that reaches the manager. Then add a severity-9 ticket and decide: should the tail print “unhandled”, or should the manager handle anything? Document your choice.
Self-check
- Who picks the final handler?
Answer
No one up front — each handler decides locally to handle or forward, so the receiver emerges from the chain walk. - What happens with no willing handler?
Answer
The request exits the tail unhandled unless you add a default handler or an explicit failure report. - Chain vs Strategy: what differs?
Answer
Strategy picks one variant up front; Chain tries handlers in order until one claims the request.
Command
Intent
Wrap each request as an object holding everything needed to run it, so calls can be queued, logged, and undone.
Motivation
A TV remote has on, off, and undo buttons. Wiring the remote directly to lamp circuits means every new device rewrites the remote. Turning each press into a command object — one for “light on”, one for “light off” — lets the remote store, replay, and reverse presses without knowing what a light is.
Structure
flowchart LR Remote[Remote Invoker] --> Cmd[Command] Cmd --> OnCmd[LightOn Command] Cmd --> OffCmd[LightOff Command] OnCmd --> Light[Light Receiver] OffCmd --> Light
- Invoker (Remote) — holds commands and triggers them; keeps history for undo.
- Command (LightOn, LightOff) — packages one request plus its undo step.
- Receiver (Light) — the device that actually does the work when a command runs.
Consequences
- Benefit: requests become storable values — queueable, loggable, replayable, and undoable.
- Cost: one small class per action; simple calls gain indirection that can feel heavy.
Basic Recap
Command turns a request into an object containing the action and the data needed to perform it. Invokers can queue, schedule, log, or route commands without knowing receiver details. Receivers implement the actual work, while command handlers connect the two. Undo is possible only when the domain offers a real inverse or compensation; storing an object does not automatically make its effects reversible.
Complex Scenario
A deployment platform represents scale, restart, and configuration-change requests as commands placed on a durable work queue. The API validates and serializes intent, the scheduler chooses a worker, and a handler invokes the infrastructure receiver. Operators can inspect pending requests and cancel work that has not started. Each command carries a stable identifier, target version, and authorization context captured at submission time.
Edge cases
- Retries: Queue redelivery after worker failure must not scale a service twice, so handlers use idempotency records or reconcile actual target state.
- Ordering: A restart submitted before a configuration change may be invalid after it; target versions and per-target sequencing prevent stale commands from overtaking newer intent.
- Memory pressure: A durable backlog should store compact payloads and claim work in batches rather than loading every pending command into worker memory.
A user-facing undo operation should issue a new compensating command with its own policy and audit record, not blindly replay mutable receiver state. Queue persistence also needs an explicit retention policy for authorization data and payloads that may contain sensitive configuration.
Sketch (illustrative pseudocode, not runnable):
worker.claimBatch(limit):
for command in batch:
if command.targetVersion < currentVersion(command.target):
markSuperseded(command)
continue
execution = executions.beginOrLoad(command.id)
if not execution.completed:
result = registry.handler(command.type).handle(command)
executions.completeOnce(command.id, result)
acknowledgeAfterDurablyRecording(command)
When to Use / When Not to Use
Use when:
- Actions need undo, redo, queuing, scheduling, or logging.
- The sender of a request should not depend on the receiver’s type.
Avoid when:
- Every call is fire-and-forget with no history need — a plain function call is simpler.
Examples
examples/elixir/command/examples/dart/command/examples/go/command/examples/rust/command/
Expected outcome: pressing on prints the light is ON, then undo prints it is OFF again.
Anti-pattern / Failure Mode
-
Misuse: Commands as glorified function calls with no queue, log, or undo need.
-
Review signal: Command classes with one method that only forwards — indirection without benefit.
-
Misuse symptom: One command class contains a giant type switch and all receiver logic, recreating procedural dispatch behind a fashionable name. Serializing live services, credentials, or open connections into queued commands is another failure that makes replay unsafe.
-
Review signal: Look for commands without stable identifiers, handlers with non-idempotent external calls, and
undomethods that assume external systems have not changed. Queue metrics should distinguish duplicate delivery from new submissions; a lack of execution records makes retries impossible to audit.
Related
- Memento — commands plus snapshots enable undo.
- Strategy — requests as objects vs swappable steps.
- Order Pipeline — commands separate payment variants from refunds.
Exercise
Add a dim command that sets brightness to 50 and undoes back to the previous level. Store enough prior state in the command to make undo exact.
Self-check
- Where does undo knowledge live?
Answer
In each command object, which captures the prior state or the inverse action — not in the remote or the light. - What does the invoker know about the receiver?
Answer
Nothing — it only knows the command interface, so new devices plug in without touching the remote. - Command vs Strategy: what differs?
Answer
Strategy swaps one step of an algorithm; Command packages a full request with context so it can be stored and reversed later.
Interpreter
Intent
Define a tiny language as composable expression objects, each able to evaluate itself in a shared context.
Motivation
A settings page lets power users type rules like “3 + x” where x is a live value. A tangle of string splits and special cases breaks the moment subtraction or nesting appears. Modeling each piece — numbers, variables, plus — as an expression that evaluates itself turns parsing into assembly and evaluation into one recursive call.
Structure
flowchart LR Client[Client] --> Expr[Expression] Expr --> Num[Number] Expr --> Var[Variable] Expr --> Add[Add] Add --> Expr Client --> Ctx[Context x=4]
- Context — holds variable bindings (here x = 4) every expression can read.
- Abstract Expression — the shared evaluate contract.
- Terminal expressions (Number, Variable) — leaves with no children.
- Nonterminal expression (Add) — combines child expressions and evaluates them.
Consequences
- Benefit: each grammar rule is one small unit; extending the language means adding a unit, not rewriting a parser.
- Cost: class count grows per rule, and interpretation is slower than compiled code — unsuitable for large or hot languages.
Basic Recap
Interpreter represents the grammar of a small language as expressions that can be evaluated in a context. Terminal expressions read values or constants, and nonterminal expressions combine child expressions according to language rules. Parsing builds the expression tree; evaluation interprets it without embedding language-specific branches throughout the client. This suits a bounded grammar, not the accidental creation of an unmaintainable general-purpose language.
Complex Scenario
A fraud review service lets analysts write a restricted rules language such as
amount > limit and country in allowedCountries. A parser produces an abstract
syntax tree, a validator checks fields and types, and expressions evaluate
against one transaction context. Approved trees are cached so repeated decisions
do not repeatedly parse the same rule text. Analysts can change rules without
deploying the decision service, but they cannot execute arbitrary host code.
Edge cases
- Concurrency: Immutable expression trees may be shared across evaluations, while transaction values and random or clock inputs must remain in a separate per-request context.
- Memory pressure: Rule caching needs size limits, and deep or very wide expressions require depth and node-count validation before recursive evaluation exhausts the stack.
- Partial failure: A missing risk-provider value should yield an explicit unknown or policy-driven outcome instead of being coerced to zero or false.
Evaluation must be deterministic within the supplied context, with a clear three-valued comparison policy if unknown values are part of rule decisions.
Sketch (illustrative pseudocode, not runnable):
AndExpression.evaluate(context):
left = leftExpression.evaluate(context)
if left == FALSE:
return FALSE
right = rightExpression.evaluate(context)
return threeValuedAnd(left, right)
RuleEngine.decide(transaction):
tree = ruleCache.getOrParse(ruleId, ruleText, limits)
validator.assertApproved(tree)
context = EvaluationContext(transaction, providerValues)
return tree.evaluate(context).toDecision(policy)
When to Use / When Not to Use
Use when:
- The language is tiny and stable (config rules, simple filters, demo arithmetic).
- You want evaluation logic next to each rule for readability.
Avoid when:
- The grammar is large, performance matters, or a real parser library already exists — use a parser instead.
Examples
examples/elixir/interpreter/examples/dart/interpreter/examples/go/interpreter/examples/rust/interpreter/
Expected outcome: evaluating “3 + x” with x = 4 prints 7.
Anti-pattern / Failure Mode
-
Misuse: A full language where a data table or existing parser would do.
-
Review signal: Grammar changes forcing edits across every expression class.
-
Misuse symptom: New operators, statements, variables, and exceptions are added until a homemade interpreter becomes an untested programming language. Evaluating raw strings as host-language code to escape grammar maintenance is a severe security failure, not a convenient extension.
-
Review signal: Watch for expression classes that perform I/O, mutable variables stored in shared tree nodes, recursive evaluation with no depth guard, and grammar changes without parser and validation tests. If domain rules need full language tooling, use an established sandbox or embed a deliberately selected rules engine instead.
Related
- Visitor — evaluate a tiny language vs add operations over a structure.
- Composite — expression trees are composites.
- KISS — prefer the smallest language that works.
Exercise
Add a Subtract expression and evaluate “10 - x” with x = 4. Then add Multiply and check “3 + x * 2” — decide whether your parser handles precedence or evaluates left to right, and document it.
Self-check
- Where do variables get their values?
Answer
From the shared Context object passed into every evaluate call, not from the expression nodes themselves. - Terminal vs nonterminal: what differs?
Answer
Terminal nodes are leaves (a number or variable lookup); nonterminal nodes hold child expressions and combine their results. - When should you NOT use Interpreter?
Answer
For a big or fast language — grammar growth explodes class count and tree-walking is slow; reach for a parser generator.
Iterator
Intent
Walk through a collection’s items one by one without exposing how the collection stores them.
Motivation
A music app keeps a playlist internally as a list, but the player screen should not depend on that choice — tomorrow the storage could become a stream or a paged cache. Giving the playlist its own traversal object lets the screen ask “first song, next song, done?” while the list stays private and free to change.
Structure
flowchart LR Client[Player Client] --> It[Playlist Iterator] It --> Songs[Playlist Collection] Songs --> S1[Song A] Songs --> S2[Song B] Songs --> S3[Song C]
- Collection (Playlist) — owns the items and creates iterators; never hands out the raw list.
- Iterator — tracks position and answers first/next/done.
- Client (Player) — consumes items through the iterator only.
Consequences
- Benefit: traversal logic lives in one place; the collection can change storage and support several simultaneous walks.
- Cost: a tiny extra object per traversal; trivial for in-memory lists but worth noting.
Basic Recap
Iterator provides sequential access to elements without exposing the underlying collection’s representation. It encapsulates traversal state and offers a common way to advance and detect completion. Collections can therefore support arrays, trees, streams, or remote pages behind a consistent consumption model. An iterator is not automatically a snapshot or a transaction; its consistency and resource lifetime must be stated separately.
Complex Scenario
An audit service streams security events from a database cursor to an export worker. The iterator requests pages as needed and exposes each event in a stable format, so the exporter neither loads the full table nor constructs SQL. A cursor token records the last event key, and the iterator owns the cursor’s closure. Consumers can process days of history with bounded memory while the storage engine continues to optimize page access.
Edge cases
- Ordering: New inserts and updates during traversal can duplicate or skip events unless the query uses a keyset cursor and a defined high-water mark or snapshot.
- Partial failure: A failed page request should preserve the last committed cursor; after bounded retries, the iterator must close resources and surface the failure rather than silently ending the export.
- Memory pressure: Fetching the next page must be bounded and backpressured, because prefetching aggressively can recreate the full-table memory problem.
Completion should mean the defined range is exhausted, not that one transient page request happened to fail.
Sketch (illustrative pseudocode, not runnable):
AuditIterator.next():
if buffer.empty:
if finished:
return End
page = fetchPageAfter(cursor, highWaterMark, pageLimit)
buffer = page.events
cursor = page.nextCursor
finished = page.exhausted
return buffer.removeFirst()
Export.run(iterator):
try:
while iterator.hasNext:
event = iterator.next()
sink.append(event)
finally:
iterator.close()
When to Use / When Not to Use
Use when:
- Callers must visit every item but must not depend on storage details or index math.
- You need multiple traversal styles (forward, shuffle, filtered) over one collection.
Avoid when:
- The collection is a plain list nobody hides, and callers already iterate it directly with no pain.
Examples
examples/elixir/iterator/examples/dart/iterator/examples/go/iterator/examples/rust/iterator/
Expected outcome: the three playlist songs print in order without the client touching the raw list.
Anti-pattern / Failure Mode
-
Misuse: An iterator that exposes the storage it was meant to hide.
-
Review signal: Callers depending on iteration order that was never promised.
-
Misuse symptom: Iterator becomes an excuse to expose mutable internals or to hide unbounded network work behind a seemingly cheap
nextcall. Methods such ashasNextthat advance the cursor create duplicates and make ordinary loops unreliable. -
Review signal: Look for offset pagination over changing data, page failures mapped to end-of-stream, iterators without close operations, and traversal state shared between consumers. Export metrics should include pages fetched, retry counts, and the final cursor so a truncated file cannot be mistaken for a successful complete traversal.
Related
- Composite — walk trees uniformly.
- Observer — pull iteration vs push broadcasts.
- Information Hiding — the principle behind the curtain.
Exercise
Add a shuffle iterator that visits the same three songs in a different fixed order. The player code must work unchanged with either iterator.
Self-check
- What stays hidden from the client?
Answer
The storage shape and indexing — the client only sees first/next/done, never the underlying list. - How do two simultaneous walks coexist?
Answer
Each walk gets its own iterator object with its own position, both reading the same collection. - Why not just expose the list?
Answer
Exposing it locks the storage choice and lets callers mutate or index it; the iterator keeps one traversal contract while storage evolves.
Mediator
Intent
Route all communication between peers through one hub object so peers never reference each other directly.
Motivation
A chat room has users who message each other. If every user holds a pointer to every other user, adding, removing, or muting someone touches the whole mesh. A room hub that receives each message and forwards it to the right recipient collapses that mesh into spokes: users know the room, the room knows the users.
Structure
flowchart LR Alice[Alice User] --> Room[Chat Room Mediator] Bob[Bob User] --> Room Room --> Alice Room --> Bob
- Colleagues (Alice, Bob) — send and receive through the mediator; hold no peer references.
- Mediator (Chat Room) — owns the directory and the routing rules; delivers each message.
Consequences
- Benefit: peers stay simple and swappable; routing, muting, and logging rules live in one auditable place.
- Cost: the hub can grow into a god object if every rule piles in — split routing from policy when it swells.
Basic Recap
Mediator centralizes interactions among a set of colleagues so they communicate through a coordinator rather than holding references to one another. Each colleague focuses on its own capability and reports relevant events or requests. The mediator decides how capabilities collaborate for a shared workflow. This reduces a mesh of dependencies, but it also concentrates workflow knowledge that must be kept explicit and testable.
Complex Scenario
An order fulfillment coordinator mediates inventory, payment, shipment, and customer-notification components. Inventory reports reservation results to the mediator, which decides when payment capture can proceed and when shipment instructions are allowed. Components do not call one another directly or infer the overall order state. The mediator records workflow progress and emits notifications only after meaningful fulfillment transitions.
Edge cases
- Partial failure: Payment may succeed after inventory reserved but before shipment creation fails; the mediator needs a durable recovery path and a compensation decision instead of simply returning an exception.
- Retries: Redelivered colleague events must be deduplicated by event and order identifiers so payment capture and notifications happen once logically.
- Concurrency: Reservation and cancellation events can arrive concurrently; order versioning or serialized processing prevents the mediator from acting on an obsolete state.
The mediator should coordinate domain transitions, while colleagues retain the rules and technical details of their own operations.
Sketch (illustrative pseudocode, not runnable):
FulfillmentMediator.on(event):
if eventJournal.alreadyHandled(event.id):
return
order = orders.lockAndLoad(event.orderId)
transition = workflow.decide(order, event)
for action in transition.actions:
actionJournal.dispatchOnce(action.key, action)
orders.saveWithVersion(order, transition.newVersion)
eventJournal.markHandled(event.id)
Inventory.onReserved(result):
mediator.on(InventoryReserved(result.orderId, result.lines))
When to Use / When Not to Use
Use when:
- A mesh of peers manages each other directly and changes ripple everywhere.
- Routing rules (who hears what) deserve one visible owner.
Avoid when:
- Only two peers talk on a fixed path — a direct call is clearer than a hub.
Examples
examples/elixir/mediator/examples/dart/mediator/examples/go/mediator/examples/rust/mediator/
Expected outcome: Alice and Bob exchange two messages, each routed visibly through the room.
Anti-pattern / Failure Mode
-
Misuse: A mediator that becomes the god object holding all peer logic.
-
Review signal: Peers that can only be tested through the full mediator mesh.
-
Misuse symptom: The mediator absorbs validation, pricing, database access, vendor protocols, and every new feature until colleagues are anemic wrappers. Direct colleague calls then reappear for exceptions, producing both a god mediator and the original tangled mesh.
-
Review signal: Watch for a mediator with many unrelated event types, mutable workflow state not persisted across restarts, and colleagues importing one another’s implementation classes. Tests should replay duplicate and out-of-order events; dashboards need durable workflow steps rather than one opaque
processOrderduration.
Related
- Observer — hub routing vs broadcasts.
- Facade — peers through a hub vs one call for a subsystem.
- Chat Router — mediator screening with reversible moderation.
Exercise
Add a third user plus a mute rule: messages from muted senders never deliver. Keep all routing logic inside the room — users must not check mute lists themselves.
Self-check
- What do colleagues know about each other?
Answer
Nothing — each colleague only knows the mediator, which resolves recipients. - Where does a mute rule live?
Answer
In the mediator, so policy changes touch one hub instead of every user. - Mediator vs Observer: what differs?
Answer
Observer broadcasts one-to-many with no routing logic; Mediator peers talk many-to-many and the hub decides who gets what.
Memento
Intent
Capture an object’s state as a sealed snapshot so it can be restored later without exposing its internals.
Motivation
A text editor types freely but must undo back to an earlier draft. Letting the undo stack poke at the editor’s buffers couples history to editing guts. A snapshot object that the editor fills and later replays lets history store opaque drafts while only the editor reads them.
Structure
flowchart LR Editor[Editor Originator] --> Snap[Snapshot Memento] Keeper[History Caretaker] --> Snap Editor --> Keeper
- Originator (Editor) — creates snapshots of itself and restores from them; the only one that reads snapshot contents.
- Memento (Snapshot) — an opaque saved state; exposes nothing to outsiders.
- Caretaker (History) — stores and returns snapshots without inspecting them.
Consequences
- Benefit: undo works without breaking encapsulation; the caretaker never learns the originator’s internals.
- Cost: snapshots consume memory — cap history depth or store deltas for large states.
Basic Recap
Memento captures an object’s state so it can be restored later without exposing the object’s internal representation to caretakers. The originator creates and interprets its snapshots, while a caretaker stores and retrieves them. This preserves encapsulation and supports features such as undo or checkpointing. A memento records internal state, not every external effect the originator may have caused since the snapshot.
Complex Scenario
A visual infrastructure editor lets engineers rearrange a deployment graph, edit node settings, and undo several changes before publishing. The graph originator creates versioned mementos containing its internal layout and configuration, and the history caretaker retains a bounded stack. Publishing to cloud infrastructure remains a separate operation. Restoring a draft therefore changes only the editor model and never claims to undeploy resources.
Edge cases
- Memory pressure: Full deep snapshots of a large graph can exhaust memory; structural sharing or deltas can help, but history must remain immutable and size limits must be explicit.
- Concurrency: Restoring an old memento while another user has saved a newer draft requires a version check or merge decision, not silent last-writer-wins.
- Partial failure: Deserialization may fail midway because a plugin is missing; restore should validate into a temporary model and swap only after the complete snapshot is usable.
The memento format needs schema versioning and secret handling if snapshots leave process memory or survive application upgrades.
Sketch (illustrative pseudocode, not runnable):
GraphEditor.capture():
return Memento(
schemaVersion = CURRENT,
baseVersion = this.version,
state = immutableCopy(this.internalGraph)
)
History.restore(snapshot):
candidate = GraphEditor.fromValidatedSnapshot(snapshot)
if snapshot.baseVersion != currentSavedVersion:
return Conflict(requiresMerge = true)
editor.replaceModelAtomically(candidate)
editor.notifyDraftChanged() # no infrastructure deployment
When to Use / When Not to Use
Use when:
- Users need undo, rollback, or checkpoints over state you want to keep private.
- Snapshot/restore must not couple history code to internal fields.
Avoid when:
- State is huge and copied often, or callers legitimately need structured access — prefer explicit save/load or commands storing deltas.
Examples
examples/elixir/memento/examples/dart/memento/examples/go/memento/examples/rust/memento/
Expected outcome: typing extends the draft, a snapshot is kept, and restore prints the earlier text.
Anti-pattern / Failure Mode
-
Misuse: Snapshots taken so often that memory grows without a restore need.
-
Review signal: Mementos exposing internals they were meant to encapsulate.
-
Misuse symptom: Caretakers read and modify memento fields, turning the snapshot into a public duplicate of the model. Capturing database sessions, listeners, credentials, or entire service graphs makes restore unsafe and breaks the boundary the pattern is meant to protect.
-
Review signal: Look for mementos serialized without version or sensitivity policy, unbounded undo stacks, and restore methods that mutate the live model before validation completes. Claims that undo reverses emails, payments, or deployments are a product-level warning that internal snapshots are being confused with external compensation.
Related
- Command — snapshots make undo safe.
- Prototype — restore later vs clone now.
- Deterministic Testing — snapshots help reproduce failures.
Exercise
Keep two snapshots and add undo-twice support. Then cap history at depth 1 and document which restore now fails and why.
Self-check
- Who may read a snapshot’s contents?
Answer
Only the originator that made it — the caretaker stores and returns it blindly. - Memento vs Command for undo: what differs?
Answer
Memento restores saved state snapshots; Command replays inverse actions. Snapshots are simpler but heavier. - What bounds memory use?
Answer
History depth caps, delta snapshots, or discarding redo branches on new edits.
Observer
Intent
Let one subject broadcast updates to any number of subscribers without knowing who they are.
Motivation
An online order changes status to “shipped” and both email and SMS services must react. Calling each notifier directly from the order wires the order to every channel — adding push means editing order code. Letting notifiers subscribe to the order and receive a broadcast keeps the order focused on status while channels come and go freely.
Structure
flowchart LR Order[Order Subject] --> E[Email Observer] Order --> S[SMS Observer] E --> Order S --> Order
- Subject (Order) — keeps the subscriber list and broadcasts each status change.
- Observers (Email, SMS) — register themselves and react when notified; never polled.
Consequences
- Benefit: subjects and channels evolve independently; adding a channel means adding a subscriber, not editing the subject.
- Cost: broadcast order is loose and cascading updates can surprise — document whether notification is synchronous and reentrancy-safe.
Basic Recap
Observer establishes a one-to-many notification relationship in which a subject announces changes without depending on concrete subscribers. Observers register interest and react through a common notification contract. The subject owns the change and subscription mechanism, while observers own their responses. Delivery semantics—synchronous or queued, ordered or unordered, at-most-once or at-least-once—are additional design choices, not guarantees supplied by the pattern name.
Complex Scenario
A warehouse telemetry subject publishes equipment temperature changes to an alerting observer, a search indexer, and a maintenance predictor. New analytical consumers can subscribe without modifying sensor ingestion. A local event bus dispatches durable event envelopes containing equipment identity, sequence, and event identifier. Alert delivery remains isolated from indexing cost so a slow analytical observer cannot block ingestion of every reading.
Edge cases
- Ordering: Observers that require equipment chronology consume per-equipment sequences and detect gaps; global ordering across all equipment is unnecessary and expensive.
- Retries: At-least-once delivery repeats events after acknowledgements are lost, so alert observers deduplicate and index writes are idempotent.
- Partial failure: One failing observer is isolated in its own subscription and dead-letter path rather than preventing unrelated observers from progress.
- Memory pressure: Slow consumers need bounded queues and backpressure or discard policies instead of an ever-growing pending-event list.
The event record should describe a fact already committed, not expose a mutable subject that observers can alter during notification.
Sketch (illustrative pseudocode, not runnable):
TelemetryIngest.onReading(reading):
event = eventStore.append(reading, nextEquipmentSequence)
bus.publishDurably(event)
Subscription.dispatchLoop():
batch = queue.receiveBounded()
for event in batch:
result = observer.handle(event)
if result.succeeded:
checkpoint.advance(event.id)
else:
retryPolicy.scheduleOrDeadLetter(event, result)
When to Use / When Not to Use
Use when:
- One state change must reach many unknown or changing parties (status feeds, UI refresh, alerts).
- Subscribers should attach and detach at runtime.
Avoid when:
- Only one fixed receiver exists, or update order and exactly-once delivery are critical — prefer direct calls or a queue.
Examples
examples/elixir/observer/examples/dart/observer/examples/go/observer/examples/rust/observer/
Expected outcome: one order-status change notifies both the email and SMS channels.
Anti-pattern / Failure Mode
-
Misuse: Broadcasts where every follower mutates shared state during notification.
-
Review signal: Update storms from cascaded notifications with no ordering guarantees.
-
Misuse symptom: The subject synchronously calls observers that perform email, database writes, and further publications on its critical path. Observer lists become hidden business orchestration, and notification cycles recursively trigger the same changes.
-
Review signal: Look for strong references that prevent unsubscribe, mutable events, observers throwing through the publisher, and no documented ordering or retry contract. Rising pending-queue depth, repeated event IDs, and latency tied to the slowest subscriber are operational signs that the simple pattern needs an explicit delivery architecture.
Related
- Mediator — broadcasts vs hub routing.
- Event-Driven — in-process broadcast vs broker-decoupled services.
- Backpressure — bound fan-out under load.
Exercise
Add a push notifier, then unsubscribe SMS and re-broadcast. Confirm only email and push react, with no edit to the order’s broadcast logic.
Self-check
- Who holds the subscriber list?
Answer
The subject — observers only register and react, they never track each other. - Push vs pull updates: what differs?
Answer
Push sends the new state inside the notification; pull sends “changed” and observers query back. The example pushes the status line. - Observer vs Mediator: what differs?
Answer
Observer is one-to-many broadcast with no routing; Mediator is many-to-many with the hub choosing recipients.
State
Intent
Let an object change its behavior when its internal status changes, by delegating each request to its current state object.
Motivation
A music player behaves differently stopped, playing, and paused: pressing play from stopped starts the track, from paused it resumes, and pressing pause while stopped does nothing. A nest of status flags in the player turns every button into a branch maze. Giving each status its own object — stopped, playing, paused — lets the player delegate the press to whichever state is active, and transitions become explicit moves between states.
Structure
flowchart LR Player[Player Context] --> St[State] St --> Stopped[Stopped] St --> Playing[Playing] St --> Paused[Paused] Stopped --> Playing Playing --> Paused Paused --> Playing
- Context (Player) — holds the current state and forwards button presses to it.
- State — the shared press-handling contract.
- Concrete states (Stopped, Playing, Paused) — implement presses for that status and trigger transitions.
Consequences
- Benefit: each status’s rules live alone; transitions are explicit and new states plug in cleanly.
- Cost: more small classes, and transitions scattered across states can be hard to survey — keep a transition list in the docs.
Basic Recap
State lets an object alter its behavior by delegating to an object representing its current state. Each state defines which events are valid and which transitions follow, while the context holds shared data and the current state. This replaces scattered conditionals about lifecycle status with localized behavior. State differs from Strategy because transitions belong to the object’s lifecycle rather than a caller freely selecting an algorithm.
Complex Scenario
A deployment controller moves through draft, awaiting-approval, executing, completed, failed, and rolling-back states. Approval is meaningful only while awaiting approval, retry is allowed only under a failure policy, and cancellation has different effects before and after execution begins. Each state handles controller events and returns explicit transitions plus actions. The controller persists its state and version so other services observe one coherent lifecycle.
Edge cases
- Concurrency: Approval and cancellation arriving together must be serialized by a version check or per-deployment lock; both transitions cannot commit from the same starting version.
- Ordering: A delayed worker-started event after cancellation is stale and should be recorded or rejected according to policy, not blindly accepted.
- Retries: Duplicate approval or completion events need idempotent handling so notification and infrastructure actions are not repeated.
Side effects should be emitted as durable actions tied to a committed transition; running them inside an in-memory state object can leave state and reality apart.
Sketch (illustrative pseudocode, not runnable):
DeploymentController.handle(event):
current = store.loadForUpdate(this.id)
decision = current.state.handle(current, event)
if decision.invalid:
return rejectionWithCurrentState(current)
store.commitIfVersionMatches(current.version, decision.nextState)
actionOutbox.appendAll(decision.actionKeys, decision.actions)
return acceptedTransition(decision)
AwaitingApproval.handle(context, Approve):
requireApproverRole(Approve.actor)
return Transition(EXECUTING, actions = [StartWorkerOnce(context.id)])
When to Use / When Not to Use
Use when:
- Behavior depends on internal status with explicit allowed transitions (players, orders, connections).
- Status-flag branches are spreading through many methods.
Avoid when:
- Behavior is picked once by the caller rather than evolving internally — that is Strategy, not State.
Examples
examples/elixir/state/examples/dart/state/examples/go/state/examples/rust/state/
Expected outcome: pressing play then pause prints each state change in order.
Anti-pattern / Failure Mode
-
Misuse: A state machine with two states and no transitions — an enum would do.
-
Review signal: Transition logic scattered across states instead of owned explicitly.
-
Misuse symptom: State objects coexist with public status flags and ad hoc assignments elsewhere, so behavior and stored status disagree. A state class that directly performs long network calls also turns lifecycle decisions into untestable side-effect bundles.
-
Review signal: Watch for transition logic duplicated in controllers, states reaching into unrelated services, and events accepted without checking the current version. Logs showing impossible transitions or repeated action keys indicate that the abstraction exists but the transition boundary is not atomic or idempotent.
Related
- Strategy — object transitions itself vs caller injects the variant.
- Template Method — status-driven behavior vs fixed skeleton.
- Explicit State Ownership — one owner per state.
Exercise
Add a “stop” action returning to Stopped from either Playing or Paused. Then make pause-from-Stopped print “already stopped” instead of changing state.
Self-check
- Who triggers transitions?
Answer
The concrete state objects (or the context on their instruction) — transitions ride on behavior, not on external if-chains. - State vs Strategy: what differs?
Answer
Strategy’s variant is chosen by the caller; State’s active variant changes itself as the object’s status evolves. - Where is the transition map?
Answer
Distributed across state objects here; for many states, centralize it in a table on the context instead.
Strategy
Intent
Package each variant of one step behind a common interface so the caller can swap variants at runtime without rewriting its flow.
Motivation
A shop checkout totals an order the same way every time, but payment differs: card talks to a gateway, cash just opens a drawer, wallet calls a phone API. Branching inside the order code for each method grows brittle — every new method edits the same function and risks breaking the others. Strategy moves each payment into its own unit and lets the order hold whichever one is selected.
Structure
flowchart LR Order[Order Context] --> Pay[PayMethod Strategy] Pay --> CardPay[Card Payment] Pay --> CashPay[Cash Payment] Pay --> WalletPay[Wallet Payment]
- Context (Order) — owns the flow and the currently chosen method; delegates the pay step.
- Strategy (PayMethod) — the shared payment step contract.
- Concrete strategies — CardPay, CashPay, WalletPay with distinct steps.
Consequences
- Benefit: new methods plug in without editing order flow; each method stays testable alone.
- Cost: more small units to discover; caller must still choose correctly, which can push selection logic elsewhere.
Basic Recap
Strategy encapsulates interchangeable algorithms behind one contract and lets a context delegate the varying step. Selection occurs through configuration, request attributes, or composition rather than a growing conditional inside the workflow. Each strategy should honor compatible inputs, outputs, and failure semantics. The pattern separates algorithm choice from orchestration, but it does not decide which choice is safe for a given situation.
Complex Scenario
A distributed API gateway enforces request limits using fixed-window,
sliding-window, and token-bucket strategies behind a LimitAlgorithm interface.
The limiter context loads a client’s current state, delegates the decision, and
returns a common allow-or-throttle result with retry metadata. Administrators
select an algorithm per route without modifying request handling. Shared state
storage and concurrency requirements are part of the strategy contract, not an
afterthought hidden in each implementation.
Edge cases
- Concurrency: Simultaneous requests can all pass if read-modify-write state updates are not atomic, even though each strategy works in a single-threaded test.
- Retries: A client retry is another request and normally consumes budget; internal gateway retries need a clear rule about whether they re-enter the strategy.
- Partial failure: If the shared state store is unavailable, the context must apply a route-specific fail-open or fail-closed policy and report degraded enforcement.
- Memory pressure: High-cardinality client keys require expiry and bounded local caches regardless of the chosen algorithm.
Strategies may return different diagnostic details, but the context must normalize them without weakening the common decision contract.
Sketch (illustrative pseudocode, not runnable):
RateLimiter.check(request):
policy = policies.forRoute(request.route)
key = policy.clientKey(request)
result = policy.algorithm.consumeAtomically(key, request.cost, clock.now)
return Decision(result.allowed, result.retryAfter, policy.name)
Gateway.handle(request):
try:
decision = limiter.check(request)
except StateStoreUnavailable:
decision = degradedDecisionFor(request.route)
return forward(request) if decision.allowed else throttle(decision)
When to Use / When Not to Use
Use when:
- Multiple variants of one step swap at runtime or per configuration.
- You want to test each variant without running the whole flow.
Avoid when:
- Only one variant exists and none is foreseen, or variants differ in flow shape rather than one step.
Examples
examples/elixir/strategy/examples/dart/strategy/examples/go/strategy/examples/rust/strategy/
Expected outcome: paying $100 by card then by cash prints two distinct lines with the same total.
Anti-pattern / Failure Mode
-
Misuse: A strategy interface with one implementation and no expected variants.
-
Review signal: Callers switching on type tags instead of injecting the variant.
-
Misuse symptom: Strategies have subtly incompatible contracts, and the context grows type checks to compensate for different result shapes or state requirements. Introducing separate strategy classes for trivial one-line branches can also obscure behavior without enabling real interchange.
-
Review signal: Look for selection strings scattered through request code, algorithms with different retry or atomicity assumptions, and tests that never exercise strategies under contention. A configurable strategy name accepted without validation can turn a small extension point into an unsafe runtime dependency lookup.
Related
- State — caller picks vs object transitions.
- Template Method — inject the step vs subclass it.
- Order Pipeline — strategies isolate payment variants.
Exercise
Add a wallet method that charges a $1 fee. Total must still print $101 for wallet and $100 for others. Do not edit the order flow file beyond registering the new method.
Self-check
- Who owns variant selection?
Answer
The caller/Context wiring, not the strategies — strategies only execute. - Strategy vs if-else: what changed?
Answer
Branching moved from inline conditionals to polymorphic delegation; adding a method adds a unit instead of editing a function. - When would State fit better?
Answer
When the object itself changes behavior as its internal status evolves, not when the caller picks a method.
Template Method
Intent
Fix the skeleton of an algorithm in a base unit and let subclasses vary only specific steps.
Motivation
Monthly reports export through identical steps — fetch data, format it, save the file — but CSV and PDF format differently. Copying the whole pipeline per format duplicates fetch and save and lets them drift. A base exporter that owns the step order and leaves only the format step open keeps one pipeline with two interchangeable endings.
Structure
flowchart LR Base[Report Base] --> Fetch[fetch data] Fetch --> Format[format - varies] Format --> Save[save file] Format --> CSV[CSV Export] Format --> PDF[PDF Export]
- Abstract base (Report) — owns the template: the fixed step order and shared steps.
- Primitive step (format) — the one step subclasses override.
- Concrete exports (CSV, PDF) — fill in only the varying step.
Consequences
- Benefit: shared steps are written once; the step order is enforced so variants cannot skip stages.
- Cost: the base dictates structure — an odd variant that needs a different order fights the template (consider Strategy instead).
Basic Recap
Template Method defines the skeleton of an algorithm in a base operation and leaves selected steps to subclasses or hook implementations. The invariant sequence remains in one place, while variable details are supplied through primitive operations. Callers invoke the template rather than assembling the steps themselves. The base class therefore controls extension points and must make preconditions, resource ownership, and hook ordering clear.
Complex Scenario
A data synchronization framework defines runSync as open checkpoint, extract,
transform, load, and finalize. Vendor integrations implement extraction and
optional transformation, while the base template consistently handles telemetry,
checkpoint progression, and resource cleanup. A failed load can resume from the
last durable checkpoint without rerunning an entire day of extraction. New
connectors override a small set of documented steps instead of copying the
synchronization loop.
Edge cases
- Partial failure: A checkpoint written before data is durably loaded can skip records after a crash, so checkpoint advancement belongs after confirmed load and inside a well-defined consistency boundary.
- Retries: A retry may repeat an ambiguous load, making idempotent merge keys necessary even if the template itself runs the same sequence.
- Ordering: Optional hooks such as schema validation must run at a fixed, documented point; letting subclasses reorder finalization can bypass cleanup.
Prefer narrow hooks over allowing every step to be replaced. A template that no longer guarantees its invariant sequence offers little value.
Sketch (illustrative pseudocode, not runnable):
SyncTemplate.runSync():
resources = acquireResources()
try:
checkpoint = checkpoints.load(syncKey)
batch = extract(checkpoint) # required primitive
prepared = transform(batch) # optional hook
receipt = loadIdempotently(prepared, checkpoint.token)
checkpoints.advanceAfter(receipt.durable)
finalizeSuccess(receipt)
finally:
releaseResources(resources)
Connector.transform(batch):
return batch # default, deliberately optional
When to Use / When Not to Use
Use when:
- Several variants share the same step order and differ in one or two steps.
- You want the framework to enforce the pipeline while users plug in details.
Avoid when:
- Variants need different step orders or wholly different flows — prefer Strategy or composition.
Examples
examples/elixir/template-method/examples/dart/template-method/examples/go/template-method/examples/rust/template-method/
Expected outcome: CSV and PDF exports each print their shared steps with their own format stage.
Anti-pattern / Failure Mode
-
Misuse: A skeleton with every step overridable — subclasses can break the invariant.
-
Review signal: Deep template hierarchies where the fixed part keeps changing.
-
Misuse symptom: Subclasses override nearly the entire algorithm, call hooks in a different order, or must know undocumented base-class fields to work. Deep inheritance chains make a small change in the base silently alter every integration.
-
Review signal: Watch for public calls that bypass the template and invoke primitive steps directly, empty hooks with surprising required behavior, and base methods whose contracts exist only in implementation comments. Connector tests should verify crash points around loading and checkpointing, not just a successful happy-path sequence.
Related
- Strategy — subclass the step vs inject it.
- Report Generator — template isolates report jobs across workers.
- Composition over Inheritance — prefer injection when the skeleton churns.
Exercise
Add an HTML exporter that varies only the format step. Then try adding one that also needs an extra “chart” step — note where the template resists and what you would change.
Self-check
- Who controls the step order?
Answer
The base template method — subclasses fill steps but never reorder them. - What may a subclass change?
Answer
Only the designated primitive steps (here: format); shared steps stay inherited untouched. - Template Method vs Strategy: what differs?
Answer
Template fixes the skeleton and varies steps by inheritance; Strategy swaps the whole step by delegation at runtime.
Visitor
Intent
Add new operations to a family of shapes without editing the shapes, by moving each operation into a visitor object the shapes accept.
Motivation
A drawing holds circles and squares. Area math lives naturally with each shape, but each new report — export, pricing, validation — would force every shape file open for edits. Letting shapes accept a visitor and call back into it flips the dependency: new operations arrive as new visitors, and shapes only keep one stable accept method.
Structure
flowchart LR Client[Client] --> V[Shape Visitor] V --> Area[Area Visitor] V --> Export[Export Visitor] Circle[Circle Element] --> V Square[Square Element] --> V
- Elements (Circle, Square) — hold their own data and expose one accept method.
- Visitor (Area, Export) — implements one operation across every element type.
- Client — pairs elements with whichever visitor it needs.
Consequences
- Benefit: new operations cost one new visitor, zero shape edits; all of one operation’s logic sits together.
- Cost: adding a new shape type forces every visitor to grow a branch — cheap operations, pricey elements.
Basic Recap
Visitor adds an operation over a stable set of element types without placing that operation in every element class. Elements accept a visitor and dispatch to the method for their concrete type, while a visitor accumulates or returns the operation’s result. This is useful when new analyses are common but new element kinds are rare. Adding an element kind still requires updating every concrete visitor, which is the pattern’s central trade-off.
Complex Scenario
An infrastructure configuration model has stable nodes for compute, database, queue, and network resources. Separate visitors validate security policy, estimate monthly cost, and generate an execution manifest without turning each resource class into a home for all three concerns. A validation visitor returns structured findings attached to resource paths, while the cost visitor combines usage context with node attributes. The resource graph stays independent of the reporting and policy tools built over it.
Edge cases
- Ordering: A manifest visitor must honor dependencies between resources rather than treating traversal order as deployment order; dependency analysis belongs in the operation or an earlier plan.
- Partial failure: One malformed resource should produce a located finding and let validation continue where safe, instead of losing all other errors to the first exception.
- Memory pressure: Reusing one visitor across large graphs can retain every intermediate result, so accumulation needs bounded output or streaming.
- Concurrency: A mutable visitor instance cannot be shared by simultaneous analyses unless its accumulation is isolated per traversal.
Traversal control and operation logic should be separated enough to handle cycles or shared nodes without duplicating policy code.
Sketch (illustrative pseudocode, not runnable):
SecurityValidator.visitDatabase(node, path):
if node.publiclyReachable and not node.explicitlyApproved:
findings.add(path, PUBLIC_DATABASE)
for child in node.children:
child.accept(this, path.extend(child.name))
Analyze.run(root):
validator = SecurityValidator(findings = StreamSink(limit))
traversal.walkOnce(root, validator) # visited identity set prevents cycles
return validator.findings.summary()
When to Use / When Not to Use
Use when:
- Element types are stable but operations over them keep growing (area, export, pricing, checks).
- You want each operation’s cross-type logic in one reviewable unit.
Avoid when:
- New element types appear often — every addition ripples through all visitors (prefer plain polymorphism then).
Examples
examples/elixir/visitor/examples/dart/visitor/examples/go/visitor/examples/rust/visitor/
Expected outcome: an area visitor prices a circle and a square, then an export visitor reports both shapes.
Anti-pattern / Failure Mode
-
Misuse: A visitor over an unstable element set — every new element breaks all visitors.
-
Review signal: Visitors that need private element internals to work.
-
Misuse symptom: The element hierarchy changes weekly, forcing edits to a dozen visitors, or visitors use type tests because elements lack proper double dispatch. Visitors that mutate resources while validating also blur analysis with transformation and make results traversal-dependent.
-
Review signal: Look for empty visit methods added just to compile after a new node type, huge visitors handling unrelated operations, and shared mutable accumulators. If new element kinds are more frequent than new operations, ordinary polymorphic methods on the elements usually create less churn.
Related
- Iterator — add operations vs walk storage.
- Composite — operate over stable trees.
- Open/Closed — new operations without editing elements.
Exercise
Add a triangle element — update every visitor and note the ripple. Then add a perimeter visitor touching no element files, and compare the two change shapes.
Self-check
- Who changes when a new operation appears?
Answer
Only the new visitor — elements keep their single accept method untouched. - Who changes when a new element appears?
Answer
Every visitor needs a new branch, which is this pattern’s main cost. - How does accept dispatch work?
Answer
Double dispatch: the element’s accept calls back the visitor method for its own type, so the operation picks the right branch per element.
Architecture Patterns Tutorial
Part of the unified study index: Home · canonical decision guidance in selection guide.
Two tracks: how code is structured inside one project vs how services and infrastructure communicate at scale. All pages are original prose with text-native Mermaid diagrams and illustrative pseudocode.
Application Architecture (Code Structure)
- Layered — horizontal layers, each talks only to the layer below.
- Hexagonal — core logic isolated behind ports, adapters face the outside.
- Onion — domain model at the center, inward-pointing dependencies.
- Clean — concentric rings around Entities and Use Cases, strict dependency rule.
- Vertical Slice — organize by feature slice, not technical layers.
- MVC / MVVM / MVP — UI separations compared in one table.
- Each application page below now includes its complex scenario, edge cases, and expanded failure-mode guidance.
System & Distributed Architecture (Infrastructure & Scale)
- Monolithic — one codebase, one deployable unit.
- Modular Monolith — one deployable, strict module boundaries inside.
- Microservices — small independently deployable services, each owning its data.
- Event-Driven — async events via a broker decouple producers from consumers.
- Serverless — ephemeral functions and managed backends, no servers to run.
- SOA — larger reusable enterprise services, often coordinated via an ESB.
- CQRS & Event Sourcing — separate read/write models, every change stored as an event.
- Each system page below now includes its complex scenario, edge cases, and expanded failure-mode guidance.
Suggested Study Order
- Layered, Monolithic — the baseline everything else reacts to.
- Vertical Slice, Modular Monolith — first escapes from pure layering.
- Hexagonal, Onion, Clean — ports, rings, and dependency rules as a group.
- MVC / MVVM / MVP — UI separations after core structure clicks.
- Microservices, Event-Driven — distribution and async as a group.
- SOA, Serverless, CQRS & Event Sourcing — enterprise, functions, and data separation last.
Comparisons
Hexagonal vs Onion vs Clean
| Question | Hexagonal | Onion | Clean |
|---|---|---|---|
| Center | Application core | Domain model | Entities + Use Cases |
| Mechanism | Ports (interfaces) + adapters | Concentric rings, inward deps | Rings + strict dependency rule |
| Choose when | Swapping UI/DB/API matters most | Domain purity with infra outside | Enforcing layered rules at scale |
Layered vs Vertical Slice
| Question | Layered | Vertical Slice |
|---|---|---|
| Organized by | Technical layer | Feature |
| Change shape | Cross-layer for one feature | One folder per feature |
| Choose when | Small team, uniform stack | Features evolve independently |
Modular Monolith vs Microservices
| Question | Modular Monolith | Microservices |
|---|---|---|
| Deployables | One | Many |
| Boundaries | In-code modules, enforced | Service + database per capability |
| Choose when | One team, need boundaries first | Independent scaling and deploys outweigh ops cost |
Event-Driven vs CQRS & Event Sourcing
| Question | Event-Driven | CQRS & Event Sourcing |
|---|---|---|
| Center | Events triggering decoupled services | Read/write separation + immutable event log |
| Transport | Broker delivery | Event log as source of truth |
| Choose when | Reacting across services | Reads and writes scale or evolve differently |
Decision Guide
- Solo project, simple CRUD → Layered + Monolithic.
- Growing team, one deployable → Vertical Slice + Modular Monolith.
- Swappable UI/DB/providers → Hexagonal (or Onion/Clean if domain-centric).
- UI-heavy client → MVC / MVVM / MVP per platform norms.
- Independent scaling per capability → Microservices; add Event-Driven for async flows.
- Enterprise reuse across business units → SOA with ESB governance.
- Spiky workloads, minimal ops → Serverless functions + managed backends.
- Read-heavy with complex writes → CQRS; add Event Sourcing when audit/replay matters.
Combinations are normal: e.g., Clean inside a Modular Monolith module, or Vertical Slices each exposing ports, or Microservices communicating via events with CQRS on the hot path.
Architecture Page Template (Shared Explanation Shape)
Follow this order on every page under architecture/. Keep prose original and scannable.
See content/MAPPING.md for single-source rules and guides/selection.md for the canonical chooser.
Intent
One or two sentences: what problem this pattern solves.
When It Helps
2-4 bullets: team size, complexity, or scale signals that point here. (This is the Motivation slot of the shared shape — keep it as signals, not prose.)
Structure
Original Mermaid diagram only (no copied images). Example:
flowchart LR A --> B
Rules
Numbered dependency or topology rules (what may call what, what is forbidden).
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch of the key boundary
Basic Recap
3-5 sentences restating the pattern’s intent and core roles in your own words.
Complex Scenario
A work-like situation with a topology diagram, at least one failure or scaling walkthrough, and edge cases.
Trade-offs
- Benefit: …
- Cost: …
When to Use / When Not to Use
Use when:
- …
Avoid when:
- …
(If this duplicates When It Helps, keep When It Helps as signals and use this section for the explicit avoid-when cases plus scaling limits.)
Anti-pattern / Failure Mode
One misuse symptom plus one review signal, followed by the expanded failure-mode and trade-off guidance formerly kept in the depth page.
Related Patterns
Links to 1-3 neighboring architecture patterns plus at least one cross-pillar link (design pattern, principle, or practice capstone) with one line on how they differ or combine.
Clean Architecture
Intent
Arrange the system as concentric rings around entities and use cases with one strict rule: source-code dependencies may only point inward.
When It Helps
- Long-lived product where frameworks, UI toolkits, and databases will be replaced during its lifetime.
- Teams need a shared vocabulary: entities (what the business is), use cases (what it does), adapters (how it connects).
- Testability matters — use cases should run with in-memory gateways and no framework boot.
Structure
flowchart TB
subgraph Rings["Clean rings (outer → inner)"]
FW["Frameworks & drivers<br/>(web, DB, devices)"] --> ADAPT["Interface adapters<br/>(controllers, presenters, gateways)"]
ADAPT --> UC(["Use cases<br/>(application rules)"])
UC --> ENT(["Entities<br/>(business rules)"])
end
Rules
- Dependency rule: inner rings know nothing about outer rings; all dependencies point inward.
- Use cases orchestrate entities and declare the gateway interfaces they need; outer rings implement them.
- Interface adapters convert between external formats (HTTP, SQL rows) and the plain data that use cases accept.
- Frameworks and drivers are details in the outermost ring and are never referenced by name from use cases or entities.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch of the dependency-rule boundary
inner Entities:
entity Order { items, total }
rule place_valid(cart): cart is non-empty
inner UseCases:
function checkout(cart, orders: OrderGateway, notify: Notifier):
check place_valid(cart) # pure business orchestration
id = orders.save(build(cart))
notify.sent(id)
return id
outer InterfaceAdapters:
controller CheckoutController:
on POST(cart_json): return checkout(parse(cart_json), SqlOrders, EmailNotify)
gateway SqlOrders implements OrderGateway:
function save(order): database.insert("orders", order)
Basic Recap
Clean architecture separates enterprise entities, application use cases, interface adapters, and external drivers. Source dependencies point inward, while outer adapters translate transport and persistence data into plain inputs and outputs. Use cases coordinate policy without knowing which web framework or database invokes them. The structure pays off when business behavior outlives several generations of technology.
Complex Scenario
A travel company runs reservation changes through web, mobile, and call-center clients. The ChangeItinerary use case validates fare and ticketing rules, then coordinates booking and notification gateways. Search traffic is much heavier than change traffic, so developers initially reuse that use case to answer availability queries. This couples high-volume reads to transactional write dependencies and framework-specific response mapping.
flowchart TB
Web["Web and mobile drivers"] --> Controllers["Controllers and presenters"]
Agents["Call-center desktop"] --> Controllers
Controllers --> Change[["ChangeItinerary use case"]]
Change --> Entities[("Fare and ticket entities")]
Change --> Booking[["Booking gateway interface"]]
Change --> Notices[["Notification gateway interface"]]
Search["Availability query adapter"] --> ReadGateway[["Availability read gateway"]]
Booking --> GDSAdapter["Booking adapter"] --> GDS["External reservation system"]
ReadGateway --> SearchDB[("Availability read store")]
Notices --> Mail["Notification driver"]
Scaling walkthrough. A marketing launch raises availability traffic tenfold. Every search now constructs write-side gateways, opens reservation transactions, and waits on the external booking system, exhausting workers even though no ticket changes. Mitigate by giving queries a narrow adapter and denormalized read store, reserving ChangeItinerary for writes, and applying independent connection pools and autoscaling limits to the two paths.
Edge cases — concurrent itinerary changes need expected booking versions, retries need a client operation key, and partial failure needs a recoverable state when the booking succeeds before notification. Search results may be stale, so their timestamp must survive adapter mapping.
Sketch (illustrative pseudocode, not runnable):
use_case ChangeItinerary:
input: {operation_key, booking_id, expected_version, new_segments}
output: {booking_id, status, fare_delta}
dependencies: BookingGateway, NotificationGateway # inner-owned interfaces
query_adapter Availability:
input: {route, date, passengers}
reads: AvailabilityReadGateway
returns: {options[], snapshot_time}
wiring:
change_controller -> ChangeItinerary -> booking_adapter
search_controller -> Availability -> read_store
forbidden: entities -> any controller or database package
Trade-offs
- Benefit: business rules are fully decoupled from delivery and persistence, so frameworks become replaceable details.
- Cost: the most ceremony of the ring family — four layers of mapping for even small features.
When to Use / When Not to Use
Use when:
- Long-lived product where frameworks and databases will be replaced.
- Teams needing shared vocabulary of entities and use cases with fast in-memory tests.
Avoid when:
- Small CRUD app where four rings add ceremony without benefit.
Anti-pattern / Failure Mode
- Misuse: Use cases referencing framework types directly.
- Review signal: Cannot run business tests without booting the framework.
Failure Modes / Trade-offs
- Mapping ceremony: near-identical request, entity, gateway, and response objects multiply without protecting behavior. Consolidate representations where their change reasons are actually the same.
- Framework gravity: controllers acquire policy, while use cases import sessions or serialization decorators. Inner-ring imports and framework-free tests reveal the drift.
- Use-case mega-service: unrelated commands share one orchestrator and all gateways, making every client depend on every infrastructure concern. Split by application operation and transaction boundary.
- Delivery trade-off: clear roles and isolated policy ease long-term migration, but small features cross many boundaries and require disciplined dependency wiring.
Dependency review. Build inner rings separately from drivers so an accidental framework import fails quickly; package names alone do not prove the dependency rule.
Boundary-data review. Include operation identity, expected versions, and freshness in plain boundary models rather than retrieving them implicitly from web sessions or ORM contexts.
Query review. Separating availability search from reservation changes is still clean architecture: both have explicit adapters, but only the write operation needs transactional use-case orchestration.
- Test trade-off: use-case tests avoid slow framework startup, while adapter tests must still cover the external errors that plain inner models cannot represent directly.
- Performance trade-off: repeated data conversion costs CPU and allocations, so hot paths need measurement rather than automatic acceptance of every mapping layer.
- Ownership trade-off: shared entities can unify enterprise policy, but forcing every bounded context into one entity model creates coupling that rings cannot fix.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Product expected to survive UI and database migrations | Use inward dependencies and adapters to contain those migrations. |
| Very different read and write latency targets | Use narrow query adapters rather than routing searches through transactional use cases. |
| Four-person team building a prototype with uncertain rules | Avoid full ring ceremony; start with direct application services and add boundaries as policy stabilizes. |
| Compliance demands repeatable business decisions across channels | Use framework-independent use cases with recorded inputs, policy versions, and adapter outcomes. |
Related Patterns
- Onion — same inward-pointing rings, centered on the domain model rather than entities plus use cases.
- Hexagonal — same isolation through interfaces, framed as ports and adapters instead of rings.
- Vertical Slice — alternative that cuts across rings to keep one feature’s code together.
- Dependency Rule — the strict form of the rule.
- Modular Monolith Orders — clean inside module boundaries.
Hexagonal Architecture
Intent
Isolate core business logic in the center and reach everything outside it — UI, databases, external APIs — only through explicit ports (interfaces) with adapters on each side.
When It Helps
- Business rules matter more than any single framework, database, or delivery mechanism.
- You need to swap infrastructure (e.g. change database vendor, add a CLI beside the web UI) without rewriting logic.
- Tests should drive the core through ports using fake adapters instead of booting real infrastructure.
Structure
flowchart LR
subgraph Outside["Outside world"]
UI["Web UI"]
DB[("Database")]
API["External API"]
end
subgraph Hexagon["Application"]
PA["Driving adapters<br/>(controllers, CLI)"] --> PI[["Driving ports<br/>(use-case interfaces)"]]
PI --> CORE(["Core logic"])
CORE --> PO[["Driven ports<br/>(storage / notify interfaces)"]]
PO --> DA["Driven adapters<br/>(SQL repo, HTTP client)"]
end
UI --> PA
DA --> DB
DA --> API
Rules
- Core logic depends only on port interfaces it defines; it never imports an adapter, framework, or driver directly.
- All inbound calls (UI, CLI, tests) enter through driving ports and their adapters.
- All outbound calls (persistence, messaging, third-party APIs) leave through driven ports and their adapters.
- Swapping an adapter (e.g. in-memory store for a SQL store) must not require changes to the core.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch of the port / adapter boundary
port OrderStore: # driven port, defined by the core
function save(order) -> id
core OrderService(store: OrderStore):
function place(items):
order = build_order(items) # pure logic, no SQL here
return store.save(order) # talks only to the port
adapter SqlOrderStore implements OrderStore: # driven adapter
function save(order):
return database.insert("orders", order)
adapter InMemoryOrderStore implements OrderStore: # test adapter
function save(order):
return fake_list.append(order)
Basic Recap
Hexagonal architecture places application behavior behind ports that describe what the core needs or offers. Driving adapters translate web requests, commands, or tests into those ports, while driven adapters connect storage and external systems. Dependencies point toward the core, so infrastructure choices remain replaceable. The pattern is most useful when several delivery mechanisms share meaningful business rules.
Complex Scenario
A subscription business accepts payments from a web app, a partner API, and an offline reconciliation job. All three paths must apply the same credit-limit and duplicate-payment rules. The core owns contracts for payment storage, a payment provider, and receipt publication; provider-specific authentication and database transactions stay in adapters. A new partner adapter must not change the payment policy.
flowchart LR
Web["Web controller"] --> UseCase[["Charge subscription port"]]
Partner["Partner API adapter"] --> UseCase
Job["Reconciliation adapter"] --> UseCase
UseCase --> Core["Payment policy core"]
Core --> Store[["Payment store port"]]
Core --> Provider[["Payment provider port"]]
Core --> Receipts[["Receipt port"]]
Store --> SQL["SQL adapter"] --> DB[("Payments DB")]
Provider --> PSP["Provider adapter"] --> API["Payment provider"]
Receipts --> Outbox["Outbox adapter"] --> Queue[("Receipt queue")]
Failure walkthrough. The payment provider times out after accepting a charge, and each adapter retries the same request with a new provider key. Customers receive duplicate charges while the web path occupies workers waiting for receipts. Mitigate this by carrying one stable idempotency key through every driving port, using bounded provider timeouts and circuit breaking, and publishing receipts through a transactional outbox after the stored result commits.
Edge cases — concurrency requires a uniqueness constraint on the payment key, retries require provider-safe replay, and partial failure requires an explicit accepted_unknown state for ambiguous provider responses. Ordering between a charge and its receipt should come from outbox records, not adapter timing.
Sketch (illustrative pseudocode, not runnable):
port ChargeSubscription:
execute(command{idempotency_key, account, amount}) -> result
core PaymentPolicy:
execute(command):
existing = payments.find_by_key(command.idempotency_key)
return existing if present
authorize_credit(command.account, command.amount)
return payments.record_pending(command)
adapter ProviderGateway:
charge(pending):
response = provider.post(charge, key=pending.idempotency_key, timeout=2s)
return classify(response, timeout_as="accepted_unknown")
Trade-offs
- Benefit: business logic stays independent of frameworks and infrastructure, so adapters are swappable and the core is easy to test.
- Cost: more interfaces and adapter classes than plain layering, which can feel like ceremony for simple CRUD apps.
When to Use / When Not to Use
Use when:
- Core logic must run with swapped UI/DB/providers or with in-memory fakes.
Avoid when:
- Single fixed stack with no swap need — Layered is simpler.
Anti-pattern / Failure Mode
- Misuse: Ports defined per adapter instead of per domain need, leaking infrastructure into the core.
- Review signal: Core importing adapter packages.
Failure Modes / Trade-offs
- Port proliferation: every entity gets a repository, notifier, and mapper interface despite having only one plausible implementation. Review signals are one-line ports and tests that only verify mocks.
- Leaky contracts: a port exposes SQL transactions, HTTP responses, or provider error classes. The core then changes whenever an adapter changes, defeating the boundary.
- Adapter anarchy: business rules move into controllers or provider clients because those locations are convenient. Compare behavior across driving adapters to expose drift.
- Practical trade-off: isolated core tests are fast and infrastructure can evolve independently, but mapping, dependency wiring, and failure translation add real maintenance cost.
Contract review. Every port should use domain vocabulary and state its idempotency, transaction, and failure semantics; adapter-specific optional parameters are a leakage warning.
Composition review. Keep construction of adapters in one composition root so tests and production cannot accidentally wire different policy dependencies.
Recovery review. Reconcile accepted_unknown payments with a status-query adapter or provider report instead of letting operators guess whether to retry.
- Testing trade-off: fake adapters clarify core behavior, but contract tests against real infrastructure remain necessary for serialization, timeouts, and constraints.
- Security trade-off: narrow ports limit exposed credentials, though too many generic pass-through methods can silently grant adapters excessive capability.
- Diagnostics trade-off: translation at each boundary improves isolation but requires correlation identifiers on core commands and adapter logs to preserve an end-to-end trace.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Multiple UIs, jobs, or partner APIs sharing rules | Use driving ports to keep behavior consistent across entry points. |
| Frequent provider or database replacement | Use driven ports where substitution is a demonstrated requirement. |
| Tiny team building short-lived CRUD with one database | Avoid a full port per dependency; direct application services are cheaper to understand. |
| Compliance requires deterministic policy tests and audit evidence | Use a pure core plus recording fake adapters, while keeping signed audit persistence outside it. |
Related Patterns
- Onion — same inward-dependency spirit with the domain model at the center instead of ports.
- Clean — same isolation goal with stricter concentric rings around entities and use cases.
- Layered — simpler stacked alternative when you do not need swappable adapters.
- Test Isolation — ports make fakes trivial.
- Modular Monolith Orders — hexagonal boundaries inside one deployable.
Layered Architecture
Intent
Organize code into stacked horizontal layers so that each layer only uses the layer directly beneath it, keeping UI, business logic, and data access cleanly separated.
When It Helps
- Small to medium team building a conventional business application (e.g. internal tools, CRUD systems).
- Requirements are fairly stable and the domain logic is simple enough to live in one middle layer.
- You want a structure every developer recognizes on day one, without extra abstractions.
Structure
flowchart TB
P["Presentation<br/>(UI / Controllers)"] --> B["Business Logic<br/>(Services / Rules)"]
B --> DA["Data Access<br/>(Repositories / Queries)"]
DA --> DB[("Database")]
Rules
- Presentation may call Business Logic, but never Data Access or the database directly.
- Business Logic may call Data Access, but never Presentation.
- Data Access owns all persistence details; upper layers never write SQL or touch connection objects.
- Dependencies point strictly downward — no layer calls upward and no layer skips a level.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch of the layer boundary
layer Presentation:
on submit_order(request):
# may only talk to the layer below
result = Business.OrderService.place(request.items)
render(result)
layer Business:
function place(items):
validate(items)
total = price(items) + tax(items)
return DataAccess.OrderStore.save(items, total)
layer DataAccess:
function save(items, total):
# only layer allowed to touch persistence
return database.insert("orders", {items, total})
Basic Recap
Layered architecture separates presentation, business rules, and persistence into a downward-pointing stack. Each layer exposes a contract to the layer above and hides the mechanics of the layer below. The approach works because most developers can infer where a change belongs without learning a large framework. Its value disappears when layers become labels rather than enforced dependency boundaries.
Complex Scenario
A claims operations team runs one application for adjusters, nightly renewals, and customer document uploads. A new regulatory report must combine claim rules with several database queries without duplicating policy calculations. The team adds a reporting facade above the business layer, but a shortcut lets that facade call back into presentation formatting. The resulting topology looks orderly until dependency checks and peak load expose the shortcuts.
flowchart TB
Adjuster["Adjuster UI"] --> Presentation["Presentation controllers"]
Renewal["Nightly renewal job"] --> Presentation
Presentation --> Business["Business services and policy rules"]
Business --> Access["Data access repositories"]
Access --> DB[("Claims database")]
Access --> Cache[("Policy cache")]
Report["Regulatory report facade"] --> Business
Presentation -. "forbidden callback" .-> Report
Failure walkthrough. During a tenfold renewal batch, each business call waits on the exhausted database pool while presentation threads remain blocked above it. The reporting callback also creates a dependency cycle, so a harmless formatting change now requires business code to recompile. Mitigate the runtime failure with bounded job concurrency, query timeouts, and a separate reporting read pool; remove the cycle by moving neutral formatting below presentation or passing formatted output outward.
Edge cases — concurrent renewals can reserve the same claim, retries can duplicate a submission, and partial failure can leave a report mixing policy versions. Use database-backed claim versions, idempotency keys, and a report snapshot token rather than relying on layer placement to solve these problems.
Sketch (illustrative pseudocode, not runnable):
dependency_rules:
presentation -> business
business -> data_access
forbidden: business -> presentation
forbidden: presentation -> data_access
renewal_job:
workers: 4
claim_lock: optimistic_version
repository_timeout: 800ms
retry: only_if idempotency_key_present
Trade-offs
- Benefit: simple, familiar separation that keeps UI and SQL out of each other’s way.
- Cost: rigid layering can force trivial logic through every level, and the business layer tends to become a catch-all as the system grows.
When to Use / When Not to Use
Use when:
- Small team, uniform stack, CRUD-heavy app with stable layers.
Avoid when:
- One feature routinely cuts across all layers with independent deploy needs — consider Vertical Slice.
Anti-pattern / Failure Mode
- Misuse: Every feature edits every layer with circular imports between them.
- Review signal: Changes that touch 4+ layers for one field.
Failure Modes / Trade-offs
- Pass-through stack: controllers, services, and repositories repeat the same method names without adding decisions. Collapse empty layers for simple features instead of preserving symmetry.
- Business-layer sink: validation, orchestration, caching, and UI formatting all migrate into one service package. Review signals are thousand-line services and imports from every other package.
- Layer skipping: a controller issues SQL for a quick report, then production behavior diverges from tested business rules. Make the exception a deliberate read path rather than an undocumented shortcut.
- Operational trade-off: a shared stack keeps transactions and debugging straightforward, but one slow lower layer can stall every entry point unless resource budgets are applied per workload.
Boundary review. A change to presentation markup should not alter repository tests, and a schema change should not require controller edits except at an explicit mapping boundary.
Transaction review. Document which layer begins and ends a transaction; hidden commits inside repositories make retries and batch recovery unpredictable.
Test review. Test policy beneath the UI with repository fakes, then retain a few full-stack tests to prove that the real downward wiring still works.
Release review. Track changes that cross all three layers; frequent vertical changes are normal for a feature, but widespread edits for one rule suggest misplaced responsibility.
- Reuse trade-off: generic services shared by unrelated features become coordination points, so reuse should follow stable policy rather than similar method signatures.
- Security trade-off: authorization only in presentation leaves jobs exposed, while authorization only in repositories loses caller intent; place each check at its appropriate boundary.
- Data trade-off: one shared persistence model is simple, but reporting-specific queries may need separate projections without becoming a new business layer.
- Change trade-off: strict downward dependencies aid navigation, yet they do not replace feature ownership or prevent a large business layer from becoming coupled.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Team of 2–8 developers with conventional CRUD work | Use a small three-layer stack; it is easy to navigate and needs little architectural staffing. |
| Strict latency budget for simple queries | Use cautiously: permit measured read-only shortcuts, but avoid forcing every query through ceremonial mappings. |
| Many autonomous teams changing unrelated domains | Avoid one shared layered codebase; feature or domain boundaries will usually serve ownership better. |
| Regulatory requirement for repeatable calculations | Use an enforced business layer with versioned rules, and keep reporting on a consistent snapshot. |
Related Patterns
- Hexagonal — keeps the same idea of isolating business logic but replaces stacked layers with ports and adapters.
- Vertical Slice — organizes the same code by feature instead of by technical layer.
- MVC / MVVM / MVP — a finer-grained split for structuring just the presentation layer above.
- Modular Monolith — layering inside enforced module boundaries.
- Separation of Concerns — the principle behind the layers.
MVC / MVVM / MVP
Intent
Separate user-interface concerns — what is shown, what the user does, and how the two stay in sync — so views stay thin and UI logic stays testable without booting a screen.
When It Helps
- The application has significant UI surface (forms, navigation, state updates) that would tangle without a pattern.
- Designers and developers iterate on views while logic must keep working headlessly under test.
- You need to pick the UI wiring that matches your platform’s conventions rather than forcing one shape everywhere.
Structure
flowchart LR
subgraph MVC["MVC"]
U1["View"] --> C1["Controller"]
C1 --> M1[("Model")]
M1 --> U1
end
subgraph MVP["MVP"]
U2["View"] <--> P2["Presenter"]
P2 <--> M2[("Model")]
end
subgraph MVVM["MVVM"]
U3["View"] <-->|data binding| VM3["ViewModel"]
VM3 --> M3[("Model")]
end
Rules
- Views render state and forward user intent; they never contain business rules or direct data access.
- In MVC, controllers handle input and mediate between view and model; the model notifies views of changes.
- In MVP, the presenter owns all view logic behind a view interface, and the view delegates every decision to it.
- In MVVM, the view binds declaratively to an observable view-model; the view-model never holds a reference to view widgets.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch of the view / coordination boundary
view OrderScreen: # all three variants keep this thin
on submit_pressed(items): delegate.submit(items)
show_confirmation(id): display("Order " + id + " placed")
coordinator OrderPresenter_or_ViewModel: # presenter or view-model
function submit(items): # no widget imports here
id = OrderService.place(items)
view.show_confirmation(id) # presenter calls view interface,
# or view-model publishes id for binding
Basic Recap
MVC, MVP, and MVVM separate rendering, user intent, presentation decisions, and domain state in different ways. MVC controllers mediate input, MVP presenters drive a passive view through an interface, and MVVM exposes observable state for declarative binding. None of these variants gives a view permission to own business policy or direct persistence. The best choice usually follows the platform’s rendering and binding model.
Complex Scenario
A retailer maintains a server-rendered catalog, a desktop receiving terminal, and a reactive mobile inventory app. The catalog uses MVC, the terminal uses MVP because its widget toolkit lacks binding, and mobile uses MVVM. All three display the same stock policy through a domain service, but their synchronization mechanisms differ. A new real-time price feed now updates every visible item several times per second.
flowchart LR Browser["Catalog browser"] <--> Controller["MVC controller"] Controller --> Model["Stock and pricing model"] Model --> Controller Terminal["Receiving view"] <--> Presenter["MVP presenter"] Presenter <--> Model Mobile["Mobile view"] <-- "declarative binding" --> ViewModel["MVVM view-model"] ViewModel --> Model Feed["Real-time price feed"] --> Model Model --> Policy["Domain stock policy"]
Scaling walkthrough. A tenfold price-event burst triggers a binding update for every cell, queues work on the mobile UI thread, and retains obsolete view-models through undisposed feed subscriptions. Screens drop frames while memory climbs, and the MVP terminal repeats individual widget updates. Mitigate by conflating updates to the latest snapshot, batching renders at a measured cadence, disposing subscriptions with screen lifecycle, and moving diff computation off the UI thread.
Edge cases — concurrent edits need a visible conflict state, retries need stable submission keys, and out-of-order feed messages need sequence checks before binding. Partial failure should leave the last confirmed model visible with a stale-data indicator rather than clearing the screen.
Sketch (illustrative pseudocode, not runnable):
view_model InventoryScreen:
state: {rows, pending_submission, stale, error}
on_start:
subscription = price_feed
.conflate_to_latest()
.batch_every(100ms)
.observe_on(ui_scheduler)
.subscribe(render_state)
on_stop: subscription.dispose()
presenter ReceivingScreen:
submit(command):
view.show_pending(command.idempotency_key)
result = stock_service.apply(command)
view.render_once(result) # no domain rules in widgets
Trade-offs
- Benefit: UI logic becomes unit-testable and views become replaceable, since rendering is decoupled from decisions.
- Cost: extra types and indirection (presenters, view-models, bindings) that outweigh the gain for trivial screens.
Comparison
| Variant | What it separates | When to choose it |
|---|---|---|
| MVC (Model–View–Controller) | Input handling (controller) from rendering (view) and domain state (model) | Server-rendered or framework-conventional apps where the framework already routes input to controllers |
| MVP (Model–View–Presenter) | View logic behind a view interface so the presenter drives a passive view | Platforms without data binding (e.g. classic desktop, WinForms-style, legacy mobile) where explicit presenter control and unit tests matter |
| MVVM (Model–View–ViewModel) | View state as an observable view-model that the view binds to declaratively | XAML / reactive / modern front-end stacks with data binding, where two-way sync without manual view updates pays off |
When to Use / When Not to Use
Use when:
- UI-heavy client needing separated presentation, state, and view logic per platform norms.
Avoid when:
- Headless service with no UI — the separation adds no value.
Anti-pattern / Failure Mode
- Misuse: Business rules living in controllers/view-models with no testable core.
- Review signal: Massive view-controllers doing persistence and formatting.
Failure Modes / Trade-offs
- Massive coordinator: controllers, presenters, or view-models absorb navigation, validation, caching, and business rules. A coordinator that imports every service is a review warning.
- Two sources of truth: widgets, observable fields, and the domain model each hold editable copies, producing flicker and lost input. Define ownership and one synchronization direction per field.
- Binding opacity: generated subscriptions outlive screens or hide expensive work. Profile allocation and UI-thread time rather than assuming declarative code is cheap.
- Variant trade-off: explicit MVC/MVP wiring is easy to trace but verbose; MVVM reduces manual updates but demands lifecycle and binding expertise.
State review. For every editable field, identify the authoritative owner and when user input is committed; otherwise model refreshes can overwrite work in progress.
Lifecycle review. Test backgrounding, rotation, navigation away, and reconnection because subscriptions and presenter references usually fail at transitions rather than initial render.
Accessibility review. Presentation state should expose progress, stale data, and errors semantically so each view variant can announce them rather than encoding meaning only in color or layout.
- Testing trade-off: passive views and observable state support headless tests, but rendering tests remain necessary for layout, focus, accessibility, and actual binding behavior.
- Performance trade-off: batching reduces render pressure but delays feedback, so critical submission state should bypass the batch used for routine price changes.
- Portability trade-off: sharing a domain model across variants is realistic; sharing widget-specific presenters or view-models usually imports platform assumptions.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Framework already provides conventional server controllers | Use MVC instead of introducing a second presentation abstraction. |
| Legacy widgets and a hard requirement for headless UI tests | Use MVP with a narrow passive-view interface. |
| Reactive platform plus frequent, high-volume state changes | Use MVVM cautiously, with update conflation, lifecycle disposal, and frame-time budgets. |
| Two developers maintaining a few static forms | Avoid elaborate triads; simple view code plus domain services has lower cost. |
Related Patterns
- Layered — these UI patterns typically live inside the presentation layer of a layered app.
- Vertical Slice — each slice can own its small MVC/MVVM triad so UI wiring stays feature-local.
- Hexagonal — UI adapters (controllers, presenters, view-models) are the driving adapters of a hexagon.
- Separation of Concerns — the UI form of the split.
- Observer — view updates via broadcasts.
Onion Architecture
Intent
Put the domain model at the center and wrap it in concentric rings so that every dependency points inward toward the model, never outward toward infrastructure.
When It Helps
- The domain is rich — entities, value objects, and rules deserve protection from UI and persistence concerns.
- Multiple outer concerns (web UI, background jobs, several databases) orbit one stable core.
- You want infrastructure to be a replaceable outer ring rather than something the domain knows about.
Structure
flowchart TB
subgraph Rings["Onion rings (outer → inner)"]
INFRA["Infrastructure<br/>(DB, web, messaging)"] --> APP["Application services<br/>(workflows, DTOs)"]
APP --> DOMAIN_SVC["Domain services<br/>(domain operations)"]
DOMAIN_SVC --> MODEL(["Domain model<br/>(entities, value objects)"])
end
Rules
- The domain model at the center depends on nothing outside itself.
- Each ring may depend only on rings inside it — never on an outer ring.
- Outer rings implement interfaces declared by inner rings (dependency inversion at every boundary).
- Cross-cutting concerns (logging, configuration) live in the outer rings and are injected inward, never imported by the model.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch of the inward-dependency boundary
center DomainModel: # depends on nothing
entity Order { items, total }
rule: total = sum(items) + tax(items)
ring DomainServices: # depends only on the model
function price(order: Order):
return order.total # pure domain operation
ring ApplicationServices: # depends inward
function checkout(cart, store: OrderRepository):
order = DomainModel.build(cart)
return store.save(order) # repository interface declared inside
outer Infrastructure: # implements inner interfaces
repository SqlOrders implements OrderRepository:
function save(order): database.insert("orders", order)
Basic Recap
Onion architecture wraps a dependency-free domain model in domain services, application services, and infrastructure. Inner rings define policies and required abstractions; outer rings supply technical implementations. This keeps entities and value objects meaningful even when delivery or persistence technology changes. The rings are a dependency rule, not a requirement to create arbitrary projects for every concept.
Complex Scenario
A hospital medication service checks allergies, dosage ranges, and formulary eligibility before a pharmacist approves an order. The domain model must run in bedside devices during network outages, while the hosted application also calls insurance and identity providers. Application services coordinate transactions, but clinical rules remain in the model and domain services. Infrastructure supplies repository and benefits implementations without leaking their types inward.
flowchart TB
UI["Pharmacist UI"] --> Infra["Infrastructure ring"]
Bedside["Offline bedside adapter"] --> App
Infra --> App["Application services ring"]
App --> DomainServices["Domain services ring"]
DomainServices --> Model[("Medication domain model")]
Infra --> DB[("Clinical database")]
Infra --> Benefits["Insurance benefits API"]
Infra -. "implements inner interfaces" .-> App
Failure walkthrough. The benefits API stalls during a regional outage, and application workers wait while holding database transactions open. Bedside checks are unaffected only if the domain was kept free of network clients, but hosted approvals soon exhaust their connection pool. Mitigate with benefits calls outside the write transaction, short deadlines, bounded concurrency, and a cached eligibility snapshot whose age is visible to the pharmacist; never turn an unavailable benefit answer into an automatic clinical approval.
Edge cases — concurrent prescription edits need aggregate versions, retries need stable request identity, and partial failure must distinguish a saved clinical order from an unconfirmed insurance claim. Offline synchronization also needs conflict rules based on clinical timestamps and reviewer decisions.
Sketch (illustrative pseudocode, not runnable):
center Model:
MedicationOrder.check(allergies, dose_limits) # no imports outside domain
inner DomainServices:
MedicationReview.evaluate(order, patient, formulary_snapshot)
ring Application:
approve(command, orders: OrderRepository, benefits: BenefitsGateway):
order = orders.load(command.id, expected_version=command.version)
review = MedicationReview.evaluate(order, command.patient, command.snapshot)
orders.save(order.approve(review))
outer Infrastructure:
HttpBenefits implements BenefitsGateway:
deadline: 700ms
fallback: cached_snapshot_with_age
Trade-offs
- Benefit: the domain model stays pure and stable while UI and infrastructure churn around it.
- Cost: several rings and interface boundaries to maintain, which is heavyweight when the domain is thin.
When to Use / When Not to Use
Use when:
- Domain purity matters most and infrastructure must stay outside concentric rings.
Avoid when:
- UI-driven app where domain is thin — MVC/MVVM is enough.
Anti-pattern / Failure Mode
- Misuse: Application services leaking into domain entities.
- Review signal: Domain package importing infrastructure.
Failure Modes / Trade-offs
- Decorative rings: every ring contains interfaces and mappers but the center has no meaningful rules. This creates navigation cost without protecting a domain.
- ORM-centered model: persistence annotations, lazy loading, and framework sessions leak into entities, making offline or unit execution depend on infrastructure.
- Outer-ring policy: insurance or dosage decisions migrate into controllers and SQL stored procedures. Divergent behavior between bedside and hosted clients is the review signal.
- Evolution trade-off: inward dependencies support durable policy and replaceable technology, but cross-ring mapping can obscure simple workflows and inflate small changes.
Ring review. A dependency report should prove that model and domain-service code compile without application or infrastructure packages, not merely avoid importing a web controller.
State review. Aggregate boundaries determine what can change atomically; expecting one transaction to cover every clinical system would push infrastructure concerns into the model.
Safety review. Record whether a decision used live, cached, or offline formulary data so later reviewers can interpret the same outcome correctly.
- Modeling trade-off: rich entities protect invariants but require domain expertise and ongoing collaboration with the people who own clinical policy.
- Persistence trade-off: translating between aggregates and database rows adds code, yet reusing ORM objects as the center makes lazy loading part of domain behavior.
- Consistency trade-off: cached eligibility improves availability, but its freshness and clinical authority must be explicit rather than hidden in infrastructure fallback logic.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Complex clinical, financial, or engineering invariants | Use a rich center so rules can be exercised without infrastructure. |
| Offline clients must reuse the same policy | Use a portable domain core and keep synchronization in outer rings. |
| Small team delivering mostly forms and reports | Avoid deep rings until domain behavior justifies their maintenance. |
| Compliance requires explainable decisions, not just stored outcomes | Use explicit domain review outputs with rule and snapshot versions recorded by the application ring. |
Related Patterns
- Hexagonal — centers on ports and adapters rather than a domain-model core, but shares inward dependencies.
- Clean — nearly the same ring idea with entities and use cases named as the inner layers.
- Layered — simpler horizontal alternative when a rich domain core is overkill.
- Dependency Rule — the rule onion enforces.
Vertical Slice Architecture
Intent
Organize code by feature slice — each slice owns its request, handler, and persistence for one capability — instead of spreading every feature across shared technical layers.
When It Helps
- Features evolve independently and rarely share logic (e.g. checkout vs. reporting vs. notifications).
- Teams want small, deletable units: removing a feature means removing one folder, not edits across layers.
- High-churn product where minimizing cross-feature coupling matters more than maximizing code reuse.
Structure
flowchart LR
subgraph App["Application"]
S1["Slice: Place order<br/>(request + handler + store)"]
S2["Slice: Add review<br/>(request + handler + store)"]
S3["Slice: Send receipt<br/>(request + handler + mailer)"]
end
S1 --> DB1[("Orders table")]
S2 --> DB2[("Reviews table")]
S3 --> MTA["Mail service"]
SHARED["Shared kernel<br/>(only true common code)"] -.-> S1
SHARED -.-> S2
SHARED -.-> S3
Rules
- Each slice contains everything its feature needs (input model, handler, validation, persistence) and is importable by nothing else.
- Slices never call each other directly; shared behavior goes through explicit messages/events or a tiny shared kernel.
- Cross-cutting code (auth, logging, pipelines) is composed around slices, not placed inside them.
- New features start as new slices; resist adding a shared abstraction until the third duplication.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch of one self-contained slice
slice PlaceOrder: # everything for this feature, together
request PlaceOrder(items, address)
handler execute(request):
validate(request) # validation lives in the slice
total = price(request.items)
id = database.insert("orders", {request, total})
publish_event("order_placed", id)
slice AddReview: # a second slice, independent
request AddReview(order_id, stars, note)
handler execute(request):
validate(request)
database.insert("reviews", request)
# note: neither slice imports the other
Basic Recap
Vertical slice architecture groups a feature’s request, validation, handler, and infrastructure choices in one place. Slices may use different implementation styles because their internal decisions are private. Shared code is reserved for genuinely stable concepts rather than anticipated reuse. This optimizes for feature-level change and deletion instead of uniform technical layers.
Complex Scenario
A media platform has slices for uploading footage, requesting transcription, publishing an episode, and generating audiograms. Upload uses direct object storage, publishing uses relational transactions, and audiograms invoke a rendering worker. A developer notices that publishing and billing both format account entitlements, so publishing imports the billing handler instead of extracting a neutral contract. The shortcut creates a cross-slice dependency just as rendering load rises.
flowchart LR
UploadAPI["Upload request"] --> Upload["Slice: Upload"]
Upload --> Objects[("Object storage")]
Upload --> Events[("Media event queue")]
Events --> Transcribe["Slice: Transcribe"]
Events --> Audiogram["Slice: Audiogram"]
Audiogram --> Workers["Rendering workers"]
PublishAPI["Publish request"] --> Publish["Slice: Publish"]
Publish --> PublishDB[("Publishing tables")]
Publish -. "unintended handler import" .-> Billing["Slice: Billing"]
Kernel["Small shared kernel: IDs and clock"] -.-> Publish
Kernel -.-> Billing
Failure walkthrough. Billing later imports publication status to decide entitlement renewal, completing a circular dependency between slices. A tenfold audiogram burst also saturates the shared worker client, delaying publishing because its connection pool has no workload limit. Mitigate the cycle with a versioned entitlement contract owned by billing and a publication event consumed by billing; isolate rendering behind a queue and give publishing its own bounded client resources.
Edge cases — concurrent publication attempts need version checks, queue retries need idempotent render keys, and partial failure needs a durable render_pending state. Ordering matters when an episode is unpublished while an older render completion arrives.
Sketch (illustrative pseudocode, not runnable):
slice PublishEpisode:
input: {episode_id, expected_version, actor}
handler:
authorize(actor)
publish_with_version(input)
emit EpisodePublished{episode_id, publication_version}
resources: {db_pool: 8, timeout: 1s}
slice Audiogram:
trigger: AudiogramRequested
concurrency: 12
idempotency_key: episode_id + render_revision
boundary_test:
forbid: slice_a imports slice_b.handler
allow: versioned contracts and tiny shared value types
Trade-offs
- Benefit: features stay cohesive and evolvable — changes land in one place and dead features delete cleanly.
- Cost: some duplication across slices, and without discipline the shared kernel either starves or swells.
When to Use / When Not to Use
Use when:
- Features evolve independently and cross-layer changes dominate.
Avoid when:
- Shared domain rules must stay uniform across slices — add a shared kernel or switch to Layered.
Anti-pattern / Failure Mode
- Misuse: Slices duplicating the same domain logic with drift.
- Review signal: No shared contracts where consistency matters.
Failure Modes / Trade-offs
- Shared-kernel gravity: entitlement rules, UI formatting, persistence, and transport types accumulate in
common. Every slice then ships in lockstep and deletion becomes risky. - Copy-paste divergence: duplicated authorization or money logic drifts across slices. Promote the third proven repetition to a contract with one policy owner, not a helper full of options.
- Accidental distributed monolith: handlers directly invoke other handlers until a feature change triggers a broad build. Import checks and consumer-driven contract tests expose the coupling.
- Change trade-off: local choices and clean feature deletion speed delivery, but inconsistent slice idioms can make cross-feature maintenance and platform governance harder.
Ownership review. A slice should have a named feature owner and a reason to change; utility folders with callers from every slice belong to a platform contract or need splitting.
Contract review. Events and public queries crossing slices need compatibility tests just as network APIs do, even when current calls remain in-process.
Resource review. Measure each slice’s database, queue, and downstream usage separately so a convenient shared client does not erase backpressure boundaries.
- Duplication trade-off: copying a tiny formatting rule can be safer than sharing a volatile helper, but copying regulated decisions creates unacceptable drift.
- Discovery trade-off: feature folders make behavior easy to locate, while global policies become harder to inventory without a registry of cross-cutting composition.
- Deletion trade-off: clean deletion works only when database migrations, events, schedules, and dashboards are also owned and retired with the slice.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Several feature teams with mostly independent requirements | Use slices and automated import boundaries to reduce cross-team edits. |
| Tight delivery budget and high feature churn | Use simple per-slice implementations instead of building reusable layers up front. |
| Strong enterprise mandate for identical persistence and workflow style | Avoid unrestricted slice-by-slice technology choices; standardize a thin composition root. |
| Compliance-sensitive authorization or money rules | Use cautiously: centralize those policies under explicit owners rather than accepting independent duplicates. |
Related Patterns
- Layered — the technical-layer organization that slices replace; compare before choosing.
- Clean — can be combined per-slice (each slice with its own mini use case) when rules need rigor.
- Hexagonal — slices can each expose their own ports if swappable infrastructure matters.
- Small Batch — slices ship independently.
- Multi-Tenant SaaS — slices isolate tenants.
CQRS + Event Sourcing
Intent
Separate the model that handles writes from the model that serves reads, and persist state changes as an immutable sequence of events that is the source of truth.
When It Helps
- Reads and writes have very different shapes — complex transactional writes versus fast, denormalized queries.
- Audit history matters: you must answer not just the current state but how it got there.
- Rebuilding views, replaying history, or deriving new projections from past facts is valuable.
Structure
flowchart LR Clients -->|commands| Write[Write Model] Write --> Log[(Event Log: immutable, append-only)] Log --> Projector[Projectors] Projector --> R1[(Read Model: Orders View)] Projector --> R2[(Read Model: Search Index)] Clients -->|queries| R1 Clients -->|queries| R2
Deployment unit: write side, projectors, and read stores deploy as separate units fed by the same log. Communication: commands flow into the write model; events flow out of the log into projectors; queries never touch the write model directly. Data ownership: the event log is the authoritative truth; read models are disposable projections that can be rebuilt from it at any time.
Rules
- All state changes append immutable events to the log — never update or delete past events in place.
- The write model validates commands; the read models serve queries; neither does the other’s job.
- Projectors must be replayable: any read model can be dropped and rebuilt solely from the event log.
- Event schema evolution is additive — old events stay readable so replays keep working.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch: commands -> events -> projections
command: PlaceOrder(cart) -> write model validates -> append:
events: [order.initiated, order.paid, order.shipped]
projector order-view:
on order.initiated -> insert row {status: pending}
on order.paid -> update row {status: paid}
on order.shipped -> update row {status: shipped}
query: get_order(id) reads order-view (never the log directly)
rebuild: drop order-view, replay events 1..N -> identical view
Basic Recap
CQRS separates command handling from query models, and event sourcing stores each accepted state change as an immutable event. The write model enforces invariants and appends events; projectors derive disposable read views from the log. Replays support audits, historical reconstruction, and new queries without changing the original decisions. This power brings eventual consistency, schema evolution, and projection operations.
Complex Scenario
A bank disputes service must explain every status transition while serving both agent timelines and high-volume customer summaries. Commands append events with an expected aggregate version, and separate projectors maintain a summary database and a search index. A new regulatory view should be buildable from the same history. Customer screens may read a projection, but dispute decisions always go through the write model.
flowchart LR
Agents["Dispute agents"] --> Commands["Command API and write model"]
Commands --> Version{"Expected version matches?"}
Version -->|yes| Log[("Immutable dispute event log")]
Log --> SummaryProjector["Summary projector"]
Log --> SearchProjector["Search projector"]
Log --> RegulationProjector["Regulatory projector"]
SummaryProjector --> SummaryDB[("Customer summary DB")]
SearchProjector --> Search[("Case search index")]
RegulationProjector --> AuditView[("Regulatory timeline view")]
Customers["Customer queries"] --> SummaryDB
Agents --> Search
Failure walkthrough. The summary projector crashes on an unknown legacy event while commands continue appending. Customer balances remain stale, retries of the same event block its partition, and a traffic spike makes the lag visible as contradictory agent and customer screens. Mitigate with additive event upcasting, idempotent projector checkpoints, quarantine plus an alerted replay procedure, and read responses that expose projection freshness; rebuild the fixed projection into a new store before switching queries atomically.
Edge cases — concurrent commands use optimistic version checks, command retries need deterministic idempotency, and event ordering is guaranteed per aggregate rather than across every dispute. Memory pressure during replay requires batched checkpoints instead of loading the full log into one process.
Sketch (illustrative pseudocode, not runnable):
command AcceptEvidence:
key: dispute_id + command_id
precondition: aggregate_version == expected_version
on_success: append EvidenceAccepted{event_version: 3, ...}
on_version_conflict: reload_and_reject_or_revalidate
projector customer-summary:
batch_size: 500
checkpoint: transactional_with_projection_rows
on legacy EvidenceAccepted.v1:
upcast_to_v3(defaults_from_original_payload)
on unrecognized_event:
stop_partition_and_alert
read customer-summary:
return {summary, projected_through, freshness}
never_claim: authoritative_current_write_state
Trade-offs
- Benefit: read/write scaling and a complete audit trail — queries stay fast on tailored views while every state change remains replayable history.
- Benefit: temporal insight — past states can be reconstructed and new views derived without migrating the write path.
- Cost: two models to maintain plus projector lag — reads are eventually consistent and debugging spans commands, log, and projections.
- Cost: event-schema and storage discipline — the immutable log grows forever and needs versioning, retention, and replay tooling.
When to Use / When Not to Use
Use when:
- Reads and writes scale or evolve differently; audit/replay matters.
Avoid when:
- Simple CRUD with one model sufficing — the split adds cost.
Anti-pattern / Failure Mode
- Misuse: Applying CQRS to every aggregate, duplicating models with no scaling need.
- Review signal: Event log with no schema evolution plan.
Failure Modes / Trade-offs
- Event log as mutable database: teams patch history to fix projections, destroying the audit guarantee. Corrections should be new facts with a clear relationship to earlier events.
- Leaky event schema: serialized class internals become permanent public history, making refactoring hazardous. Use explicit business schemas and tested upcasters.
- Read-your-write surprise: a command returns success but an immediate query shows the old view. Return the new version, use a command result view, or apply bounded consistency waiting only where required.
- Complexity trade-off: independent read shapes and complete history are valuable, but every feature now touches commands, events, upcasters, projections, and replay tooling.
History review. Event payloads should record business facts and decision context, not secrets copied from request bodies; immutability makes careless sensitive data especially durable.
Projection review. Track lag per projection and partition, test rebuilds routinely, and keep projector code versioned alongside the read schema it produces.
Command review. Validate invariants against the aggregate’s replayed state and reject stale expected versions explicitly rather than overwriting another agent’s decision.
- Privacy trade-off: deletion requests may require crypto-shredding or separate personally identifiable data because rewriting an immutable history is not an acceptable erasure strategy.
- Storage trade-off: snapshots can shorten replay but add another versioned artifact and never replace the events needed for a new projection.
- Operations trade-off: read stores are disposable in theory only when replay capacity, backfill traffic, cutover, and correctness checks have been rehearsed.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Compliance requires attributable, reconstructable decision history | Use immutable events with access controls, schema governance, and tested retention rules. |
| Reads and writes have sharply different scale and query shapes | Use tailored projections and scale them separately from command validation. |
| Users require immediate globally consistent reads after every write | Avoid asynchronous projections on that path, or provide a synchronous read-your-write mechanism. |
| Small team with ordinary CRUD and no audit or replay requirement | Avoid event sourcing; current-state persistence is much cheaper to operate. |
| Storage budget cannot retain indefinite history | Use cautiously: define lawful archival and snapshot policies without silently deleting required audit facts. |
Related Patterns
- Event-Driven — shares events and brokers, but this pattern adds read/write separation and a persistent log as truth; event-driven alone is only about async delivery.
- Microservices — a service can adopt CQRS internally while still exposing a normal API to other services.
- Modular Monolith — a module can use event sourcing for its own state without distributing the whole system.
- Event Sourcing (#51) and CQRS (#52) — principle summaries.
- Event-Driven Payments — replayable payments exercise.
Event-Driven
Intent
Let services react to things that happened — published events — instead of calling each other directly, so producers and consumers stay decoupled in time and knowledge.
When It Helps
- Workflows fan out: one action (order placed) should trigger many reactions (billing, email, analytics).
- Producers should not wait for or even know their consumers.
- Load is spiky and consumers should drain work at their own pace.
Structure
flowchart LR P1[Producer: Checkout] -->|publishes order.placed| Broker[(Event Broker)] Broker --> C1[Consumer: Billing] Broker --> C2[Consumer: Notifications] Broker --> C3[Consumer: Analytics] C1 --> DB1[(Billing DB)] C2 --> DB2[(Notifications Store)] C3 --> DB3[(Analytics Store)]
Deployment unit: producers, consumers, and the broker each deploy and scale independently. Communication: asynchronous event delivery through a broker (queue/stream log style); producers never call consumers directly. Data ownership: each consumer owns its store and builds it from the events it subscribes to; the broker owns only transient delivery, not domain truth.
Rules
- Producers publish facts about what happened, never commands telling a specific consumer what to do.
- Consumers own their subscription position and must handle duplicate or out-of-order delivery idempotently.
- Event schemas evolve backward-compatibly; breaking changes ship as new event versions or new topics.
- The broker is infrastructure: business rules live in producers and consumers, not in routing configuration.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch: broker-based async delivery
topic: order.placed (v2: {order_id, total, items[]})
producer checkout:
on payment_accepted -> publish(order.placed, {...})
consumer billing:
on order.placed -> charge(total) # idempotent on order_id
consumer notifications:
on order.placed -> send_email(items) # retries on failure
Basic Recap
Event-driven architecture publishes durable facts that other components can consume asynchronously. Producers do not need to know every reaction, and consumers can scale or recover at their own pace. A broker buffers delivery, but domain truth remains with the producing application unless a stronger log-based model is chosen. The approach exchanges immediate consistency and simple call traces for loose coupling and elasticity.
Complex Scenario
A ticketing platform emits OrderConfirmed after a database commit, triggering seat delivery, loyalty points, fraud scoring, and analytics. A new consumer should be addable without changing checkout. Each consumer keeps its own checkpoint and store, and event versions include an order identifier and occurrence time. Checkout uses an outbox so a successful order cannot silently lose its event.
flowchart LR
Checkout["Checkout producer"] --> Tx["Order transaction and outbox"]
Tx --> OrderDB[("Orders DB")]
Relay["Outbox relay"] --> Broker[("Partitioned event broker")]
Tx --> Relay
Broker --> Delivery["Seat delivery consumer"]
Broker --> Loyalty["Loyalty consumer"]
Broker --> Fraud["Fraud consumer"]
Broker --> Analytics["Analytics consumer"]
Delivery --> Mail["Email provider"]
Delivery --> DLQ[("Delivery dead-letter topic")]
Loyalty --> PointsDB[("Points DB")]
Analytics --> Warehouse[("Analytics store")]
Failure walkthrough. During a tenfold sales burst, the email provider goes down and delivery retries repeatedly at the head of each partition. Lag grows, duplicates reach loyalty after redeployments, and checkout would fail if it published synchronously to a congested broker. Mitigate with outbox-based producer decoupling, consumer idempotency records, bounded retries with backoff, a dead-letter path plus replay tooling, and consumer scaling by lag without exceeding downstream provider limits.
Edge cases — concurrency needs per-order aggregate versions, retries assume at-least-once delivery, and ordering is normally preserved only within a partition key. Partial failure requires committing the consumer state and checkpoint atomically where possible, or making replay harmless.
Sketch (illustrative pseudocode, not runnable):
event OrderConfirmed.v2:
key: order_id
fields: {event_id, order_id, occurred_at, seats[], total}
compatibility: additive_fields_only
consumer seat-delivery:
group: delivery-production
on event:
if inbox.contains(event_id): acknowledge
else: send_and_record_inbox(event)
retry: exponential_backoff(max=5)
on_exhausted: dead_letter_with_cause
operations:
scale_signal: consumer_lag
alert: oldest_lag > 90s or dead_letter_growth
Trade-offs
- Benefit: loose coupling and elastic scaling — add consumers without touching producers, and let slow consumers lag without blocking checkout.
- Benefit: resilience to bursts — the broker buffers spikes so producers stay fast while consumers catch up.
- Cost: eventual consistency and observability gaps — tracing a single user request across topics, retries, and replays is harder than following one call chain.
- Cost: broker operations — schema registry, partition sizing, retention, dead-letter handling, and replay tooling become permanent upkeep.
When to Use / When Not to Use
Use when:
- Reactions across services with temporal decoupling via a broker.
Avoid when:
- Request/response with strong consistency needs — prefer direct calls or CQRS reads.
Anti-pattern / Failure Mode
- Misuse: Assuming broker delivery equals exactly-once processing without idempotent consumers.
- Review signal: Unordered consumers depending on global event order.
Failure Modes / Trade-offs
- Event soup: vague events such as
ObjectUpdatedcarry no stable business meaning, forcing consumers to inspect mutable producer state. - Distributed schema coupling: a producer renames a field and breaks unknown consumers. Registry checks and consumer-driven contract tests should gate publication.
- Poison-message blockage: endless retries prevent later valid events from progressing. Dead-lettering is useful only when ownership, alerting, and replay procedures exist.
- Consistency trade-off: producers stay responsive during bursts and consumers evolve independently, but users and operators must handle stale views and delayed reactions.
Flow review. Document which business fact each topic carries, its partition key, retention, owner, and known consumers; a topic named after a technical layer is usually a weak contract.
Replay review. Reprocessing history must not resend customer email or award points twice, so side-effect consumers need separate replay modes or durable idempotency evidence.
Lag review. Monitor the oldest unconsumed timestamp as well as message count, since many tiny events can hide a badly delayed consumer.
- Broker trade-off: managed brokers reduce infrastructure work but still require schema, quota, residency, recovery, and cost decisions.
- Coupling trade-off: producers avoid direct consumer dependencies, yet consumers become semantically dependent on event meaning and completeness.
- Debugging trade-off: correlation IDs connect a workflow across topics, but they do not replace checkpoints, dead-letter context, and a timeline of consumer decisions.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Bursty traffic with work that can complete later | Use broker buffering and scale consumers against measured lag. |
| Many independent reactions to one business fact | Use versioned events to avoid changing the producer for each consumer. |
| User must receive an authoritative decision within 100 ms | Avoid making asynchronous reactions part of that decision path. |
| Tiny team without broker and replay operating experience | Avoid a broad event backbone; start with a managed queue for one clear workflow. |
| Compliance requires an immutable audit trail | Use cautiously: delivery events alone are insufficient unless retention, integrity, and access controls are guaranteed. |
Related Patterns
- Microservices — services frequently use events as their decoupling mechanism.
- CQRS + Event Sourcing — differs by centering on a persistent event log plus separate read/write models, not just broker delivery.
- Serverless — functions pair naturally with events as triggers that scale to zero between bursts.
- CQRS & Event Sourcing — broker reactions vs log-as-truth.
- Observer — in-process precursor.
- Idempotency — retries are safe only with idempotent consumers.
Microservices
Intent
Decompose the system into small services that each own one capability and its data, and that build, deploy, and scale independently.
When It Helps
- Multiple autonomous teams need to ship without blocking each other.
- Different parts of the system have very different scaling or availability needs.
- The domain has stable, well-understood bounded contexts worth isolating.
Structure
flowchart LR Clients --> GW[API Gateway] GW --> S1[Service: Orders] GW --> S2[Service: Catalog] GW --> S3[Service: Billing] S1 --> DB1[(Orders DB)] S2 --> DB2[(Catalog DB)] S3 --> DB3[(Billing DB)] S1 <-->|sync API or async events| S3
Deployment unit: each service is its own artifact, pipeline, and runtime (container set or serverless unit). Communication: synchronous calls (HTTP/gRPC) for queries plus asynchronous events for state changes; no shared in-process calls. Data ownership: strict per-service databases — services never share tables, only APIs or events.
Rules
- Each service owns its data exclusively; access from outside happens only through its API or published events.
- Services deploy independently — a deploy of one must never require a lockstep deploy of another.
- Prefer backward-compatible API evolution over coordinated breaking changes.
- Each service carries its own health checks, dashboards, and runbooks; there is no single shared runtime to hide behind.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch: per-service deploy + owned data
service orders:
deploy: orders:v42 (3 replicas, scales on queue depth)
db: orders_db (owned, no external access)
publishes: order.placed
service billing:
deploy: billing:v17 (2 replicas, scales on CPU)
db: billing_db (owned)
subscribes: order.placed -> charge()
# forbidden: billing querying orders_db directly
Basic Recap
Microservices divide a system into independently deployable capabilities with explicit APIs and private data ownership. Teams can release and scale a service without shipping the rest of the system. The architecture replaces in-process calls with networks, partial failures, versioned contracts, and distributed data decisions. It is an organizational and operational commitment, not merely a smaller code layout.
Complex Scenario
An online shop runs catalog, cart, inventory, orders, and payment as separate services. Checkout needs a timely reservation and payment result, while recommendations can arrive later. Each service owns its database and scaling policy, and a gateway applies caller authentication. A flash sale creates a burst concentrated on inventory rather than evenly across the system.
flowchart LR
Clients["Web and mobile clients"] --> Gateway["API gateway"]
Gateway --> Cart["Cart service"]
Gateway --> Orders["Orders service"]
Gateway --> Catalog["Catalog service"]
Orders --> Inventory["Inventory service"]
Orders --> Payment["Payment service"]
Cart --> CartDB[("Cart DB")]
Catalog --> CatalogDB[("Catalog DB")]
Inventory --> StockDB[("Stock DB")]
Orders --> OrderDB[("Order DB")]
Payment --> Ledger[("Payment ledger")]
Orders --> Events[("Order events")]
Events --> Recommendations["Recommendation worker"]
Failure walkthrough. Traffic spikes tenfold and inventory replicas saturate; orders retry immediately, multiplying load until gateway deadlines expire and payment calls queue behind doomed reservations. Mitigate by scaling inventory on reservation latency and queue depth, propagating one end-to-end deadline, using jittered retry budgets and circuit breakers, and moving noncritical recommendations to events. Payment must never be retried blindly after an ambiguous response; its operation key supports safe status recovery.
Edge cases — concurrent purchases need atomic stock reservation, retries need stable operation keys, and partial failure needs a saga that releases stock or records a compensating refund. Ordering across order and stock events is guaranteed only per documented key.
Sketch (illustrative pseudocode, not runnable):
request checkout:
trace_id: propagated
total_deadline: 2500ms
operation_key: client_generated_uuid
call orders -> inventory:
timeout: min(600ms, remaining_deadline)
retries: 1_if_budget_allows
circuit_breaker: open_after_50_percent_timeouts
service inventory:
autoscale_on: [reservation_p95, pending_reservations]
min_replicas: 6
reservation: conditional_write(stock > requested)
recovery:
payment_unknown -> query_by_operation_key
reservation_abandoned -> expire_after_2m
Trade-offs
- Benefit: independent scaling and deployment — hot services scale alone and teams release on their own cadence.
- Benefit: fault and technology isolation — one service can fail or adopt a new stack without forcing the whole system along.
- Cost: distributed operations — service discovery, versioning, retries, tracing, and many pipelines multiply operational load.
- Cost: data consistency gets harder — cross-service transactions become sagas or eventual consistency instead of one database commit.
When to Use / When Not to Use
Use when:
- Capabilities needing independent scaling, deploys, and data ownership.
Avoid when:
- One team with uniform scale — Modular Monolith is cheaper.
Anti-pattern / Failure Mode
- Misuse: Shared database across services with distributed transactions everywhere.
- Review signal: Chatty synchronous calls recreating the monolith over the network.
Failure Modes / Trade-offs
- Distributed monolith: services share tables, release trains, or deep synchronous call chains, so none can fail or deploy independently.
- Chatty boundaries: an entity per service creates many network calls for one screen. Measure user operations before drawing service boundaries.
- Retry amplification: every layer repeats the same attempt policy, turning one slowdown into a multiplicative storm. One caller should own the retry decision within a shared deadline.
- Ownership trade-off: autonomous deployment and focused scaling are powerful, but tracing, contract tests, data reconciliation, and on-call coverage become permanent costs.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Multiple autonomous teams with stable bounded contexts | Use services where ownership and release independence solve measured coordination problems. |
| Very different scaling or availability targets per capability | Use independently scalable services with explicit dependency budgets. |
| Team lacks mature observability and on-call capacity | Avoid broad decomposition; a modular monolith has a smaller operational burden. |
| Strict end-to-end latency below a few milliseconds | Avoid deep service chains; colocate critical decisions and use events for secondary work. |
| Compliance scope differs sharply between payment and content | Use separate deployables only if credentials, networks, and audit ownership are separated too. |
Related Patterns
- Modular Monolith — prefer it first when boundaries are uncertain; it is cheaper to run than services.
- Event-Driven — the common way microservices stay decoupled, reacting to events instead of chaining calls.
- SOA — an earlier, coarser-grained take on reusable services, often with a central bus instead of independent services.
- You Build It, You Run It — ownership per service.
- Event-Driven Payments — duplicate-safe processing across services.
Modular Monolith
Intent
Keep a single deployable for operational simplicity while enforcing strict internal module boundaries so the system can evolve or split later.
When It Helps
- The team is growing (roughly 8–30 developers) and stepping on each other’s code.
- You suspect services will be needed eventually but the boundaries are not proven yet.
- You want independent development streams without paying for distributed operations today.
Structure
flowchart TB Clients --> Gateway[Single Entry Point] Gateway --> A[Module: Orders] Gateway --> B[Module: Catalog] Gateway --> C[Module: Billing] A -.->|public API only| SharedKernel[Shared Kernel] B -.->|public API only| SharedKernel C -.->|public API only| SharedKernel A --> DB[(Shared DB, Schema per Module)] B --> DB C --> DB
Deployment unit: one artifact containing all modules, deployed together. Communication: synchronous calls through each module’s public API only — no reaching into another module’s internals. Data ownership: each module owns its tables or schema; other modules read them only via the owning module’s API.
Rules
- Modules may depend only on another module’s declared public API, never on its internals.
- No shared mutable state between modules except through explicit APIs or events.
- Each module owns its data — cross-module queries go through the owner, not direct table joins.
- All modules version and deploy together; extraction to a service must not require rewriting callers.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch: enforced module boundary
module orders:
public: place_order(cart) -> order
private: tables orders, order_lines
module billing:
public: charge(order) -> receipt
private: tables invoices, payments
# allowed:
billing.charge(orders.place_order(cart))
# forbidden:
billing.read_table(orders.order_lines) # must call orders API
Basic Recap
A modular monolith keeps one process and deployment while assigning business capabilities to modules with explicit public APIs. Each module owns its data and hides internal implementation from other modules. The approach supports parallel development without introducing network failures between every capability. Its benefits depend on automated boundary enforcement, not folder names alone.
Complex Scenario
An education platform contains enrollment, billing, course delivery, and identity modules in a single deployable. Enrollment must confirm that a learner has an active entitlement before unlocking a course. To meet a deadline, enrollment imports billing’s repository and reads its tables directly. Billing then calls enrollment internals to revoke access after a refund, producing a cycle that only appears in full integration builds.
flowchart TB
Learners["Learner web app"] --> Entry["Single application entry point"]
Staff["Staff admin"] --> Entry
Entry --> Enrollment["Module: Enrollment"]
Entry --> Billing["Module: Billing"]
Entry --> Courses["Module: Course delivery"]
Entry --> Identity["Module: Identity"]
Enrollment --> EnrollAPI[["Enrollment public API"]]
Billing --> BillingAPI[["Billing public API"]]
Enrollment --> ESchema[("Enrollment schema")]
Billing --> BSchema[("Billing schema")]
Enrollment <-. "repository and internal-call cycle" .-> Billing
Events["In-process domain events"] --> Courses
BillingAPI --> Events
Failure walkthrough. A billing schema rename breaks enrollment at startup, while the dependency cycle prevents either module from being tested alone. During a refund burst, nested in-process calls also hold enrollment and billing transactions longer, causing lock contention across both schemas. Mitigate by exposing EntitlementQuery and RefundCompleted contracts, deleting cross-schema access, and enforcing an acyclic module graph in the build; keep cross-module transaction expectations explicit.
Edge cases — concurrent refunds need per-learner ordering or versioning, retries need idempotent entitlement revocation, and partial failure inside one transaction needs a documented commit boundary. In-process events dispatched after commit must not be lost when the process stops.
Sketch (illustrative pseudocode, not runnable):
module billing:
public:
EntitlementQuery.active?(learner_id, course_id)
events: RefundCompleted{refund_id, learner_id, version}
owns: billing_schema.*
transaction: commit_before_event_dispatch
module enrollment:
depends_on: [billing.public, identity.public]
owns: enrollment_schema.*
on RefundCompleted:
revoke_once(refund_id, learner_id)
architecture_test:
require: acyclic_public_dependencies
forbid: cross_module_table_access
Trade-offs
- Benefit: scales development — teams work in parallel inside clear boundaries without distributed-system overhead.
- Benefit: extraction is cheap later: a module with a clean API and owned data can become a service with minimal rewiring.
- Cost: boundary discipline needs tooling and reviews; without enforcement it decays back into a tangled monolith.
- Cost: runtime scaling is still all-or-nothing since every module ships in one process, and a faulty module can crash its neighbors.
When to Use / When Not to Use
Use when:
- One team needing boundaries first without service ops overhead.
- Extraction-ready structure before splitting.
Avoid when:
- Capabilities needing independent scaling/deploys now — go Microservices.
Anti-pattern / Failure Mode
- Misuse: Module boundaries only on paper, bypassed by direct DB access.
- Review signal: Cross-module imports with no fitness-function enforcement.
Failure Modes / Trade-offs
- Namespace-only modules: packages look separate but freely share entities, tables, and mutable singletons. Boundary tests should fail before integration tests expose the leak.
- Distributed-monolith rehearsal: synchronous APIs connect every module in deep chains, reproducing service coupling without network isolation. Prefer domain events for secondary reactions.
- Premature extraction: teams split modules into services to escape poor discipline, only to add latency and deployment coupling. Fix ownership before changing the deployment unit.
- Scaling trade-off: development can be separated cleanly, but all modules still share runtime capacity, release timing, and potentially the failure domain.
Boundary review. Generate the module dependency graph on every build and test public APIs without importing implementation packages or opening another module’s schema.
Transaction review. A call crossing modules may appear to be a local function while still coordinating two policies and lock sets; document atomicity and event dispatch at the API.
Extraction review. Candidate modules need their own migrations, configuration, metrics, and data export before becoming services, otherwise extraction simply publishes internal coupling over HTTP.
- Test trade-off: module tests become focused, but full-process tests remain necessary for shared middleware, transaction managers, and composition-root mistakes.
- Security trade-off: database users per module can enforce ownership more reliably than package visibility, though credential management becomes more involved.
- Release trade-off: clear module ownership reduces merge friction but cannot provide independent rollback or deployment timing.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Team of 8–30 with increasingly clear domain ownership | Use explicit module APIs, owned schemas, and dependency tests. |
| Small infrastructure budget with future service extraction likely | Use one deployment now; extract only modules with proven scaling or release needs. |
| Hard requirement that billing deploy without enrolling changes | Avoid a monolith for that capability because deployment independence is the constraint. |
| Compliance requires separation of duties but not separate runtimes | Use module-owned credentials and reviewed APIs, backed by database permissions and audit tests. |
Related Patterns
- Monolithic — the simpler starting point this pattern adds discipline to.
- Microservices — the natural next step once a module’s boundary and load justify independent deployment.
- CQRS + Event Sourcing — can be applied inside one module to separate its reads from its writes.
- Modular Monolith Orders — extraction-ready exercise.
- Common Closure — co-locate what changes together.
Monolithic
Intent
One codebase, one executable, one deployment: the whole system ships and runs as a single unit.
When It Helps
- A small team (roughly 1–8 developers) building the first version of a product.
- The domain boundaries are still unclear and likely to shift.
- Operational simplicity matters more than independent scaling of parts.
Structure
flowchart TB Clients --> App[Single Application] App --> UI[UI Module] App --> Logic[Business Logic Module] App --> DataAccess[Data Access Module] DataAccess --> DB[(Shared Database)]
Deployment unit: one artifact (single binary, container, or package) replicated as a whole. Communication: in-process function calls between modules; external clients use one entry point. Data ownership: a single shared database owned by the whole application.
Rules
- All modules ship together — no module may be deployed or versioned alone.
- Cross-module calls stay in-process; do not add network hops inside the monolith.
- All data access goes through the data-access module, never directly from UI code.
- Scaling means replicating the entire application behind a load balancer.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch: one deployable, modules call each other in-process
deployable: shop-app v1.4
modules: [web-ui, catalog, checkout, data-access]
request -> web-ui -> catalog.list_items()
request -> web-ui -> checkout.place_order()
checkout.place_order() -> data-access.save(order)
Basic Recap
A monolith packages its user interface, business capabilities, and data access into one deployable application. Internal calls remain in-process and modules commonly share one database. Replicas run the same artifact, which keeps deployment, transactions, and debugging comparatively simple. The pattern trades independent scaling and fault isolation for low operational overhead.
Complex Scenario
A municipal permitting system runs applicant pages, staff review, payments, and monthly compliance reports in one application. Most requests are short, but a year-end report scans permit history and builds large in-memory summaries. The same database and runtime serve every workload. The operations team must absorb reporting demand without turning the whole product into separate services.
flowchart TB
Applicants["Applicants"] --> LB["Load balancer"]
Staff["Permit staff"] --> LB
LB --> App1["Permit application replica A"]
LB --> App2["Permit application replica B"]
App1 --> Modules["UI, review, payments, reporting modules"]
App2 --> Modules
Modules --> DB[("Primary permit database")]
Modules --> Files[("Document storage")]
Reporter["Scheduled report trigger"] --> Modules
Failure walkthrough. A tenfold increase in requested reports consumes heap and database connections until applicant requests time out; one out-of-memory termination also removes payment capacity on that replica. Mitigate with a bounded report queue, streaming instead of in-memory aggregation, per-workload connection pools, and a small always-on request reserve. If reporting remains disruptive, run the same artifact with report-only routing and resource limits rather than immediately splitting domain services.
Edge cases — concurrent staff edits need record versions, payment retries need idempotency, and partial failure needs a durable report checkpoint. Memory pressure is a cross-module concern because every module shares the process heap.
Sketch (illustrative pseudocode, not runnable):
deployment permit-app:
artifact: permits-2026.11
request_replicas: 3
report_replicas: 1
shared_database: permits_primary
report_worker:
queue: compliance-reports
concurrency: 2
result_streaming: true
checkpoint_every: 1000_permits
db_pool: 4
request_path:
reserved_db_connections: 12
payment_idempotency: required
Trade-offs
- Benefit: simplest to build, test, and deploy — one pipeline, one artifact, and easy end-to-end debugging.
- Benefit: in-process calls keep latency low and refactoring across modules cheap while the product is young.
- Cost: scaling is coarse — a busy checkout path forces replication of the entire app, wasting resources.
- Cost: a single failure or slow dependency can take down everything, and the codebase gets harder to split as it grows.
When to Use / When Not to Use
Use when:
- Solo project or early product with one team and one deployable.
Avoid when:
- Independent scaling or deploy per capability outweighs ops cost — consider Modular Monolith first, then Microservices.
Anti-pattern / Failure Mode
- Misuse: A ‘modular’ monolith with no boundaries — big ball of mud.
- Review signal: One slow dependency stalling the whole deploy.
Failure Modes / Trade-offs
- Big-ball-of-mud drift: unrestricted imports and shared tables erase module ownership, making a small change require system-wide knowledge.
- Coarse failure domain: a leak, deadlock, or CPU-heavy task in one feature harms unrelated features because runtime resources are shared.
- Deployment congestion: every fix ships the entire artifact, so a large team serializes releases and expands rollback scope.
- Operational trade-off: one pipeline and local calls are inexpensive to understand, but scaling replicates idle capabilities alongside busy ones.
Capacity review. Load-test reports and applicant traffic together, because separate benchmarks hide contention for heap, worker pools, caches, and database connections.
Recovery review. A replica restart must resume queued reports and preserve payment idempotency; running one artifact does not automatically make recovery atomic.
Ownership review. Even without service boundaries, assign modules to code owners and forbid direct cross-feature table writes to keep future changes understandable.
- Data trade-off: one database supports easy joins and transactions, but large reports can block online writes and broad credentials increase the impact of a flaw.
- Release trade-off: a single rollback is conceptually simple, yet reverting the artifact may revert unrelated urgent features at the same time.
- Scaling trade-off: adding replicas is effective until one database or shared external dependency becomes the actual bottleneck.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Team of 1–8 with uncertain product boundaries | Use a monolith; refactoring in one codebase is cheaper than premature distribution. |
| Limited operations budget and no 24/7 platform team | Use one well-instrumented deployment with managed database backups. |
| Strict latency for checkout beside heavy analytics | Use cautiously: isolate workload resources, or avoid one runtime if isolation cannot meet the budget. |
| Compliance demands independent payment certification and release cadence | Avoid a single deployment for that scope when certification boundaries cannot be isolated. |
Related Patterns
- Modular Monolith — keeps one deployment but enforces strict module boundaries as a stepping stone out.
- Microservices — splits the monolith into independently deployable services when teams and scale demand it.
- Serverless — removes server management entirely, opposite extreme from managing one server app yourself.
- Single Source of Truth — one codebase, one truth.
- Layered — typical in-process structure.
Serverless
Intent
Run code and backends without managing servers: ephemeral functions and managed services scale to demand — including to zero — and you pay per use.
When It Helps
- Traffic is bursty or unpredictable and idle servers would waste money.
- A small team wants to ship without operating runtimes, clusters, or OS patching.
- Workloads are event-triggered tasks (webhooks, file processing, scheduled jobs) rather than long-lived connections.
Structure
flowchart LR Clients --> Edge[Managed Gateway / CDN] Edge --> F1[Function: place-order] Edge --> F2[Function: get-catalog] F1 --> BaaS1[(Managed DB)] F1 -->|emits| Queue[(Managed Queue)] Queue --> F3[Function: send-receipt] F2 --> BaaS1
Deployment unit: individual functions (plus managed-backend configuration) deployed per function, not per server fleet. Communication: inbound via managed triggers (HTTP gateway, queue, timer, storage event); outbound via managed service APIs. Data ownership: state lives in managed backends (database, object store, queue) — functions themselves are stateless and own no durable data.
Rules
- Functions must be stateless — persist everything to a managed backend, never to local disk or memory across invocations.
- Keep functions small and single-purpose so cold starts stay short and permissions stay narrow.
- Design for retries and timeouts: every trigger may fire twice and every run has a maximum duration.
- Put shared logic in versioned layers or packages, not copy-pasted across dozens of functions.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch: function + trigger config, no servers
function place-order:
trigger: http POST /orders (via managed gateway)
timeout: 10s, memory: 512MB, concurrency: 100
env: ORDERS_TABLE (managed db reference)
steps:
- validate(request) -> save(ORDERS_TABLE) -> enqueue(receipt-queue)
function send-receipt:
trigger: receipt-queue message
steps:
- load(order) -> send_email() # idempotent on order_id
Basic Recap
Serverless systems run stateless code in provider-managed execution environments triggered by requests, events, or schedules. Durable state belongs in managed databases, queues, and object stores rather than function memory. Capacity can scale with demand and fall to zero, while billing follows consumption. The model reduces server operations but introduces provider limits, cold starts, and distributed configuration.
Complex Scenario
A document-signing product accepts webhooks, renders signed PDFs, and notifies recipients through managed functions. Rendering is CPU-heavy, while webhook acknowledgement must be fast and reliable. A queue separates ingestion from rendering, and signed files live in object storage. A customer campaign is expected to produce a sharp burst after a quiet period.
flowchart LR
Partners["Partner webhooks"] --> Gateway["Managed API gateway"]
Gateway --> Ingest["Function: ingest webhook"]
Ingest --> Queue[("Managed render queue")]
Ingest --> Meta[("Signing metadata DB")]
Queue --> Render["Function: render PDF"]
Render --> Pool["Database connection proxy"]
Pool --> Meta
Render --> Files[("Signed document storage")]
Files --> NotifyTrigger["Storage event trigger"]
NotifyTrigger --> Notify["Function: notify recipient"]
Notify --> Email["Managed email API"]
Failure walkthrough. Traffic rises tenfold after idle, so new webhook and renderer instances start together. Cold starts delay execution, queue retries multiply invocations, and hundreds of renderers open direct database connections until ingestion also fails. Mitigate by acknowledging only after durable queue storage, reserving finite renderer concurrency, reusing connections through a proxy, extending retry backoff beyond cold-start time, and keeping minimal warm capacity only for the latency-critical ingest path.
Edge cases — triggers may retry or arrive out of order, so rendering needs a deterministic signing-operation key and revision check. Concurrent completions require compare-and-swap metadata updates, and partial failure must leave retryable temporary files separate from the final signed object.
Sketch (illustrative pseudocode, not runnable):
function ingest-webhook:
timeout: 3s
reserved_concurrency: 40
minimum_warm_instances: 2
writes: queue_message{idempotency_key, document_revision}
response: accepted_only_after_queue_commit
function render-pdf:
timeout: 90s
memory: 2048MB
reserved_concurrency: 25
database: via_connection_proxy
success: atomic_publish(final_object, revision)
queue render-queue:
visibility_timeout: 120s
delivery: at_least_once
poison_policy: dead_letter_after_6_attempts
Trade-offs
- Benefit: near-effortless scaling — concurrency rises with demand and drops to zero cost when idle, with no capacity planning.
- Benefit: minimal operations — patching, availability zones, and runtime hardening shift to the provider.
- Cost: cold starts, timeouts, and runtime limits constrain long-running or latency-sensitive work.
- Cost: provider coupling and cost surprises — egress, invocations, and managed-service bills need monitoring, and deep provider features are hard to port.
When to Use / When Not to Use
Use when:
- Spiky workloads with minimal ops, event-triggered functions plus managed backends.
Avoid when:
- Long-running, stateful, or latency-critical paths with sustained load.
Anti-pattern / Failure Mode
- Misuse: Functions chained into a distributed monolith with hidden latency.
- Review signal: No idempotency on retried invocations causing duplicates.
Failure Modes / Trade-offs
- Function pinball: dozens of tiny synchronous functions add latency and make one business request difficult to trace. Group work by operational boundary, not by arbitrary code size.
- Hidden state: local caches or temporary files become required for correctness even though instances are ephemeral. Move durable workflow state to an explicit backend.
- Unbounded elasticity: functions scale faster than databases and partner APIs, shifting the outage downstream. Reserved concurrency is a backpressure tool as well as a cost control.
- Economic trade-off: idle and spiky workloads can be inexpensive, but sustained high utilization, egress, observability, and managed-service requests can exceed fleet costs.
Cold-path review. Measure initialization, dependency downloads, cold starts, and downstream connection setup separately; provisioned warmth cannot fix an oversized deployment package alone.
Permission review. Give ingest, render, and notify distinct identities and resource policies so a vulnerable parser cannot read unrelated documents or publish arbitrary events.
Cost review. Model invocation, duration, queue retention, storage, proxy, logs, and egress together under both burst and sustained-load assumptions.
- Recovery trade-off: short stateless runs simplify replacement, but workflow recovery still depends on durable checkpoints and idempotent external effects.
- Portability trade-off: ordinary language code may move easily while triggers, identity policies, queues, and observability remain deeply provider-specific.
- Consistency trade-off: queues and storage events create delays between signing and notification, so product status must reflect each completed stage.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Small team with sparse, unpredictable event traffic | Use managed triggers and scale-to-zero to minimize operations and idle spend. |
| Hard p99 latency below cold-start variance | Avoid on-demand cold paths, or budget for warm capacity and verify with production-like tests. |
| Long-running jobs beyond provider execution limits | Avoid one function per job; use a worker or explicitly checkpointed workflow. |
| Strict data residency and portability requirements | Use cautiously: select regionally compliant services and isolate provider-specific APIs behind tested boundaries. |
| Fixed monthly budget with possible viral load | Use concurrency caps, queue backpressure, and cost alarms rather than relying on infinite autoscaling. |
Related Patterns
- Event-Driven — serverless functions are usually triggered by events from queues, streams, or storage.
- Microservices — functions can serve as the smallest deployable unit, but without long-lived service processes.
- Monolithic — the opposite starting point: one always-on process you manage yourself versus zero-managed ephemeral units.
- Bounded Resource — configure timeouts and concurrency.
- Multi-Tenant SaaS — elastic bursts per tenant.
SOA (Service-Oriented Architecture)
Intent
Expose stable business capabilities as larger, reusable enterprise services shared across many applications, often mediated by a central integration layer.
When It Helps
- A large enterprise must reuse the same capabilities (identity, payments, customer records) across many applications.
- Central governance, auditing, or protocol translation is required between systems.
- Integrations outnumber greenfield builds: connecting existing systems matters more than shipping new ones.
Structure
flowchart LR AppA[App: Web Store] --> ESB[Enterprise Service Bus] AppB[App: Call Center] --> ESB AppC[App: Partner Portal] --> ESB ESB --> S1[Service: Customer] ESB --> S2[Service: Payments] ESB --> S3[Service: Inventory] S1 --> DB1[(Customer DB)] S2 --> DB2[(Payments DB)] S3 --> DB3[(Inventory DB)]
Deployment unit: coarse-grained services plus the central bus/gateway, each operated by a platform or service team. Communication: through the central bus or managed gateway — routing, transformation, and policy enforcement happen in the middle rather than point-to-point. Data ownership: each enterprise service owns its canonical data (one customer record, one payments ledger) shared by all consuming apps.
Rules
- Consumers integrate through published service contracts via the bus, never by direct database access to a service’s store.
- Canonical data models are owned by their service; the bus translates formats but does not own business truth.
- Service contracts change slowly and with central versioning — reuse stability beats per-team velocity.
- Cross-cutting concerns (auth, auditing, rate limits) live in the bus/gateway layer, applied uniformly.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch: central bus routing + contract
service customer (v3, canonical):
contract: get_customer(id) -> {id, name, tier}
db: customer_master (owned)
bus route:
from: call-center-app.getCustomer
translate: legacy-xml -> customer-v3-json
policy: require(authenticated) + audit(log)
to: service customer.get_customer
Basic Recap
Service-oriented architecture exposes coarse business capabilities for reuse across applications and organizational units. Services own canonical data and publish governed contracts, often through a central bus or gateway. The mediation layer supplies routing, protocol translation, security, and auditing. This favors enterprise consistency and legacy interoperability over maximum team autonomy.
Complex Scenario
A manufacturing group runs a dealer portal, call center, and warranty application after several acquisitions. Customer, entitlement, and payment services provide canonical capabilities to each channel. The enterprise service bus translates legacy XML, applies access policy, and records audit events. A new partner program adds high-volume entitlement checks that need only a small subset of customer data.
flowchart LR
Dealer["Dealer portal"] --> Bus["Clustered enterprise service bus"]
CallCenter["Call center"] --> Bus
Warranty["Warranty application"] --> Bus
Partner["Partner batch gateway"] --> Bus
Bus --> Customer["Customer service v4"]
Bus --> Entitlement["Entitlement service"]
Bus --> Payments["Payment service"]
Customer --> CustomerDB[("Canonical customer DB")]
Entitlement --> EntDB[("Entitlement DB")]
Payments --> PayDB[("Payment ledger")]
Bus --> Audit[("Central audit archive")]
Bus --> Transform["XML and canonical-model transformation"]
Failure walkthrough. Partner volume grows tenfold and every request performs an expensive XML-to-canonical transformation on the bus. CPU saturation delays unrelated payment calls, while a central audit queue applies further backpressure to all routes. Mitigate by autoscaling stateless bus nodes, separating partner and payment route pools, moving bulky translation into versioned edge adapters, applying per-consumer quotas, and sending audit records asynchronously with monitored durable storage.
Edge cases — concurrent customer updates need canonical versions, retries need correlation and idempotency identifiers, and partial failure needs an explicit response when a service succeeds but audit delivery lags. Contract ordering matters when legacy batch requests are replayed after newer updates.
Sketch (illustrative pseudocode, not runnable):
route partner_entitlement_check:
consumer: partner-program
adapter: partner-xml-v2 -> entitlement-query-v3
target: entitlement-service
quota: 150_requests_per_second
timeout: 800ms
resource_pool: partner_only
audit: durable_async(correlation_id, actor, decision)
route payment_authorize:
resource_pool: payments_only
retry: none_without_idempotency_key
contract_change: central_review_required
bus_cluster:
nodes: autoscaled
forbidden: business_rules_inside_route_scripts
Trade-offs
- Benefit: reuse and consistency — one governed customer or payments service serves every channel with uniform rules and audit trails.
- Benefit: integration leverage — the bus absorbs protocol and format differences so legacy and modern apps can interoperate.
- Cost: the bus becomes a bottleneck and single point of governance friction — changes queue behind central teams and routing logic.
- Cost: coarse services plus central mediation add latency and upgrade risk; scaling means scaling shared infrastructure everyone depends on.
When to Use / When Not to Use
Use when:
- Enterprise reuse across business units with governed shared services.
Avoid when:
- Small org or fast-moving product where ESB governance slows delivery.
Anti-pattern / Failure Mode
- Misuse: Central ESB becoming a bottleneck and single point of failure.
- Review signal: Coarse services versioned without compatibility guarantees.
Failure Modes / Trade-offs
- Bus as business logic: route scripts accumulate entitlement and pricing decisions that service owners cannot test or version. Keep mediation technical and policy in named services.
- Governance deadlock: every contract change waits for one central committee, so teams bypass the bus with undocumented point-to-point links.
- Canonical-model overreach: one enormous customer schema tries to satisfy every department and changes constantly. Use bounded contracts and translate only necessary fields.
- Reuse trade-off: common capabilities and uniform controls reduce enterprise duplication, but mediation adds hops and concentrates scaling and release risk.
Contract review. Version canonical capabilities around consumer use cases and maintain compatibility windows; translating an old payload does not make an incompatible decision semantics safe.
Capacity review. Load-test shared routes together and independently, then reserve resources for payments and other critical traffic rather than trusting cluster-wide autoscaling alone.
Governance review. Central teams should publish service levels for contract review and bus changes so consumers can plan instead of creating shadow integrations.
- Audit trade-off: centralized evidence is consistent, but asynchronous auditing needs durability and reconciliation to avoid presenting buffered intent as completed history.
- Mediation trade-off: translation protects legacy consumers, while too many format versions increase CPU cost and make the effective contract difficult to understand.
- Availability trade-off: clustered bus nodes remove a single machine failure but cannot protect against a bad route deployment applied everywhere.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Many applications must reuse regulated customer or payment capabilities | Use governed service contracts with clear data ownership and audit controls. |
| Heterogeneous legacy protocols require interoperability | Use mediation for translation, preferably at isolated adapters or well-bounded routes. |
| Small product organization optimizing weekly independent releases | Avoid central bus governance; team-owned services or modules impose less coordination. |
| Strict low-latency path for a single application | Avoid unnecessary bus hops and test whether direct governed service access meets control requirements. |
| Central platform budget cannot support clustered, audited mediation | Avoid an ESB-centered design; a lightweight gateway plus explicit service contracts is safer. |
Related Patterns
- Microservices — finer-grained, team-owned services with decentralized governance instead of a central bus.
- Modular Monolith — a cheaper alternative when reuse is needed inside one organization without enterprise-wide integration.
- Event-Driven — can replace request/reply bus flows with async events where consumers do not need an immediate answer.
- Backward Compatibility — version shared contracts.
- API Consistency — uniform service surface.
Engineering Principles
Part of the unified study index: Home · how to choose in selection guide.
A study catalog of 110 software engineering, architecture, design, and development principles, grouped into 11 categories. Each principle has its own section with a definition, rationale, example, anti-pattern or failure mode, and related principles. Use it alongside the pattern selection guide and the architecture pages.
How to use this catalog
- Start with the category that matches your current problem.
- Read a principle’s Rationale before applying it; principles trade off against each other.
- Check the Anti-pattern note to recognize misuse.
- Follow Related links to neighboring principles and patterns.
Categories
- SOLID Principles — 1–5
- General Software Design Principles — 6–20
- Architecture Principles — 21–33
- Distributed Systems Principles — 34–52
- Performance and Resource Management Principles — 53–61
- Security Principles — 62–69
- Testing and Quality Principles — 70–77
- API and Protocol Design Principles — 78–84
- Development and Project Management Principles — 85–92
- Functional Programming Principles — 93–100
- BEAM / OTP Design Principles — 101–110
Contents at a glance
| # | Principle | Category |
|---|---|---|
| 1 | Single Responsibility Principle (SRP) | SOLID |
| 2 | Open/Closed Principle (OCP) | SOLID |
| 3 | Liskov Substitution Principle (LSP) | SOLID |
| 4 | Interface Segregation Principle (ISP) | SOLID |
| 5 | Dependency Inversion Principle (DIP) | SOLID |
| 6 | DRY | General Design |
| 7 | KISS | General Design |
| 8 | YAGNI | General Design |
| 9 | Separation of Concerns | General Design |
| 10 | Principle of Least Astonishment | General Design |
| 11 | Law of Demeter | General Design |
| 12 | Composition over Inheritance | General Design |
| 13 | Encapsulation | General Design |
| 14 | Information Hiding | General Design |
| 15 | Program to an Interface | General Design |
| 16 | Fail Fast | General Design |
| 17 | Defensive Programming | General Design |
| 18 | Least Privilege | General Design |
| 19 | Explicit over Implicit | General Design |
| 20 | Convention over Configuration | General Design |
| 21 | Separation of Architecture and Implementation | Architecture |
| 22 | Dependency Rule | Architecture |
| 23 | Hexagonal Architecture | Architecture |
| 24 | Clean Architecture | Architecture |
| 25 | Onion Architecture | Architecture |
| 26 | Domain-Driven Design | Architecture |
| 27 | Bounded Context | Architecture |
| 28 | High Cohesion, Low Coupling | Architecture |
| 29 | Modularity | Architecture |
| 30 | Stable Dependencies | Architecture |
| 31 | Stable Abstractions | Architecture |
| 32 | Common Closure | Architecture |
| 33 | Common Reuse | Architecture |
| 34 | CAP Theorem | Distributed Systems |
| 35 | PACELC | Distributed Systems |
| 36 | Eventual Consistency | Distributed Systems |
| 37 | Strong Consistency | Distributed Systems |
| 38 | Idempotency | Distributed Systems |
| 39 | Bulkhead | Distributed Systems |
| 40 | Circuit Breaker | Distributed Systems |
| 41 | Timeout | Distributed Systems |
| 42 | Retry with Backoff | Distributed Systems |
| 43 | At-Least-Once Delivery | Distributed Systems |
| 44 | At-Most-Once Delivery | Distributed Systems |
| 45 | Exactly-Once Processing | Distributed Systems |
| 46 | Single Writer | Distributed Systems |
| 47 | Leader Election | Distributed Systems |
| 48 | Backpressure | Distributed Systems |
| 49 | Fault Isolation | Distributed Systems |
| 50 | Graceful Degradation | Distributed Systems |
| 51 | Event Sourcing | Distributed Systems |
| 52 | CQRS | Distributed Systems |
| 53 | Premature Optimization | Performance |
| 54 | Locality of Reference | Performance |
| 55 | Batch Processing | Performance |
| 56 | Lazy Evaluation | Performance |
| 57 | Resource Pooling | Performance |
| 58 | Bounded Resource | Performance |
| 59 | Zero-Copy | Performance |
| 60 | Data-Oriented Design | Performance |
| 61 | Concurrency over Parallelism | Performance |
| 62 | Zero Trust | Security |
| 63 | Defense in Depth | Security |
| 64 | Secure by Default | Security |
| 65 | Complete Mediation | Security |
| 66 | Fail Securely | Security |
| 67 | Economy of Mechanism | Security |
| 68 | Least Common Mechanism | Security |
| 69 | Separation of Privilege | Security |
| 70 | Test Pyramid | Testing |
| 71 | Arrange-Act-Assert | Testing |
| 72 | FIRST | Testing |
| 73 | Shift Left Testing | Testing |
| 74 | Test Isolation | Testing |
| 75 | Deterministic Testing | Testing |
| 76 | Continuous Integration | Testing |
| 77 | Regression Testing | Testing |
| 78 | Postel’s Law | API |
| 79 | Principle of Least Surprise | API |
| 80 | Backward Compatibility | API |
| 81 | Semantic Versioning | API |
| 82 | API Consistency | API |
| 83 | Statelessness | API |
| 84 | Self-Describing Messages | API |
| 85 | Boy Scout Rule | Development |
| 86 | Continuous Refactoring | Development |
| 87 | Small Batch | Development |
| 88 | Feedback Loop | Development |
| 89 | Automation First | Development |
| 90 | Single Source of Truth | Development |
| 91 | You Build It, You Run It | Development |
| 92 | Evolutionary Architecture | Development |
| 93 | Immutability | Functional |
| 94 | Pure Functions | Functional |
| 95 | Referential Transparency | Functional |
| 96 | Function Composition | Functional |
| 97 | Higher-Order Functions | Functional |
| 98 | Declarative Programming | Functional |
| 99 | Side Effect Isolation | Functional |
| 100 | Recursion over Mutable Iteration | Functional |
| 101 | Let It Crash | BEAM/OTP |
| 102 | Fault Isolation | BEAM/OTP |
| 103 | Share Nothing | BEAM/OTP |
| 104 | Supervision Tree | BEAM/OTP |
| 105 | Process-per-Responsibility | BEAM/OTP |
| 106 | Message Passing | BEAM/OTP |
| 107 | Location Transparency | BEAM/OTP |
| 108 | Preemptive Scheduling | BEAM/OTP |
| 109 | Behavior-Based Design | BEAM/OTP |
| 110 | Explicit State Ownership | BEAM/OTP |
Principles Entry Template (Shared Explanation Shape)
Every principle entry under principles/<category>.md MUST be a full section in
this order. Keep entries scannable; diagrams are optional and only where they
clarify. See content/MAPPING.md for single-source rules.
N. Name (example: ## 1. Single Responsibility Principle (SRP))
Scope note (one line, only when the name overlaps another entry or pillar): state the scope and link the counterpart — e.g. distributed-services vs BEAM supervision, or “canonical treatment: architecture page”.
Definition. One or two sentences: the rule in your own words.
Rationale. Why the rule exists; what trade-off it manages and what happens without it.
Example. One concrete, minimal scenario (code, config, or team practice).
Anti-pattern / failure mode. One misuse symptom plus one review signal.
Related. Links to neighboring principles plus at least one cross-pillar
link (pattern, architecture, or practice) where the principle is applied.
For topics taught canonically in architecture/ (Hexagonal, Clean, Onion,
CQRS, Event Sourcing), keep this entry a summary and link the canonical page
(e.g. Hexagonal architecture)
instead of re-teaching it.
SOLID Principles
1. Single Responsibility Principle (SRP)
Definition. A module should have one reason to change: it owns a single responsibility and the knowledge behind it.
Rationale. When a unit does several unrelated things, a change to one forces re-testing and re-deploying the others, and the unit accumulates unrelated dependencies. Splitting by responsibility keeps change impact small and makes the code easier to name, test, and replace.
Example. An Invoice class that both computes totals and renders PDFs has two reasons to change (tax rules vs. layout). Split it into Invoice (totals) and InvoicePrinter (rendering); the printer depends on the invoice, not vice versa.
Anti-pattern / failure mode. A “god object” or service class that grows a new method for every feature request, with unrelated fields and imports piling up. Review signal: a class with many unrelated public methods or frequent merge conflicts.
Related. Separation of Concerns (#9), High Cohesion, Low Coupling (#28), Modularity (#29).
2. Open/Closed Principle (OCP)
Definition. Software entities should be open for extension but closed for modification: new behavior is added by writing new code, not by editing stable, tested code.
Rationale. Editing working code risks regressions and forces re-testing everything that depends on it. Extension points (interfaces, hooks, strategies) let you add capabilities while leaving proven code untouched.
Example. Instead of adding if (type == "pdf") branches to a ReportExporter, define an Exporter interface and add PdfExporter as a new implementation. The exporter loop never changes.
Anti-pattern / failure mode. Repeated switch/if-else chains on a type tag that grow with every new variant; each new case edits a central function. Review signal: a function modified in every feature PR.
Related. Strategy pattern, Dependency Inversion (#5), Composition over Inheritance (#12).
3. Liskov Substitution Principle (LSP)
Definition. Subtypes must be substitutable for their base types without breaking correctness: a caller using the base type must not be able to tell which subtype it got.
Rationale. Inheritance is a behavioral contract, not just code reuse. If a subtype strengthens preconditions, weakens postconditions, or throws where the base did not, polymorphic code silently breaks. Honoring the contract keeps abstraction honest.
Example. A Square subclass of Rectangle that overrides setWidth/setHeight to keep sides equal violates callers that set width and height independently. Prefer a common Shape interface instead.
Anti-pattern / failure mode. Overriding methods to throw UnsupportedOperationException, or narrowing return types/accepting fewer inputs than the base. Review signal: instanceof checks scattered in client code.
Related. Program to an Interface (#15), Design by Contract, Interface Segregation (#4).
4. Interface Segregation Principle (ISP)
Definition. Clients should not be forced to depend on interfaces they do not use. Split wide interfaces into smaller, focused ones.
Rationale. A fat interface couples every client to methods it never calls, so a change to one method forces recompilation and re-testing of all clients. Narrow interfaces keep dependencies precise and evolution independent.
Example. Instead of one Worker interface with work() and eat(), split into Workable and Feedable. A robot implements only Workable.
Anti-pattern / failure mode. A single interface accumulating methods for every consumer (“kitchen sink” interface), where most implementers leave several methods as no-ops. Review signal: many UnsupportedOperationException stubs.
Related. Single Responsibility (#1), LSP (#3), High Cohesion, Low Coupling (#28).
5. Dependency Inversion Principle (DIP)
Definition. High-level and low-level modules should depend on abstractions, not on concrete implementations. Invert dependencies toward stable contracts.
Rationale. If high-level policy depends on low-level details, the policy changes whenever details change. Depending on abstractions keeps the core stable and lets details vary (databases, frameworks, devices) without touching business rules.
Example. An OrderService should depend on a PaymentGateway interface, not on StripeClient. Inject the concrete gateway at the composition root.
Anti-pattern / failure mode. new-ing concrete dependencies inside business logic, or importing database/HTTP clients directly into domain classes. Review signal: domain modules that cannot be unit-tested without real infrastructure.
Related. Hexagonal Architecture (#23), Clean Architecture (#24), Program to an Interface (#15).
General Software Design Principles
6. DRY (Don’t Repeat Yourself)
Definition. Avoid duplicating knowledge or logic; keep a single authoritative representation of each concept.
Rationale. Duplicated knowledge means a change must be made in many places, and they drift. One source of truth keeps behavior consistent and reduces the surface for bugs.
Example. Store a discount rule in one function rather than copying the formula into every checkout path. When the rule changes, one edit suffices.
Anti-pattern / failure mode. Copy-paste programming: the same calculation appears in controllers, services, and reports, each slightly different. Review signal: near-identical blocks with small variations.
Related. Single Source of Truth (#90), Common Closure (#32).
7. KISS (Keep It Simple, Stupid)
Definition. Prefer simple solutions over unnecessary complexity; choose the smallest design that solves the problem correctly.
Rationale. Complex designs are harder to understand, test, and change. Simplicity reduces defect rates and onboarding cost; complexity should be justified by a real need.
Example. Use a plain function instead of a configurable rule engine when only two cases exist today.
Anti-pattern / failure mode. Premature abstraction: frameworks, plugins, and indirection layers built for hypothetical future needs. Review signal: code that is harder to read than the problem it solves.
Related. YAGNI (#8), Economy of Mechanism (#67).
8. YAGNI (You Aren’t Gonna Need It)
Definition. Don’t implement functionality until it is actually needed; defer speculative features.
Rationale. Unused features still cost design, implementation, testing, and maintenance, and they constrain future change. Building for real requirements keeps the system lean and adaptable.
Example. Don’t add multi-currency support until a customer actually needs a second currency.
Anti-pattern / failure mode. “Just in case” features and hooks that are never exercised; dead code paths that rot. Review signal: configuration flags or extension points with no callers.
Related. KISS (#7), Small Batch (#87).
9. Separation of Concerns (SoC)
Definition. Separate systems into distinct areas of responsibility; keep unrelated concerns from mixing in the same module.
Rationale. Mixed concerns make changes risky because a fix in one area can break another. Clear boundaries let each part evolve and be tested independently.
Example. Keep HTTP parsing, business rules, and persistence in separate layers rather than one handler doing all three.
Anti-pattern / failure mode. A controller that validates input, computes pricing, writes to the database, and sends email. Review signal: a single function with multiple reasons to change.
Related. Single Responsibility (#1), High Cohesion, Low Coupling (#28).
10. Principle of Least Astonishment (POLA)
General-behavior scope — for API-surface predictability see Principle of Least Surprise (#79).
Definition. Software behavior should match user and developer expectations; avoid surprising side effects and inconsistent conventions.
Rationale. Surprises cause misuse and bugs. Predictable behavior reduces cognitive load and makes APIs and systems trustworthy.
Example. A save() method that also sends a notification astonishes callers; name it saveAndNotify() or split the actions.
Anti-pattern / failure mode. Hidden side effects in getters or query methods; inconsistent naming. Review signal: methods whose names do not describe their effects.
Related. Principle of Least Surprise (#79), API Consistency (#82).
11. Law of Demeter (LoD)
Definition. Objects should communicate primarily with their immediate collaborators; avoid reaching through chains of objects to distant parts of the system.
Rationale. Long chains couple callers to intermediate structures and break when those structures change. Talking to direct collaborators keeps coupling shallow and encapsulation intact.
Example. Instead of order.getCustomer().getAddress().getCity(), ask order.getShippingCity().
Anti-pattern / failure mode. “Train wreck” expressions chaining getters across multiple objects. Review signal: code that knows the shape of several objects at once.
Related. Encapsulation (#13), Information Hiding (#14).
12. Composition over Inheritance
Definition. Prefer assembling behavior through composition rather than deep inheritance hierarchies; compose small, focused objects instead of subclassing.
Rationale. Inheritance binds behavior at compile time and creates fragile base classes; composition lets you swap parts at runtime and keeps classes small. Deep hierarchies amplify change impact.
Example. Give a Character a Weapon object it can swap, rather than subclassing SwordCharacter, BowCharacter, and so on.
Anti-pattern / failure mode. Deep inheritance trees where a base-class change ripples through dozens of subclasses. Review signal: subclasses that override most inherited methods.
Related. Open/Closed (#2), Dependency Inversion (#5).
13. Encapsulation Principle
Definition. Hide internal implementation details and expose controlled interfaces; protect invariants by limiting direct access to state.
Rationale. Uncontrolled access lets callers put objects into invalid states and couples them to representation. Controlled interfaces preserve invariants and allow the implementation to change freely.
Example. Make fields private and expose deposit()/withdraw() that enforce a non-negative balance, instead of public mutable fields.
Anti-pattern / failure mode. Public mutable state with external code enforcing rules; “anemic” objects with no behavior. Review signal: setters that allow invalid states.
Related. Information Hiding (#14), Program to an Interface (#15).
14. Information Hiding Principle
Definition. Hide design decisions likely to change behind stable boundaries; keep volatile details out of public contracts.
Rationale. By hiding what changes, you limit the blast radius of a change to the module that owns it. Stable interfaces let the rest of the system depend on contracts, not details.
Example. Hide the storage engine behind a repository interface so swapping SQL for a document store touches one adapter.
Anti-pattern / failure mode. Leaking database schemas, file formats, or third-party types through public APIs. Review signal: changing a library version forces broad code changes.
Related. Encapsulation (#13), Dependency Rule (#22).
15. Program to an Interface, Not an Implementation
Definition. Depend on contracts rather than concrete implementations; code against abstractions so implementations can vary freely.
Rationale. Concrete dependencies lock you to one implementation and make substitution, testing, and evolution hard. Abstractions decouple consumers from producers.
Example. A Notifier interface with EmailNotifier and SmsNotifier implementations lets callers switch channels without code changes.
Anti-pattern / failure mode. Direct instantiation of concrete classes in business logic; static calls to specific implementations. Review signal: code that cannot be tested with a fake.
Related. Dependency Inversion (#5), Hexagonal Architecture (#23).
16. Fail Fast Principle
Definition. Detect and report errors as early as possible; surface problems at the boundary where they occur instead of letting them propagate.
Rationale. Late failures are harder to diagnose and may corrupt state downstream. Early detection keeps errors local, messages clear, and recovery simple.
Example. Validate required fields at the API boundary and return a 400 immediately, rather than failing deep in a batch job hours later.
Anti-pattern / failure mode. Swallowing errors, returning nulls, or deferring validation; “fail slow” systems that produce wrong results far from the cause. Review signal: errors surfaced in unrelated components.
Related. Defensive Programming (#17), Fail Securely (#66).
17. Defensive Programming
Definition. Anticipate invalid inputs and unexpected states; validate assumptions and handle edge cases deliberately.
Rationale. The outside world is unreliable: bad data, race conditions, and partial failures happen. Defensive code keeps the system robust instead of crashing on the first surprise.
Example. Check for null/empty inputs, clamp ranges, and use assertions for invariants that must hold.
Anti-pattern / failure mode. Assuming inputs are always valid; trusting internal callers blindly. Review signal: production crashes on malformed but plausible input.
Related. Fail Fast (#16), Complete Mediation (#65).
18. Principle of Least Privilege (PoLP)
Identity/access scope (who may do what) — for minimizing shared infrastructure see Least Common Mechanism (#68), and for splitting critical actions see Separation of Privilege (#69).
Definition. Grant only the permissions necessary to perform a task; limit access so a compromised component cannot do more than it needs.
Rationale. Excess permissions amplify the impact of a bug or breach. Minimal permissions contain damage and reduce the attack surface.
Example. A report generator gets read-only database access, not admin credentials.
Anti-pattern / failure mode. Shared admin accounts, wildcard permissions, services running as root. Review signal: a compromised low-risk component can alter critical data.
Related. Zero Trust (#62), Defense in Depth (#63), Separation of Privilege (#69).
19. Explicit over Implicit
Definition. Make important behavior and dependencies clear; favor visible wiring over hidden convention or magic.
Rationale. Implicit behavior is easy to miss and hard to debug. Explicit wiring makes dependencies and effects obvious, aiding review and maintenance.
Example. Inject dependencies through constructors instead of resolving them from a global registry.
Anti-pattern / failure mode. Magic strings, auto-wiring by naming convention, hidden global state. Review signal: “where does this come from?” during code review.
Related. Convention over Configuration (#20), Explicit State Ownership (#110).
20. Convention over Configuration
Definition. Use sensible defaults to reduce unnecessary configuration; let common cases work with little or no setup.
Rationale. Most projects follow the same patterns; forcing configuration for the common case wastes time and invites errors. Defaults capture the common case while still allowing overrides.
Example. A framework that finds controllers in a standard directory without explicit registration.
Anti-pattern / failure mode. Over-configured systems where every default must be specified; or magic defaults that are hard to discover. Review signal: long configuration files for standard setups.
Related. Explicit over Implicit (#19), API Consistency (#82).
Architecture Principles
21. Separation of Architecture and Implementation
Definition. Keep architectural decisions independent of implementation details; architecture should outlive any particular technology choice.
Rationale. Technologies change faster than business needs. If architecture is expressed in framework terms, every technology shift becomes an architecture rewrite. Separating them preserves intent across migrations.
Example. Express “orders are validated before persistence” as a rule, not as a Spring interceptor or Rails filter.
Anti-pattern / failure mode. Architecture diagrams that name specific frameworks; business rules embedded in framework callbacks. Review signal: cannot describe the system without naming a framework.
Related. Dependency Rule (#22), Clean Architecture (#24).
22. Dependency Rule
Definition. Source-code dependencies should point toward more stable, higher-level policies; inner layers must not know about outer layers.
Rationale. Stable core policy should not be broken by volatile details like UI or databases. Inward dependencies keep the core testable and reusable across delivery mechanisms.
Example. Domain entities have no imports from the web or persistence packages; adapters depend on domain interfaces.
Anti-pattern / failure mode. Domain code importing ORM entities or HTTP types. Review signal: changing a database forces domain edits.
Related. Clean Architecture (#24), Onion Architecture (#25), Hexagonal (#23).
23. Hexagonal Architecture (Ports and Adapters)
Canonical treatment: Hexagonal architecture. This entry is a summary — see the canonical page for structure, rules, and trade-offs.
Definition. Isolate business logic from external systems through ports and adapters; the domain depends on interfaces, not infrastructure.
Rationale. External systems (DB, messaging, HTTP) change and are hard to test. Ports define what the domain needs; adapters implement it, keeping the domain pure and testable with fakes.
Example. A PaymentPort interface with a StripeAdapter and a FakePaymentAdapter for tests.
Anti-pattern / failure mode. Domain code calling third-party SDKs directly. Review signal: tests that require real network or database.
Related. Dependency Inversion (#5), Clean Architecture (#24), Dependency Rule (#22), canonical Hexagonal.
24. Clean Architecture Principle
Canonical treatment: Clean architecture. This entry is a summary — see the canonical page for rings, dependency rule, and trade-offs.
Definition. Keep business rules independent of frameworks, databases, and delivery mechanisms; the core should be testable without its surroundings.
Rationale. Frameworks and databases are details; business rules are the value. Isolating them lets you test rules in milliseconds and swap details freely.
Example. Use cases and entities in a core package with no framework imports; frameworks live in outer adapter packages.
Anti-pattern / failure mode. Business logic scattered across controllers and ORM entities. Review signal: cannot run business tests without booting the framework.
Related. Hexagonal (#23), Onion (#25), Dependency Rule (#22), canonical Clean.
25. Onion Architecture
Canonical treatment: Onion architecture. This entry is a summary — see the canonical page for rings and dependency rules.
Definition. Organize dependencies toward the application core; each layer depends only on the layers inside it.
Rationale. Concentric layers make the direction of dependency explicit and prevent outer concerns from leaking inward. The core remains stable and framework-free.
Example. UI and infrastructure depend on application services, which depend on domain; domain depends on nothing.
Anti-pattern / failure mode. Inner layers referencing outer ones; circular dependencies between layers. Review signal: domain package importing application or infrastructure.
Related. Clean Architecture (#24), Dependency Rule (#22), canonical Onion.
26. Domain-Driven Design (DDD)
Definition. Model software around business domains and their language; align code structure with the problem domain.
Rationale. Software that mirrors the domain is easier for experts and developers to discuss and evolve. Ubiquitous language reduces translation errors between business and code.
Example. Name classes Order, Shipment, Invoice after domain concepts, with methods like ship() rather than updateStatus(3).
Anti-pattern / failure mode. Anemic domain models with logic in services; generic “Manager”/“Handler” classes disconnected from domain terms. Review signal: developers and domain experts use different vocabularies.
Related. Bounded Context (#27), High Cohesion, Low Coupling (#28).
27. Bounded Context Principle
Definition. Define explicit boundaries for domain models and their meanings; keep each model consistent within its own context.
Rationale. The same word means different things in different parts of a business (“Customer” in sales vs. billing). Explicit boundaries prevent one model from being stretched to mean everything.
Example. Separate Sales.Customer and Billing.Customer models, each with its own attributes, integrated via events or translation.
Anti-pattern / failure mode. A single shared Customer entity used by every module, growing fields for all of them. Review signal: a core entity with dozens of optional fields used by different teams.
Related. DDD (#26), Modularity (#29).
28. High Cohesion, Low Coupling
Definition. Keep related responsibilities together while minimizing dependencies between modules.
Rationale. Cohesive modules are easy to understand and change; low coupling means a change in one module rarely forces changes in others. Together they make systems maintainable.
Example. Group all order-pricing logic in one module instead of spreading it across checkout, invoice, and report modules.
Anti-pattern / failure mode. “Shotgun surgery”: one feature change touches many modules; or “feature envy” where a module constantly uses another’s data. Review signal: changes that ripple across the codebase.
Related. Single Responsibility (#1), Modularity (#29).
29. Modularity Principle
Definition. Divide systems into independently understandable and maintainable components with clear, narrow interfaces.
Rationale. Modules limit the scope of change and enable parallel work. Narrow interfaces reduce the chance that a change in one module breaks others.
Example. A payments module exposing only charge() and refund(), hiding its provider details.
Anti-pattern / failure mode. “Big ball of mud”: no clear module boundaries; everything depends on everything. Review signal: cannot build or test a component in isolation.
Related. High Cohesion, Low Coupling (#28), Bounded Context (#27).
30. Stable Dependencies Principle (SDP)
Definition. Depend in the direction of stability; unstable modules may depend on stable ones, not the reverse.
Rationale. If a stable module depends on an unstable one, the stable module becomes fragile. Directing dependencies toward stability keeps core code robust.
Example. A volatile UI module may depend on a stable domain module, but the domain must not depend on the UI.
Anti-pattern / failure mode. A core library depending on a rapidly changing plugin or experimental module. Review signal: stable components break when volatile ones change.
Related. Stable Abstractions (#31), Dependency Rule (#22).
31. Stable Abstractions Principle (SAP)
Definition. Stable components should be abstract; high stability pairs with high abstraction to allow safe reuse.
Rationale. A stable but concrete component cannot evolve without breaking dependents. Making stable components abstract lets them be extended without modification.
Example. A stable PaymentGateway interface with concrete adapters that can change freely.
Anti-pattern / failure mode. A stable, concrete utility class that everyone depends on and that cannot be changed safely. Review signal: “don’t touch that file” folklore.
Related. Stable Dependencies (#30), Open/Closed (#2).
32. Common Closure Principle (CCP)
Definition. Group components that change together; a change to one component should not force changes scattered across many modules.
Rationale. When related changes land in one place, releases are simpler and conflicts fewer. Scattered changes increase coordination cost and risk.
Example. Put all tax-calculation code in one module so a tax-rule change touches one place.
Anti-pattern / failure mode. A single feature change requiring edits across ten modules in different packages. Review signal: PRs that touch many unrelated files.
Related. Common Reuse (#33), Single Responsibility (#1).
33. Common Reuse Principle (CRP)
Definition. Group components that are reused together; avoid forcing consumers to depend on things they do not use.
Rationale. If components are always used together, package them together; if not, split them so consumers take only what they need. This reduces unnecessary dependencies.
Example. Don’t bundle a rarely used reporting helper into the core domain package that every service depends on.
Anti-pattern / failure mode. A “utils” package that every module imports but each uses only a fraction of. Review signal: transitive dependencies pulling in large unused code.
Related. Common Closure (#32), Interface Segregation (#4).
Distributed Systems Principles
34. CAP Theorem
Definition. Under network partition, a distributed system must trade off between consistency and availability; it cannot guarantee both.
Rationale. Partitions are inevitable, so the choice is which property to sacrifice. Understanding CAP prevents false expectations and guides deliberate design per use case.
Example. A shopping cart may favor availability (accept writes during partition) while inventory favors consistency (refuse conflicting updates).
Anti-pattern / failure mode. Assuming a distributed database gives strong consistency and high availability under partitions. Review signal: “we never lose data” claims without partition handling.
Related. PACELC (#35), Eventual Consistency (#36), Strong Consistency (#37).
35. PACELC Principle
Definition. Consider latency versus consistency during normal operation, alongside the partition trade-offs of CAP.
Rationale. Even without partitions, strong consistency costs latency. PACELC reminds designers to optimize the common case, not only failure modes.
Example. A read replica may serve slightly stale data to keep latency low, accepting occasional staleness.
Anti-pattern / failure mode. Tuning only for partition scenarios while ignoring everyday latency. Review signal: high p99 latency from synchronous consensus on every read.
Related. CAP (#34), Eventual Consistency (#36).
36. Eventual Consistency
Definition. Replicas converge when updates stop and communication resumes; temporary divergence is accepted.
Rationale. Strong consistency across partitions is expensive or impossible. Eventual consistency trades immediate correctness for availability and performance, suitable for many workloads.
Example. A user’s profile update appears on one server now and on others within seconds.
Anti-pattern / failure mode. Assuming “eventual” means “instant”; building features that require immediate global visibility on eventually consistent data. Review signal: race conditions and stale reads in critical paths.
Related. Strong Consistency (#37), Idempotency (#38).
37. Strong Consistency
Definition. Operations behave as if executed atomically in a globally consistent order; all observers see the same state.
Rationale. Some domains (money, inventory, rights) cannot tolerate divergence. Strong consistency provides a single source of truth at the cost of latency and availability under partitions.
Example. A bank transfer must reflect immediately across all accounts; stale reads are unacceptable.
Anti-pattern / failure mode. Using strong consistency everywhere, hurting performance and availability for data that doesn’t need it. Review signal: synchronous cross-region calls on every request.
Related. CAP (#34), Eventual Consistency (#36), Single Writer (#46).
38. Idempotency Principle
Definition. Repeating an operation produces the same effect as performing it once; design operations so retries are safe.
Rationale. Networks fail and clients retry; non-idempotent operations cause duplicates (double charges, duplicate messages). Idempotency makes retries safe and systems resilient.
Example. A payment API accepts an idempotency key; repeating the same request returns the original result instead of charging again.
Anti-pattern / failure mode. POST endpoints that create a new record on every call, including retries. Review signal: duplicate rows after network hiccups.
Related. At-Least-Once Delivery (#43), Exactly-Once Processing (#45).
39. Bulkhead Principle
Definition. Isolate failures to prevent cascading failures; partition resources so one failing part cannot exhaust the whole.
Rationale. Shared resource pools let one slow dependency starve others. Bulkheads contain the blast radius by giving each component its own limits.
Example. Separate thread pools per downstream service so a slow service doesn’t exhaust the pool used by others.
Anti-pattern / failure mode. A single shared thread/connection pool for all downstream calls. Review signal: one slow dependency takes down the whole service.
Related. Fault Isolation (#49), Circuit Breaker (#40).
40. Circuit Breaker Pattern
Definition. Stop repeatedly calling failing services; open the circuit after repeated failures and retry only after a cooldown.
Rationale. Hammering a failing dependency wastes resources and slows recovery. A circuit breaker fails fast, giving the dependency time to recover.
Example. After 5 consecutive failures, return a cached/fallback response for 30 seconds before probing again.
Anti-pattern / failure mode. Infinite retries with no backoff; or breakers that never reset. Review signal: retry storms during outages.
Related. Timeout (#41), Retry with Backoff (#42), Bulkhead (#39).
41. Timeout Principle
Definition. Every remote operation should have an appropriate timeout; bound waiting so a slow dependency cannot stall callers indefinitely.
Rationale. Unbounded waits tie up resources and cascade delays. Timeouts convert indefinite stalls into handled failures.
Example. Set a 2-second timeout on an HTTP call; on timeout, return a fallback or error.
Anti-pattern / failure mode. Default or no timeouts on HTTP/DB calls; timeouts longer than the user’s patience. Review signal: threads stuck in “waiting” state.
Related. Circuit Breaker (#40), Retry with Backoff (#42).
42. Retry with Backoff
Definition. Retry transient failures with increasing delays; add jitter to avoid thundering herds.
Rationale. Transient failures often resolve quickly; immediate retries can overwhelm a recovering service. Backoff gives time; jitter spreads load.
Example. Retry up to 3 times with exponential backoff (100ms, 400ms, 1600ms) plus random jitter.
Anti-pattern / failure mode. Tight retry loops with no delay; retrying non-transient errors. Review signal: load spikes after a brief outage.
Related. Timeout (#41), Idempotency (#38).
43. At-Least-Once Delivery
Definition. Messages are delivered one or more times; pair with idempotent consumers to handle duplicates safely.
Rationale. Guaranteeing exactly once is costly; at-least-once is achievable and sufficient if consumers are idempotent. It favors liveness over strict deduplication.
Example. A message queue redelivers unacked messages; the consumer dedupes by message id.
Anti-pattern / failure mode. Assuming at-least-once means exactly once, leading to duplicate processing. Review signal: side effects applied multiple times.
Related. Idempotency (#38), At-Most-Once (#44), Exactly-Once (#45).
44. At-Most-Once Delivery
Definition. Messages are delivered zero or one time; accept possible loss in exchange for no duplicates.
Rationale. Some workloads (metrics, best-effort notifications) prefer no duplicates over guaranteed delivery. At-most-once is simpler and cheaper.
Example. Fire-and-forget analytics events that may be dropped but never duplicated.
Anti-pattern / failure mode. Using at-most-once for critical data (orders, payments). Review signal: silent data loss in important flows.
Related. At-Least-Once (#43), Exactly-Once (#45).
45. Exactly-Once Processing Semantics
Definition. Ensure effects are applied once within a defined system boundary, usually via idempotency plus deduplication rather than true once-only delivery.
Rationale. True exactly-once delivery is generally impossible; exactly-once processing is achievable within a boundary using idempotent operations and transactional state. It matters for financial and inventory correctness.
Example. Process a payment within a transaction that records the processed message id; replaying the message is a no-op.
Anti-pattern / failure mode. Claiming “exactly once” from a broker alone without idempotent consumers. Review signal: duplicates after consumer restarts.
Related. Idempotency (#38), At-Least-Once (#43).
46. Single Writer Principle
Definition. Assign one authoritative writer for a given piece of state; avoid concurrent writes to the same data.
Rationale. Concurrent writers cause conflicts and require locking or merge logic. A single writer simplifies consistency and reasoning.
Example. Only the order service writes to the orders table; other services read replicas or events.
Anti-pattern / failure mode. Multiple services writing to the same table directly. Review signal: lock contention and lost updates.
Related. Strong Consistency (#37), Leader Election (#47).
47. Leader Election Principle
Definition. Select a coordinator to manage distributed operations; use consensus or a lock service to agree on the leader.
Rationale. Some tasks (scheduled jobs, partition assignment) need a single coordinator. Leader election provides that without manual assignment, with automatic failover.
Example. A cluster elects a leader to run a nightly reconciliation job; on failure, a new leader is elected.
Anti-pattern / failure mode. Hardcoding a primary node with no failover; split-brain leaders. Review signal: manual failover procedures or duplicate job runs.
Related. Single Writer (#46), Fault Isolation (#49).
48. Backpressure Principle
Definition. Control incoming workloads according to processing capacity; push back on producers instead of unbounded buffering.
Rationale. Unbounded queues grow until memory exhausts. Backpressure propagates capacity limits upstream, keeping the system stable under load.
Example. A stream consumer signals the producer to slow down when its buffer is full.
Anti-pattern / failure mode. Unbounded in-memory queues that grow until OOM. Review signal: memory growth under load, long queue latency.
Related. Bounded Resource (#58), Graceful Degradation (#50).
49. Fault Isolation Principle (Distributed Services)
Distributed-services scope — for process supervision see Fault Isolation (BEAM supervision).
Definition. Prevent failures in one component from propagating to others; contain errors within well-defined boundaries.
Rationale. A single failing component should not take down the system. Isolation limits impact and preserves partial functionality.
Example. A failing recommendation service returns defaults instead of failing the whole page.
Anti-pattern / failure mode. Shared process/crash domains where one bug kills everything. Review signal: full outages from minor component failures.
Related. Bulkhead (#39), Graceful Degradation (#50), Fault Isolation (BEAM) (#102).
50. Graceful Degradation
Definition. Maintain partial functionality when some components fail; serve what you can instead of failing entirely.
Rationale. Users prefer degraded service over total failure. Designing fallbacks keeps the system useful during incidents.
Example. When the search service is down, show cached results or a simplified list instead of an error page.
Anti-pattern / failure mode. All-or-nothing endpoints that fail the whole request if any dependency fails. Review signal: minor dependency outages cause full outages.
Related. Fault Isolation (#49), Circuit Breaker (#40).
51. Event Sourcing Principle
Canonical treatment: CQRS & Event Sourcing. This entry is a summary — see the canonical page for log design, projections, and trade-offs.
Definition. Store state changes as an append-only sequence of events; derive current state by replaying events.
Rationale. An event log provides a complete audit trail and lets you rebuild state, replay history, or create new projections. It shifts storage from “current state” to “what happened.”
Example. An account balance is computed by replaying deposit/withdrawal events.
Anti-pattern / failure mode. Mutating state in place with no history; or storing events without a clear schema/evolution plan. Review signal: inability to answer “how did we get here?”
Related. CQRS (#52), Single Source of Truth (#90), canonical CQRS & Event Sourcing.
52. CQRS (Command Query Responsibility Segregation)
Canonical treatment: CQRS & Event Sourcing. This entry is a summary — see the canonical page for read/write separation and when to combine with Event Sourcing.
Definition. Separate write and read models; optimize each side independently for its workload.
Rationale. Read and write workloads differ; a single model compromises both. Separation lets reads be fast/denormalized and writes be normalized/validated.
Example. Commands update a normalized write store; queries read from a denormalized read model updated via events.
Anti-pattern / failure mode. Applying CQRS to simple CRUD where one model suffices, adding complexity without benefit. Review signal: duplicated models with no performance or scaling need.
Related. Event Sourcing (#51), Separation of Concerns (#9), canonical CQRS & Event Sourcing.
Performance and Resource Management Principles
53. Premature Optimization Principle
Definition. Avoid optimizing before identifying actual bottlenecks; measure first, then optimize the hot paths.
Rationale. Guessing at bottlenecks wastes effort and often complicates code for no gain. Measurement reveals where time is actually spent; optimize there.
Example. Profile before rewriting a loop; the bottleneck may be I/O, not CPU.
Anti-pattern / failure mode. Micro-optimizing cold code while ignoring measured hot paths; “optimization” that harms readability. Review signal: complexity added without profiling evidence.
Related. Locality of Reference (#54), Data-Oriented Design (#60).
54. Locality of Reference
Definition. Favor access patterns that improve cache efficiency; keep related data close in memory.
Rationale. Modern CPUs are fast but memory is slow; cache misses dominate. Layouts that access contiguous, related data exploit caches and drastically improve throughput.
Example. Store fields of a struct together and iterate arrays of structs rather than chasing pointers.
Anti-pattern / failure mode. Pointer-heavy structures with scattered allocations; random access over large datasets. Review signal: high cache-miss rates in profiling.
Related. Data-Oriented Design (#60), Zero-Copy (#59).
55. Batch Processing Principle
Definition. Group operations to reduce overhead; amortize fixed costs across many items.
Rationale. Per-operation overhead (syscalls, network round trips, transactions) dominates small operations. Batching amortizes these costs and increases throughput.
Example. Insert 1000 rows in one transaction instead of 1000 individual commits.
Anti-pattern / failure mode. Per-item network/DB calls in a loop; “chatty” APIs. Review signal: high request counts for bulk work.
Related. Resource Pooling (#57), Concurrency over Parallelism (#61).
56. Lazy Evaluation
Definition. Delay computation until its result is needed; avoid work that may never be used.
Rationale. Eager computation wastes resources on results that may be discarded. Laziness defers cost and can avoid it entirely.
Example. Generate a report only when a user opens it; compute derived fields on demand.
Anti-pattern / failure mode. Eagerly loading large datasets or computing expensive values “just in case.” Review signal: memory/CPU spent on unused results.
Related. Premature Optimization (#53), Resource Pooling (#57).
57. Resource Pooling
Definition. Reuse expensive resources instead of repeatedly creating them; pool connections, threads, or buffers.
Rationale. Creating resources (connections, processes, large buffers) is costly. Pooling amortizes creation and bounds resource usage.
Example. A database connection pool reused across requests.
Anti-pattern / failure mode. Opening a new connection per request; unbounded allocation of expensive objects. Review signal: high allocation/GC or connection churn.
Related. Bounded Resource (#58), Batch Processing (#55).
58. Bounded Resource Principle
Definition. Put explicit limits on memory, connections, queues, and workloads; prevent unbounded growth from exhausting resources.
Rationale. Unbounded structures grow until the process crashes. Explicit bounds provide backpressure and predictable behavior under load.
Example. Cap a request queue at 1000 items and reject or block beyond that.
Anti-pattern / failure mode. Unbounded in-memory queues, caches, or buffers. Review signal: OOM under load; latency spikes from GC.
Related. Backpressure (#48), Resource Pooling (#57).
59. Zero-Copy Principle
Definition. Minimize unnecessary data copying; pass references or use buffers that can be shared.
Rationale. Copying data wastes CPU and memory bandwidth and increases latency. Avoiding copies, especially in hot paths, improves throughput and reduces GC pressure.
Example. Send a file from disk to a socket using sendfile instead of reading into user space.
Anti-pattern / failure mode. Repeatedly copying large payloads between layers. Review signal: high CPU in serialization/copy code.
Related. Locality of Reference (#54), Data-Oriented Design (#60).
60. Data-Oriented Design
Definition. Organize data to optimize access patterns and processing efficiency; design for how data is read and transformed.
Rationale. Object-oriented layouts often scatter related data, hurting cache and throughput. Designing around data access patterns yields simpler, faster processing.
Example. Store positions as arrays of x/y/z rather than an array of Point objects for tight loops.
Anti-pattern / failure mode. Deep object graphs traversed in hot loops. Review signal: profiling shows time in field access/chasing.
Related. Locality of Reference (#54), Zero-Copy (#59).
61. Concurrency over Parallelism
Definition. Structure independent activities to make progress without necessarily executing simultaneously; concurrency is about structure, parallelism about execution.
Rationale. Concurrency decomposes a program into independent tasks that can interleave; parallelism runs them at once. Designing for concurrency (clear ownership, message passing) yields correct, scalable systems even on one core.
Example. An event loop handling many connections concurrently on a single thread.
Anti-pattern / failure mode. Confusing the two and bolting threads onto tightly coupled code. Review signal: data races and lock contention from “just add threads.”
Related. Share Nothing (#103), Message Passing (#106).
Security Principles
62. Zero Trust Principle
Definition. Never automatically trust a user, device, or network; verify every request regardless of origin.
Rationale. Perimeter-based trust fails once an attacker is inside. Verifying every request limits lateral movement and reduces reliance on network boundaries.
Example. Require authentication and authorization for internal service calls, not just external ones.
Anti-pattern / failure mode. “Trusted internal network” assumptions; skipping auth for service-to-service calls. Review signal: a compromised internal host can reach everything.
Related. Defense in Depth (#63), Complete Mediation (#65), guarded access (Proxy).
63. Defense in Depth
Definition. Apply multiple independent security layers; no single control should be the only barrier.
Rationale. Any single control can fail or be bypassed. Layered controls ensure that a failure in one does not compromise the whole system.
Example. Combine input validation, parameterized queries, and least-privilege DB accounts to prevent SQL injection.
Anti-pattern / failure mode. Relying on one control (e.g., a WAF) as the only protection. Review signal: a single bypass grants full access.
Related. Zero Trust (#62), Fail Securely (#66), bulkhead isolation (Bulkhead).
64. Secure by Default
Definition. Default configurations should favor security; require explicit opt-in to weaken protections.
Rationale. Defaults are what most deployments use. Secure defaults protect the majority and reduce accidental exposure.
Example. Disable debug endpoints and require TLS by default; allow disabling only with explicit flags.
Anti-pattern / failure mode. Insecure defaults (open ports, default passwords) that users must remember to fix. Review signal: production systems running with default credentials.
Related. Economy of Mechanism (#67), Least Privilege (#18), minimal attack surface (Facade).
65. Complete Mediation
Definition. Check authorization on every access to protected resources; do not cache authorization decisions unsafely.
Rationale. Authorization must be evaluated at the point of access, not assumed from an earlier check. Caching or skipping checks creates bypass opportunities.
Example. Verify permissions on each API request rather than trusting a session flag set at login.
Anti-pattern / failure mode. Checking auth once and trusting subsequent calls; “admin mode” flags. Review signal: privilege escalation via stale sessions.
Related. Fail Securely (#66), Zero Trust (#62), request interception (Chain of Responsibility).
66. Fail Securely
Definition. Failure should not expose protected information or privileges; default to denial on error.
Rationale. Error paths are often less tested and can leak data or grant access. Failing closed keeps security posture intact under faults.
Example. If an authorization check throws, deny access rather than allow it.
Anti-pattern / failure mode. Fail-open logic that grants access on exceptions or missing config. Review signal: “allow by default” error handlers.
Related. Fail Fast (#16), Complete Mediation (#65), safe defaults (Secure by Default).
67. Economy of Mechanism
Definition. Keep security mechanisms as simple as possible; complexity breeds vulnerabilities.
Rationale. Complex security code is hard to audit and more likely to contain flaws. Simple, well-understood mechanisms are easier to verify and maintain.
Example. Use a standard, vetted auth library instead of a custom token scheme.
Anti-pattern / failure mode. Custom cryptography or bespoke auth protocols. Review signal: security code that only one person understands.
Related. KISS (#7), Defense in Depth (#63), vetted building blocks (Flyweight).
68. Least Common Mechanism
Shared-infrastructure scope (minimize shared paths) — for per-identity permissions see Least Privilege (#18).
Definition. Minimize shared mechanisms and resources between users; shared paths can leak information or amplify impact.
Rationale. Shared components create covert channels and single points of compromise. Isolating mechanisms per user or tenant limits cross-user impact.
Example. Separate caches or queues per tenant rather than one shared pool.
Anti-pattern / failure mode. Global caches keyed only by resource id, leaking data across users. Review signal: cross-tenant data exposure.
Related. Least Privilege (#18), Separation of Privilege (#69), per-tenant isolation (Multi-Tenant SaaS).
69. Separation of Privilege
Definition. Require multiple independent conditions for sensitive operations; avoid single points of control for critical actions.
Rationale. A single compromised credential or person should not be able to perform a high-impact action. Multiple independent conditions raise the bar for abuse.
Example. Require two-person approval for production deployments or large refunds.
Anti-pattern / failure mode. One admin account able to do everything; single-approval for destructive operations. Review signal: a single account compromise is catastrophic.
Related. Least Privilege (#18), Defense in Depth (#63).
Testing and Quality Principles
70. Test Pyramid
Definition. Maintain a healthy balance of unit, integration, and end-to-end tests; favor many fast unit tests over a few slow end-to-end ones.
Rationale. A broad base of fast unit tests gives rapid feedback; a small top of E2E tests covers integration. Inverting the pyramid makes suites slow and brittle.
Example. Hundreds of unit tests for logic, dozens of integration tests for adapters, a handful of E2E tests for critical flows.
Anti-pattern / failure mode. An “ice-cream cone”: many slow E2E tests and few unit tests. Review signal: long CI times and flaky suites.
Related. FIRST (#72), Continuous Integration (#76), capstone review rubrics (practice).
71. Arrange-Act-Assert (AAA)
Definition. Structure tests into setup, execution, and verification; keep each test focused on one behavior.
Rationale. A clear structure makes tests readable and failures easy to diagnose. One behavior per test keeps the cause of failure unambiguous.
Example. Arrange fixtures, act by calling the method, assert the outcome; nothing else in between.
Anti-pattern / failure mode. Tests that mix setup, multiple actions, and assertions; tests asserting several unrelated things. Review signal: a failing test doesn’t say what broke.
Related. Test Isolation (#74), FIRST (#72), testable requests (Command).
72. FIRST Principles
Definition. Tests should be Fast, Independent, Repeatable, Self-validating, and Timely.
Rationale. Fast tests run often; independent tests don’t order-depend; repeatable tests are deterministic; self-validating tests need no manual inspection; timely tests are written close to the code. Together they make tests trustworthy.
Example. A unit test that runs in milliseconds, uses in-memory fakes, and asserts via code.
Anti-pattern / failure mode. Slow, order-dependent, flaky tests that require manual checking. Review signal: developers stop running the suite locally.
Related. Deterministic Testing (#75), Test Isolation (#74), swappable test doubles (Strategy).
73. Shift Left Testing
Definition. Detect defects earlier in the development lifecycle; test during development, not only before release.
Rationale. Bugs are cheaper to fix when found early. Integrating testing into development catches issues before they compound.
Example. Run unit tests on every save and in pre-commit hooks, not just in CI.
Anti-pattern / failure mode. Testing only in a late QA phase; discovering integration issues at release. Review signal: defects found late with large fix cost.
Related. Continuous Integration (#76), Regression Testing (#77), small testable slices (Vertical Slice).
74. Test Isolation Principle
Definition. Tests should not depend on uncontrolled external state; isolate tests so they can run in any order.
Rationale. Shared state causes order-dependent and flaky tests. Isolation makes failures reproducible and parallelization safe.
Example. Use in-memory databases or fakes per test instead of a shared test database.
Anti-pattern / failure mode. Tests that mutate shared global state or depend on execution order. Review signal: tests pass alone but fail in suite.
Related. Deterministic Testing (#75), FIRST (#72), snapshot/restore for tests (Memento).
75. Deterministic Testing
Definition. The same conditions should produce predictable test results; eliminate flakiness.
Rationale. Flaky tests erode trust and waste time. Determinism makes failures meaningful and CI reliable.
Example. Avoid time-based assertions and network calls; use fixed clocks and fakes.
Anti-pattern / failure mode. Tests depending on real time, randomness, or network. Review signal: tests that fail intermittently without code changes.
Related. Test Isolation (#74), FIRST (#72), in-memory fakes (Hexagonal).
76. Continuous Integration Principle
Definition. Integrate and validate changes frequently; small, frequent integrations surface conflicts early.
Rationale. Long-lived branches diverge and merge painfully. Frequent integration with automated validation keeps the mainline healthy.
Example. Merge small PRs daily with CI running tests on each push.
Anti-pattern / failure mode. Long-lived feature branches merged rarely; “integration hell.” Review signal: large, risky merges.
Related. Small Batch (#87), Feedback Loop (#88), enforced module boundaries (Modular Monolith).
77. Regression Testing
Definition. Ensure new changes do not break existing functionality; protect prior behavior with automated tests.
Rationale. Without regression tests, fixes and features reintroduce old bugs. Automated coverage preserves behavior across changes.
Example. Add a test reproducing a bug before fixing it, so it stays fixed.
Anti-pattern / failure mode. Manual regression checks; fixing bugs without tests. Review signal: the same bug recurring.
Related. Continuous Integration (#76), Test Pyramid (#70).
API and Protocol Design Principles
78. Postel’s Law (Robustness Principle)
Definition. Be conservative in what you send and liberal in what you accept; use cautiously, as excessive permissiveness can create security and interoperability issues.
Rationale. Tolerant readers and strict writers maximize interoperability across implementations. But over-tolerance can mask errors and open security holes, so apply with care.
Example. Accept extra unknown fields in requests (ignore them) but never emit malformed or ambiguous output.
Anti-pattern / failure mode. Accepting anything and producing inconsistent output; “liberal acceptance” leading to injection or parsing bugs. Review signal: security issues from over-permissive parsing.
Related. Principle of Least Surprise (#79), API Consistency (#82), tolerant readers (Adapter).
79. Principle of Least Surprise
API-surface scope — the API counterpart of Least Astonishment (#10).
Definition. API behavior should be predictable; design interfaces that match caller expectations.
Rationale. Surprising behavior causes misuse and bugs. Predictable APIs reduce cognitive load and make integration reliable.
Example. A delete() method should remove the resource, not archive it silently.
Anti-pattern / failure mode. Methods whose names imply one thing but do another; inconsistent return types. Review signal: callers wrap calls in defensive checks.
Related. Postel’s Law (#78), API Consistency (#82), predictable contracts (Facade).
80. Backward Compatibility
Definition. New versions should preserve existing client behavior where required; avoid breaking callers unnecessarily.
Rationale. Clients depend on current behavior; breaking changes force costly upgrades and erode trust. Preserving compatibility keeps the ecosystem stable.
Example. Add new optional fields rather than renaming or removing existing ones.
Anti-pattern / failure mode. Removing or renaming fields in a minor release; changing semantics without version bump. Review signal: client breakage on upgrade.
Related. Semantic Versioning (#81), API Consistency (#82), matching families (Abstract Factory).
81. Semantic Versioning (SemVer)
Definition. Communicate compatibility through version numbers: major for breaking, minor for additive, patch for fixes.
Rationale. Version numbers convey change impact, letting consumers decide when to upgrade. Consistent SemVer builds trust and automates dependency management.
Example. Bump major for a removed endpoint, minor for a new optional field, patch for a bug fix.
Anti-pattern / failure mode. Breaking changes in patch releases; version numbers that don’t reflect impact. Review signal: consumers cannot predict upgrade risk.
Related. Backward Compatibility (#80), API Consistency (#82), stable contracts (Stable Abstractions).
82. API Consistency Principle
Definition. Use consistent naming, semantics, and error handling; a uniform API is easier to learn and use.
Rationale. Inconsistency forces users to memorize special cases and increases errors. Uniformity reduces cognitive load and support burden.
Example. Use the same error format and status codes across all endpoints.
Anti-pattern / failure mode. Mixed naming conventions, inconsistent pagination, varied error shapes. Review signal: separate documentation per endpoint for basics.
Related. Principle of Least Surprise (#79), Convention over Configuration (#20), uniform entry points (Facade).
83. Statelessness Principle
Definition. Keep request processing independent of hidden session state where appropriate; stateless services scale and fail over more easily.
Rationale. Hidden state ties requests to specific instances, complicating scaling and failover. Stateless processing lets any instance handle any request.
Example. Pass auth tokens per request rather than relying on server-side sessions.
Anti-pattern / failure mode. Server-side session state that must be replicated or sticky-routed. Review signal: scaling requires session affinity.
Related. Self-Describing Messages (#84), Location Transparency (#107), decoupled events (Event-Driven).
84. Self-Describing Messages
Definition. Messages should carry enough information to be interpreted correctly; include metadata needed for parsing and routing.
Rationale. Without metadata, receivers must guess format or meaning. Self-describing messages enable independent evolution and routing.
Example. Include content-type, version, and correlation id in message headers.
Anti-pattern / failure mode. Opaque payloads with no version or type info. Review signal: consumers break when producers change format.
Related. Statelessness (#83), API Consistency (#82).
Development and Project Management Principles
85. Boy Scout Rule
Definition. Leave the codebase cleaner than you found it; make small improvements whenever you touch code.
Rationale. Small, continuous improvements prevent decay without dedicated refactoring projects. Over time the codebase gets healthier.
Example. Rename a confusing variable or extract a method while fixing a bug in the same file.
Anti-pattern / failure mode. “Not my code” attitude; leaving messes for later. Review signal: code quality only degrades over time.
Related. Continuous Refactoring (#86), Small Batch (#87), small slices (Vertical Slice).
86. Continuous Refactoring
Definition. Improve internal code structure without changing external behavior; refactor steadily rather than in big batches.
Rationale. Big-bang refactors are risky and hard to review. Small, frequent refactors keep code healthy and changes reviewable.
Example. Extract a helper and add tests in the same PR as a feature, not a separate “refactor sprint.”
Anti-pattern / failure mode. Deferring all cleanup to a “refactor phase” that never happens. Review signal: large, scary refactoring PRs.
Related. Boy Scout Rule (#85), Small Batch (#87), template stability (Template Method).
87. Small Batch Principle
Definition. Deliver changes in small, manageable increments; small batches reduce risk and speed feedback.
Rationale. Large changes are hard to review and risky to deploy. Small batches are easier to test, review, and roll back.
Example. Ship a feature behind a flag in several small PRs instead of one huge one.
Anti-pattern / failure mode. Long-lived branches with massive PRs. Review signal: reviews that take days and deployments that fail.
Related. Feedback Loop (#88), Continuous Integration (#76), one-deployable flow (Modular Monolith).
88. Feedback Loop Principle
Definition. Shorten the time between implementation and feedback; faster feedback enables faster correction.
Rationale. Long feedback loops delay learning and let defects compound. Short loops catch issues while context is fresh.
Example. Fast local tests, preview deployments, and quick code review.
Anti-pattern / failure mode. Waiting days for CI or review. Review signal: developers context-switch away before feedback arrives.
Related. Small Batch (#87), Automation First (#89), observable broadcasts (Observer).
89. Automation First
Definition. Automate repeatable and error-prone processes; prefer scripts and pipelines over manual steps.
Rationale. Manual steps are slow and inconsistent. Automation makes processes reliable, fast, and auditable.
Example. Automate builds, tests, and deployments via CI/CD instead of manual runbooks.
Anti-pattern / failure mode. Manual deployment checklists and hand-run migrations. Review signal: “it works on my machine” deployments.
Related. Feedback Loop (#88), Continuous Integration (#76), repeatable pipelines (Builder).
90. Single Source of Truth (SSOT)
Definition. Maintain one authoritative source for each piece of information; avoid conflicting copies.
Rationale. Multiple copies drift and cause confusion about which is correct. A single source keeps data consistent and trusted.
Example. Store a user’s email in one place; other systems reference it, not copy it.
Anti-pattern / failure mode. Duplicated configuration or data across services that drift. Review signal: “which value is correct?” debates.
Related. DRY (#6), Event Sourcing (#51), canonical store (CQRS & Event Sourcing).
91. You Build It, You Run It
Definition. Development teams take responsibility for operating their software; ownership includes production health.
Rationale. When builders also operate, they feel the pain of poor operability and improve it. It aligns incentives and shortens feedback.
Example. The team that ships a service also owns its on-call and dashboards.
Anti-pattern / failure mode. Handing off to a separate ops team with no shared ownership. Review signal: production issues bounce between teams.
Related. Feedback Loop (#88), Evolutionary Architecture (#92), owned single writer (Single Writer).
92. Evolutionary Architecture
Definition. Design architecture to support continuous change; favor reversible decisions and fitness functions.
Rationale. Requirements change; architecture must adapt. Reversible decisions and automated fitness functions let the architecture evolve safely.
Example. Use fitness functions in CI to enforce architecture rules (e.g., no domain-to-infra imports).
Anti-pattern / failure mode. Big up-front design that cannot change; architecture decisions that are costly to reverse. Review signal: architecture that fights every new requirement.
Related. Separation of Architecture and Implementation (#21), Small Batch (#87).
Functional Programming Principles
93. Immutability
Definition. Avoid modifying existing data; create new values instead. Immutable data simplifies reasoning and sharing.
Rationale. Mutation makes state changes hard to track and leads to bugs, especially with concurrency. Immutable values are safe to share and easy to reason about.
Example. Update a list by returning a new list with the appended item rather than pushing in place.
Anti-pattern / failure mode. In-place mutation of shared state; “spooky action at a distance.” Review signal: bugs that depend on call order.
Related. Pure Functions (#94), Side Effect Isolation (#99).
94. Pure Functions
Definition. The same input produces the same output without side effects; pure functions are easy to test and compose.
Rationale. Purity makes functions predictable and testable in isolation. It also enables memoization, parallelization, and refactoring.
Example. A function that computes a total from inputs, with no I/O or mutation.
Anti-pattern / failure mode. Functions that read global state, mutate inputs, or perform I/O while claiming to compute. Review signal: tests that need elaborate setup or mocking.
Related. Referential Transparency (#95), Function Composition (#96).
95. Referential Transparency
Definition. An expression can be replaced by its value without changing program behavior, enabling safe refactoring and optimization.
Rationale. When expressions are referentially transparent, you can substitute, reorder, or cache them freely. This unlocks equational reasoning and optimization.
Example. Replacing f(x) with its result anywhere without changing meaning.
Anti-pattern / failure mode. Functions whose result depends on hidden state or time. Review signal: cannot simplify or inline an expression safely.
Related. Pure Functions (#94), Immutability (#93).
96. Function Composition
Definition. Build complex behavior by combining smaller functions; compose simple pieces into larger pipelines.
Rationale. Small functions are easy to test and reuse; composition assembles them into complex behavior without new code. It keeps logic declarative.
Example. process = validate |> transform |> store, each step a small function.
Anti-pattern / failure mode. Large monolithic functions that do many things; copy-pasted pipelines. Review signal: hard-to-test, hard-to-reuse blocks.
Related. Higher-Order Functions (#97), Declarative Programming (#98).
97. Higher-Order Functions
Definition. Functions can accept or return other functions; pass behavior as data to generalize operations.
Rationale. Treating functions as values lets you abstract control flow and customize behavior without subclassing or conditionals.
Example. map, filter, and reduce accept a function and apply it uniformly.
Anti-pattern / failure mode. Duplicating loop logic with slight variations instead of parameterizing the action. Review signal: many near-identical loops.
Related. Function Composition (#96), Declarative Programming (#98).
98. Declarative Programming
Definition. Describe what should happen rather than how to execute every step; let the runtime handle execution details.
Rationale. Declarative code states intent and lets the system choose an efficient execution. It is often clearer and less error-prone than imperative steps.
Example. A SQL query describes the desired result; the database plans execution.
Anti-pattern / failure mode. Over-specifying execution order for things that could be optimized or parallelized. Review signal: code that micromanages steps the runtime could handle.
Related. Function Composition (#96), Side Effect Isolation (#99).
99. Side Effect Isolation
Definition. Keep side effects at explicit boundaries; separate pure logic from I/O and mutation.
Rationale. Mixing side effects with logic makes code hard to test and reason about. Isolating them keeps the core pure and effects auditable.
Example. Compute a result in a pure function, then perform I/O in a thin shell.
Anti-pattern / failure mode. Business logic that reads/writes databases or files inline. Review signal: tests that require real I/O or mocking frameworks.
Related. Pure Functions (#94), Immutability (#93).
100. Recursion over Mutable Iteration
Definition. Use recursion or functional iteration constructs rather than mutable loop state where appropriate; prefer immutable traversals.
Rationale. Mutable loop state is a common source of bugs and is hard to reason about. Functional iteration expresses intent clearly and avoids accidental mutation.
Example. Use map/reduce or recursive functions instead of for loops with mutable accumulators.
Anti-pattern / failure mode. Complex loops with multiple mutable variables and early exits. Review signal: off-by-one and state bugs in loops.
Related. Immutability (#93), Higher-Order Functions (#97).
BEAM / OTP Design Principles
101. Let It Crash
Definition. Allow processes to fail and rely on supervision for recovery; don’t defensively handle every error.
Rationale. Defensive error handling bloats code and often leaves the system in a half-broken state. Letting a process crash and restarting it from a known good state is simpler and more robust.
Example. A worker that encounters unexpected state exits; its supervisor restarts it cleanly.
Anti-pattern / failure mode. Catching every error and continuing with corrupt state. Review signal: code full of try/catch that swallows failures.
Related. Supervision Tree (#104), Fault Isolation (#102).
102. Fault Isolation (BEAM/OTP Supervision)
Process-supervision scope — for service-level containment see Fault Isolation (Distributed Services).
Definition. Isolate failures within independent processes; a crash in one process should not take down others.
Rationale. Process isolation contains failures to their owner. Other processes continue serving, and supervisors can restart only what failed.
Example. A crashing chat session process doesn’t kill the whole server.
Anti-pattern / failure mode. Shared state or linked processes that propagate crashes. Review signal: one user action taking down the node.
Related. Share Nothing (#103), Bulkhead (#39), Fault Isolation (Distributed Services) (#49).
103. Share Nothing
Definition. Processes own their state instead of sharing mutable memory; communicate by copying messages.
Rationale. Shared mutable state causes races and coupling. Share-nothing processes are independent, easier to reason about, and safe to distribute.
Example. Each process holds its own state and receives updates via messages rather than shared ETS/heap.
Anti-pattern / failure mode. Processes reading/writing shared mutable structures. Review signal: race conditions and lock contention.
Related. Message Passing (#106), Fault Isolation (#102).
104. Supervision Tree Principle
Definition. Organize processes into hierarchical supervision structures; supervisors restart failed children according to strategy.
Rationale. Supervision makes recovery automatic and policy-driven. Hierarchies mirror the system’s structure and allow targeted restarts.
Example. A top-level supervisor restarts a whole subsystem on failure; a lower one restarts a single worker.
Anti-pattern / failure mode. Flat process structures with no supervision; manual restart logic. Review signal: processes that die and stay dead.
Related. Let It Crash (#101), Process-per-Responsibility (#105).
105. Process-per-Responsibility
Definition. Assign processes clear, independent responsibilities; one process, one job.
Rationale. Focused processes are easier to supervise, restart, and reason about. Mixing responsibilities makes failures ambiguous and recovery coarse.
Example. Separate processes for connection handling, business logic, and persistence.
Anti-pattern / failure mode. A single process doing connection handling, business logic, and DB access. Review signal: a crash loses multiple kinds of state at once.
Related. Supervision Tree (#104), Message Passing (#106).
106. Message Passing
Definition. Communicate between processes through asynchronous messages; avoid direct shared state access.
Rationale. Messages decouple processes in time and space, enabling concurrency and distribution. They make interactions explicit and traceable.
Example. Send a {:process, payload} message to a worker instead of calling a shared function.
Anti-pattern / failure mode. Synchronous calls or shared memory between processes. Review signal: blocking calls that stall schedulers.
Related. Share Nothing (#103), Location Transparency (#107).
107. Location Transparency
Definition. Design communication so local and remote process interactions can share similar abstractions, while recognizing their different failure and latency characteristics.
Rationale. Uniform abstractions simplify code, but remote calls have different failure modes. Design must account for latency and partial failure even when the API looks local.
Example. Use the same message protocol locally and over the network, but add timeouts and retries for remote calls.
Anti-pattern / failure mode. Assuming remote calls behave like local ones; no timeouts. Review signal: cascading failures from slow remote nodes.
Related. Message Passing (#106), Timeout (#41).
108. Preemptive Scheduling
Definition. Rely on the BEAM scheduler to prevent one process from monopolizing execution; keep work in small reductions.
Rationale. Preemptive scheduling keeps the system responsive even when one process does heavy work. Long-running computations should be broken into small steps.
Example. Chunk a large computation into batches and yield between them.
Anti-pattern / failure mode. Long-running NIFs or tight loops that block schedulers. Review signal: latency spikes during heavy computation.
Related. Concurrency over Parallelism (#61), Process-per-Responsibility (#105).
109. Behavior-Based Design
Definition. Use OTP behaviors to establish consistent lifecycle and interaction contracts; standard behaviors reduce boilerplate and errors.
Rationale. Behaviors (GenServer, Supervisor, etc.) encode proven patterns. Using them ensures correct lifecycle handling and reduces custom, error-prone code.
Example. Implement a worker as a GenServer rather than a hand-rolled process loop.
Anti-pattern / failure mode. Custom process loops reimplementing GenServer poorly. Review signal: inconsistent lifecycle or missing call handling.
Related. Supervision Tree (#104), Let It Crash (#101).
110. Explicit State Ownership
Definition. Make it clear which process or component owns and changes each piece of state; centralize mutable state behind a single owner.
Rationale. Ambiguous ownership causes races and inconsistent updates. A single owner makes state changes serial and predictable.
Example. One GenServer owns the counter; others request increments via messages.
Anti-pattern / failure mode. Multiple processes mutating the same state directly. Review signal: lost updates and inconsistent reads.
Related. Single Writer (#46), Share Nothing (#103).
Capstone Practice
Part of the unified study index: Home.
Six multi-pattern exercises that combine design and architecture patterns under realistic delivery constraints. Each capstone includes a scenario, required pattern combination, illustrative non-runnable sketch, and an observable review rubric.
Design-only
- Resilient E-Commerce Order Pipeline — Combine Builder, Strategy, Command, and Observer to separate order assembly, payment variants, refunds, and notifications.
- Concurrent Multi-Format Report Generator — Combine Template Method, Strategy, and Prototype to isolate report jobs while caching and rendering across concurrent workers.
- Moderated Multi-Room Chat Router — Combine Mediator, Chain of Responsibility, Observer, and Memento for screening, delivery, and reversible moderation.
Architecture-only
- Extraction-Ready Modular Monolith for Orders — Combine Modular Monolith, Hexagonal, and Layered architecture to enforce boundaries without early service operations.
- Replayable Event-Driven Payments — Combine Microservices, Event-Driven Architecture, and CQRS + Event Sourcing for duplicate-safe processing and audit replay.
Mixed
- Isolated Multi-Tenant SaaS with Spiky Load — Combine Vertical Slice, Hexagonal, Microservices, Serverless, and Event-Driven patterns for tenant isolation and elastic bursts.
Capstone: Moderated Multi-Room Chat Router
Track
Design-only
Brief
A community platform is adding moderated rooms to its existing chat service, where users currently hold direct references to room delivery and storage components. Messages need per-user rate limits, role checks, and configurable content screening before anyone receives them. Moderators must be able to hide a message and later undo that action without losing the original content or the moderation history. Design a router that keeps room coordination centralized, allows screening rules to evolve, and supports independent delivery and audit subscribers.
Constraints
- The service must sustain 5,000 messages per second across 2,000 active rooms with accepted-message routing below 150 ms at p95.
- Four application instances run concurrently, so per-user and per-room rate counters must be atomic across instances.
- A three-person backend team maintains the existing HTTP/WebSocket stack and a shared Redis deployment.
- Screening chains differ by room, but every chain must end in an explicit allow, reject, or quarantine decision.
- Only senior moderators may restore hidden content, and every hide and restore must retain actor, reason, and timestamp.
Required Patterns
- Mediator — WHY: a room mediator can coordinate participants, persistence, screening, and delivery without giving every peer references to every other component.
- Chain of Responsibility — WHY: rate limiting, authorization, and content screening are ordered handlers that can stop processing or pass a message to the next policy.
- Observer — WHY: WebSocket delivery, metrics, and audit recording can subscribe to accepted or moderated outcomes without becoming links in the screening chain.
- Memento — WHY: a private snapshot of message visibility and content state enables authorized restoration while keeping message internals encapsulated.
Solution Sketch
Illustrative pseudocode — not runnable.
ChatMediator.receive(envelope):
require authenticated sender and existing room membership
chain = chainFactory.forRoom(envelope.roomId)
decision = chain.handle(envelope)
RateLimitHandler: # first, before expensive screening
counters = Redis.atomicIncrement(senderWindow, roomWindow)
return Reject(RATE_LIMITED) when either budget is exhausted
otherwise pass to next
AuthorizationHandler: return Reject(FORBIDDEN) or pass to next
ContentScreenHandler: return Allow, Reject, or Quarantine with reason
if decision is Allow:
message = messageStore.persist(envelope, visible = true)
publishAfterCommit(MessageAccepted(message, decision.reason))
else:
publishAfterCommit(MessageScreened(envelope.id, decision))
moderator.hide(messageId, actor, reason):
require actor has MODERATE permission
message = messageStore.lockForModeration(messageId)
snapshot = message.createMemento() # private originator state + version
moderationLog.append(Hide, snapshot, actor, reason, timestamp)
message.hide()
publishAfterCommit(MessageHidden(messageId))
moderator.undoHide(moderationEventId, actor, reason):
require actor has SENIOR_MODERATE permission
entry = moderationLog.requireHideEvent(moderationEventId)
entry.message.restore(entry.memento, expectedVersion = entry.version)
moderationLog.append(Restore, actor, reason, timestamp)
subscribers = [WebSocketRoomObserver, MetricsObserver, AppendOnlyAuditObserver]
subscriber failures are isolated and retried without rerunning the screening chain
Rubric
- Coordination boundary: Passes if only the mediator coordinates room submission and outcome publication; fails if participants call screening, storage, and one another directly.
- Chain behavior: Passes if each handler documents its stop/pass behavior, all terminal decisions are explicit, and room-specific chains cannot silently fall through.
- Rate limiting: Passes if atomic shared counters enforce both user and room limits before content screening across all four instances.
- Observer separation: Passes if delivery, metrics, and audit subscribe to committed outcomes and their retries cannot resubmit a message to the chain.
- Undo authorization: Passes if restore requires the senior role and restores only the identified hidden message using its own versioned memento.
- Moderation history: Passes if hide and restore append separate records with actor, reason, and timestamp, and restoration never deletes the hide event or later user messages.
Capstone: Replayable Event-Driven Payments
Track
Architecture-only
Brief
A payments company is splitting authorization, ledger posting, and balance inquiries into independently deployable services after repeated release contention. The broker guarantees at-least-once delivery, so a consumer may see the same event several times or receive retries after a timeout. Finance requires an append-only history that can rebuild balance views for audits without rerunning charges. Design the service and data flows so commands, events, and read projections have clear ownership and failure behavior.
Constraints
- The existing platform provides Kubernetes, PostgreSQL, and a durable Kafka-compatible broker; no distributed transaction coordinator is available.
- Authorization requests need an initial response within 400 ms at p95, while balance projections may lag by up to five seconds.
- Every consumer must tolerate duplicate delivery and must not claim that the broker provides exactly-once processing.
- Ledger entries are immutable, and every audit replay must produce a trace tied to the original payment ID and event sequence.
- Card data stays in a PCI-scoped token vault; events carry tokens or references, never card numbers.
- Three teams can operate separate deployment pipelines, dashboards, and on-call runbooks.
Required Patterns
- Microservices — WHY: authorization, ledger, and inquiry have separate scaling and release needs, and each service can exclusively own its database and runtime.
- Event-Driven Architecture — WHY: durable payment events decouple the initial authorization response from ledger and projection work while making retries and asynchronous recovery explicit.
- CQRS + Event Sourcing — WHY: the write side can append authoritative payment events while optimized balance projections serve reads and can be rebuilt from ordered history.
Solution Sketch
Illustrative pseudocode and configuration — not runnable.
service authorization: owns auth_db; deploys independently
service ledger: owns ledger_db; consumes payment events
service inquiry: owns inquiry_db; serves read models only
Authorization.authorize(command):
require valid vaultToken and command.idempotencyKey
transaction auth_db:
decision = authorizeLocallyOrThroughVaultAdapter(command)
aggregate.append(PaymentAuthorized or PaymentDeclined,
paymentId, sequence, decision, commandMetadata)
outbox.insert(unpublishedAggregateEvents) # same local transaction
return decision + paymentId # does not wait for projections
OutboxRelay:
publish event with key = paymentId and stable eventId
mark published only after broker acknowledgement; retry safely
LedgerConsumer.on(event):
transaction ledger_db:
return if inbox.contains(consumer = "ledger", eventId)
inbox.insert(unique(consumer, eventId))
appendImmutableEntry(paymentId, event.sequence, amount, eventId)
acknowledge only after commit
InquiryProjection.on(event):
transaction inquiry_db:
return if inbox.contains(consumer = "balance-v3", eventId)
require next sequence for paymentId or park gap for retry
applyBalance(event); inbox.insert(eventId); recordProjectionLag()
AuditReplay(paymentId, targetProjection = "balance-audit-v1"):
read immutable events in sequence order
build a new projection; issue no authorization, refund, or payout commands
compare result with ledger and retain replay ID, source range, and timestamp
Rubric
- Service ownership: Passes if authorization, ledger, and inquiry each own their database and communicate only through APIs or versioned events, with no shared tables.
- Atomic publication: Passes if aggregate history and outbox records commit in one authorization transaction and relay retries cannot lose an accepted decision.
- Idempotent consumption: Passes if each consumer uses a durable unique
(consumer, eventId)inbox record in the same transaction as its side effects. - Ordering and recovery: Passes if events are partitioned by payment ID, sequence gaps are detected, and failed events have bounded retries plus a visible dead-letter or parking path.
- CQRS separation: Passes if inquiries read only projections, commands use authoritative write state, and API responses expose projection lag or stale status.
- Replay safety: Passes if replay reads the immutable sequence into a new projection and cannot resend financial commands or mutate original ledger entries.
- Compliance and operations: Passes if event schemas exclude card data and each service has its own pipeline, lag metrics, and runbook.
Capstone: Extraction-Ready Modular Monolith for Orders
Track
Architecture-only
Brief
A four-person team is rebuilding an order system that must ship as one deployable application this year, although order processing may become an independent service after the domain stabilizes. The existing codebase shares repositories and domain objects among checkout, inventory, billing, and shipping, making every change cross-cutting. Leadership wants strict boundaries without paying for a broker, service discovery, or multiple deployment pipelines yet. Design a modular monolith that keeps today’s operations simple and leaves a credible extraction path.
Constraints
- One team of four owns the entire system, with one deployment pipeline and one on-call rotation.
- The existing stack is a JVM web framework and PostgreSQL; adding a message broker is out of scope.
- Checkout writes must complete within 500 ms at p95 under normal load and cannot depend on remote calls.
- Checkout, inventory, billing, and shipping need explicit public APIs and separately owned persistence.
- Architecture checks must reject cross-module repository imports and domain dependencies on web or database frameworks.
Required Patterns
- Modular Monolith — WHY: one deployment preserves the small team’s operational simplicity while enforced module APIs and data ownership create future service boundaries.
- Hexagonal Architecture — WHY: ports keep order use cases independent of payment, inventory, HTTP, and PostgreSQL adapters that may change during extraction.
- Layered Architecture — WHY: interface, application, domain, and infrastructure responsibilities remain visible inside each module without creating horizontal layers shared by every module.
Solution Sketch
Illustrative pseudocode and configuration — not runnable.
deployment: orders-monolith (one artifact, one PostgreSQL cluster)
module checkout:
interface: CheckoutController -> PlaceOrderHandler
application: PlaceOrderHandler -> InventoryPort, PaymentPort, OrderRepositoryPort
domain: Order, OrderLine, Money; imports no framework or other module
infrastructure: PostgresOrderRepository implements OrderRepositoryPort
owns: checkout_schema.orders, checkout_schema.outbox
exposes: CheckoutApi.placeOrder(), CheckoutApi.orderStatus()
module inventory:
exposes: InventoryApi.reserve(lines) # in-process public API today
owns: inventory_schema.reservations
forbidden: import checkout.infrastructure.* or checkout_schema.*
module billing:
exposes: BillingApi.authorize(paymentInstruction)
owns: billing_schema.charges
module shipping:
depends on: CheckoutApi events/contracts only, never checkout tables
allowed dependencies:
interface -> application -> domain
infrastructure -> application/domain ports
checkout.application -> inventory.api + billing.api
denied by architecture tests:
*.infrastructure -> anotherModule.infrastructure
anyModule.domain -> webFramework | jdbc | anotherModule.domain
any cross-schema SQL join or repository import
future extraction seam:
move checkout artifact + checkout_schema to Order Service
replace InventoryApi/BillingApi local adapters with remote adapters
keep application handlers and domain unchanged behind the same ports
Rubric
- Module boundaries: Passes if each module names its public API and forbidden dependencies, and architecture checks reject repository imports and cross-schema SQL.
- Data ownership: Passes if every table or schema has exactly one owning module and other modules request data through that owner’s API.
- Dependency direction: Passes if application use cases depend on ports and domain types, while web and database adapters depend inward rather than the reverse.
- Layer placement: Passes if interface, application, domain, and infrastructure responsibilities are shown within modules instead of four global packages shared across the system.
- Transactional scope: Passes if the checkout design identifies its local transaction and does not claim an atomic database transaction across independently owned module schemas without an explicit coordinator.
- Extraction path: Passes if the future order service lists the code and data to move plus the API adapters to replace, with no broker required for the current deployment.
- Team fit: Passes if the design retains one artifact, pipeline, and on-call rotation and does not introduce service discovery or independent deployment obligations.
Capstone: Isolated Multi-Tenant SaaS with Spiky Load
Track
Mixed
Brief
An eight-person platform team is building a SaaS product where tenants submit usage records, configure alerts, and receive monthly invoices. Traffic can jump from a quiet baseline to a large import burst when one tenant closes its books, but that burst must not consume another tenant’s capacity or expose its data. Regulated customers also require regional storage and tenant-specific encryption keys. Design the feature organization, service boundaries, execution model, and asynchronous flows so the team can ship quickly without making isolation an afterthought.
Constraints
- Load varies from 10 to 2,500 requests per second within two minutes, and interactive APIs must remain below 500 ms at p95 during imports.
- Enterprise tenants require dedicated encryption keys; designated tenants also require a dedicated regional database rather than pooled storage.
- The platform must enforce tenant-aware quotas so one import cannot starve unrelated tenants.
- Eight engineers use managed cloud functions, managed PostgreSQL, and an existing event broker, with one small on-call rotation.
- Tenant ID must come from verified identity claims, never from a client-supplied body field or unchecked header.
- Events and stored artifacts must remain in the tenant’s approved region and support duplicate-safe consumption.
Required Patterns
- Vertical Slice Architecture — WHY: submit usage, configure alerts, and generate invoices can each own their request, validation, handler, and persistence path without shared feature-wide controller layers.
- Hexagonal Architecture — WHY: ports for tenant storage, key access, identity, and event publication let each slice stay independent of regional and tenant-specific adapters.
- Microservices — WHY: usage ingestion, alerting, and billing have distinct scaling and deployment profiles and can own separate data instead of sharing tenant tables.
- Serverless — WHY: managed functions absorb sudden ingestion and alert workloads with concurrency limits and queue-based backpressure instead of permanent peak capacity.
- Event-Driven Architecture — WHY: accepted usage events can feed alerting and billing asynchronously while tenant partitioning, retry, and deduplication keep bursts controlled.
Solution Sketch
Illustrative pseudocode and configuration — not runnable.
services:
usage: owns usage data; functions for ingest/query; regional deployments
alerts: owns rules and notification state; scales on regional queue depth
billing: owns invoices and rating state; independent deployment pipeline
Usage vertical slice: SubmitUsage
request -> SubmitUsageEndpoint -> SubmitUsageHandler -> UsageStorePort
-> UsageEventPublisherPort
no imports from ConfigureAlert or GenerateInvoice internals
SubmitUsageHandler.handle(verifiedIdentity, request):
tenant = tenantDirectory.require(verifiedIdentity.tenantClaim)
require request.region == tenant.approvedRegion
permit = quotaPort.acquire(tenant.id, request.recordCount)
reject with tenant-safe 429 when permit is denied
storage = storageFactory.forTenant(tenant) # pooled regional or dedicated DB
crypto = keyPort.forTenant(tenant.id) # tenant-specific enterprise key
result = storage.appendIdempotently(request.batchId, encrypt(request, crypto))
publisher.publishAfterCommit(UsageAccepted, tenant.id, region, result)
regional broker:
partition key = tenant.id + usageStreamId
event metadata = eventId, tenant.id, region, schemaVersion
alert/billing consumers:
enforce regional subscription and tenant authorization
transactionally record consumer + eventId before/with owned state changes
scale on queue depth with per-tenant concurrency and service maxConcurrency
interactive reads never wait for import or invoice completion
isolation policy:
standard = pooled regional DB + tenant predicate enforced by repository + RLS
regulated = dedicated regional DB + tenant key + separate connection policy
Rubric
- Tenant identity: Passes if every slice derives tenant context from verified claims and rejects mismatches in requested region; fails if a body or unchecked header selects storage.
- Isolation enforcement: Passes if the design shows both pooled row-level enforcement and dedicated-database routing, with tenant-specific key selection in the adapter boundary.
- Slice independence: Passes if each feature owns its endpoint, handler, validation, and ports and does not import another feature’s internals.
- Service and data boundaries: Passes if usage, alerts, and billing own their state and use events or APIs rather than cross-service database queries.
- Burst protection: Passes if tenant quotas, function concurrency caps, queue backpressure, and asynchronous processing together protect the 500 ms interactive target.
- Event safety and residency: Passes if consumers deduplicate transactionally, partition by tenant, and keep publication and subscription within the approved region.
- Operational fit: Passes if regional dashboards and alerts expose queue age and per-tenant saturation while retaining managed infrastructure and one small on-call rotation.
Capstone: Resilient E-Commerce Order Pipeline
Track
Design-only
Brief
Your five-person commerce team is replacing a checkout function that mixes order validation, gateway calls, refunds, and customer messaging. Card, wallet, and bank-transfer payments must share one checkout flow, while support staff need an auditable way to refund a captured charge. A recent gateway slowdown caused unchecked retries to duplicate messages and saturate the service. Design the order pipeline so new payment methods and notification channels can be added without rewriting its core flow.
Constraints
- Card numbers must never enter application logs or storage; a PCI-compliant vault returns single-use tokens.
- Checkout should acknowledge a successfully authorized order within 800 ms at p95, excluding asynchronous notifications.
- Five developers maintain an existing modular JVM application and cannot introduce a new broker this quarter.
- Gateway retries are capped at three attempts with exponential backoff and jitter; every attempt must reuse the payment idempotency key.
- Auditors require the actor, command, outcome, and timestamp for every capture and refund, retained for seven years.
Required Patterns
- Builder — WHY: assembly has ordered steps and cross-field rules; a builder can validate lines, totals, currency, and payment token before producing an immutable order.
- Strategy — WHY: card, wallet, and bank transfer are interchangeable payment algorithms behind one contract, with selection kept outside the checkout algorithm.
- Command — WHY: capture and refund become explicit, serializable operations with compensation, actor metadata, and a durable audit history rather than undocumented method calls.
- Observer — WHY: receipt, analytics, and fraud-review subscribers can react to committed order events without coupling those side effects to payment execution.
Solution Sketch
Illustrative pseudocode — not runnable.
order = OrderBuilder()
.customer(input.customerId)
.lines(input.lines)
.currency(input.currency)
.paymentToken(input.vaultToken) # never a card number
.recalculateTotals()
.validateOrReject() # no payment before this succeeds
.buildImmutable()
payment = PaymentRegistry.forMethod(order.method)
command = CaptureCommand(order.id, payment, actor, idempotencyKey)
result = CommandJournal.executeOnce(command):
append(CaptureRequested, actor, timestamp)
outcome = payment.authorize(order.total, retryPolicy = {
attempts: 3, backoff: exponential, jitter: full,
idempotencyKey: command.idempotencyKey
})
append(CaptureSucceeded or CaptureFailed, outcome, timestamp)
commitOrderAndOutboxAtomically(order, outcome)
after commit:
EventBus.publish(OrderPaid or PaymentFailed)
subscribers = [ReceiptObserver, AnalyticsObserver, FraudReviewObserver]
each subscriber consumes independently with its own deduplication key
refund = RefundCommand(originalCaptureId, amount, actor, reason)
refund.compensate():
require originalCaptureId exists and refundableBalance >= amount
gateway.refund(originalCaptureId, refund.idempotencyKey)
appendRefundAudit() # compensation never erases capture history
Rubric
- Order validity: Passes if the builder rejects missing lines, invalid totals, or currency mismatches before any payment strategy is invoked; fails if gateways receive partially assembled orders.
- Variant ownership: Passes if a registry or composition root selects the payment strategy and the order flow contains no card/wallet/bank-transfer branches.
- Retry control: Passes if exactly one named payment boundary owns the three-attempt policy, backoff, jitter, and stable idempotency key; fails if observers or commands also retry gateway calls.
- Refund semantics: Passes if refund references the original capture, checks the refundable balance, and appends a compensating audit record without deleting or rewriting the capture.
- Notification timing: Passes if observers receive only committed outcomes and each subscriber deduplicates delivery independently; fails if a slow subscriber can repeat or roll back payment.
- Audit and PCI scope: Passes if the journal records actor, command, outcome, and timestamp while all examples exclude raw card data and retain stable correlation IDs.
Capstone: Concurrent Multi-Format Report Generator
Track
Design-only
Brief
A finance analytics product generates the same approved report definition as PDF, CSV, and HTML for hundreds of scheduled and interactive requests. The current workers share mutable report templates, so one request occasionally inherits another request’s locale and filters. Repeated reports also rerun identical queries, and traffic spikes leave many workers rendering the same expensive result. Design a generation pipeline with one controlled lifecycle, interchangeable output formats, request-isolated definitions, and safe caching.
Constraints
- The service runs eight worker threads per instance and three instances behind an existing job queue.
- Interactive previews must return a cache hit within 300 ms at p95; cache misses may take up to 20 seconds.
- A three-person team must add XML next quarter without changing query acquisition, caching, or delivery steps.
- Reports on the same
asOftimestamp must use one immutable source snapshot, even when source rows change during rendering. - The shared cache has a 2 GB memory budget, and a cache entry must never contain a partial or failed render.
Required Patterns
- Template Method — WHY: cache lookup, snapshot acquisition, rendering, storage, and delivery form a fixed lifecycle whose invariant order should not be reimplemented by each format.
- Strategy — WHY: PDF, CSV, HTML, and future XML encoders are peer rendering algorithms selected per request while the lifecycle stays unchanged.
- Prototype — WHY: cloning an approved report definition gives each job an isolated configuration without rebuilding complex defaults or sharing mutable filters across workers.
Solution Sketch
Illustrative pseudocode — not runnable.
approvedDefinition = ReportDefinition(
name = "monthly-close", version = 7,
querySpec = validatedQuerySpec, defaults = sharedImmutableDefaults
)
onQueueMessage(message):
definition = approvedDefinition.clone()
definition.setRequestValues(message.filters, message.locale, message.timezone)
definition.freeze() # this worker alone owns the clone
renderer = RendererRegistry.forFormat(message.format)
ReportPipeline(renderer, cache, snapshotStore).run(definition, message.asOf)
ReportPipeline.run(definition, asOf):
key = sha256(tenantId, name, version, normalizedFilters,
locale, timezone, format, asOf)
hit = cache.getCompleteEntry(key)
if hit exists: deliver(hit); return CacheHit
return singleFlight(key): # one render; peers await its result
recheck cache after acquiring key leadership
snapshot = snapshotStore.openConsistentSnapshot(asOf)
data = query(snapshot, definition.querySpec)
artifact = renderer.render(data, definition) # Strategy hook
completed = artifact.sealWithChecksum()
cache.putIfWithinBudget(key, completed, ttlFor(format))
deliver(completed)
close(snapshot)
on error: close(snapshot); publish no cache entry; propagate failure
workers never mutate approvedDefinition, renderer instances, or cache values
Rubric
- Fixed lifecycle: Passes if the template explicitly orders lookup, single-flight control, snapshot acquisition, rendering, sealing, caching, and delivery; fails if format code can skip or reorder those steps.
- Format substitution: Passes if one registry chooses a stateless rendering strategy and adding XML requires only a new strategy plus registration.
- Request isolation: Passes if every job clones the approved definition, applies request values only to that clone, and freezes it before concurrent use.
- Cache correctness: Passes if the key includes tenant, definition version, normalized filters, locale, timezone, format, and
asOf, and only sealed successful artifacts are cached. - Snapshot consistency: Passes if all query and render inputs for a job come from the same
asOfsnapshot and the sketch closes that snapshot on success and failure. - Concurrency and budget: Passes if one leader renders each missing key, followers wait or receive the completed artifact, and the design names an eviction or admission rule for the 2 GB limit.
Selection Guide
Part of the unified study index: Home. Canonical chooser for all three pillars — patterns, architecture, and principles. Category overviews link here instead of keeping competing tables.
Start from your problem, then narrow to 2-3 candidates.
1. Patterns
By problem type
-
Need to create objects without naming exact classes?
- One product kind varies → Factory Method
- Whole family must match → Abstract Factory
- Complex object built in steps → Builder
- Many similar copies → Prototype
- Exactly one shared owner → Singleton
-
Need to fit pieces together?
-
Need to organize behavior?
- Pass request along a chain → Chain of Responsibility
- Turn requests into objects with undo → Command
- Tiny language to evaluate → Interpreter
- Walk a collection without exposing it → Iterator
- Route chat between peers → Mediator
- Snapshot and restore → Memento
- Broadcast change to followers → Observer
- Behavior follows internal status → State
- Swap one swappable step → Strategy
- Fixed skeleton, varying steps → Template Method
- Add operations over a structure → Visitor
Confused pairs
Factory Method vs Abstract Factory vs Builder
| Question | Answer |
|---|---|
| How many kinds per call? | Factory Method: one. Abstract Factory: a family. Builder: one complex object over steps. |
| When to choose Factory Method? | One flow, product kind varies. |
| When to choose Abstract Factory? | Parts must match (theme, platform). |
| When to choose Builder? | Assembly needs order + validation. |
Adapter vs Facade vs Proxy
| Question | Answer |
|---|---|
| What problem? | Adapter: wrong interface. Facade: too complex. Proxy: control access. |
| When Adapter? | Wrap one existing type to fit a new contract. |
| When Facade? | One simple call drives many subsystem calls. |
| When Proxy? | Same interface, but lazy, cached, or guarded. |
Strategy vs State vs Template Method
| Question | Answer |
|---|---|
| Who picks the variant? | Strategy: caller injects. State: object transitions itself. Template Method: subclass fills a step. |
| When Strategy? | Runtime choice among peer algorithms. |
| When State? | Behavior must track status lifecycle. |
| When Template Method? | Skeleton fixed, one step varies by subclass. |
2. Architecture
Canonical decision guidance for the architecture tutorial. The tutorial keeps the full comparison tables; this section is the quick router.
By situation
- Solo project, simple CRUD → Layered + Monolithic.
- Growing team, one deployable → Vertical Slice + Modular Monolith.
- Swappable UI/DB/providers → Hexagonal (or Onion/Clean if domain-centric).
- UI-heavy client → MVC / MVVM / MVP per platform norms.
- Independent scaling per capability → Microservices; add Event-Driven for async flows.
- Enterprise reuse across business units → SOA with ESB governance.
- Spiky workloads, minimal ops → Serverless functions + managed backends.
- Read-heavy with complex writes → CQRS & Event Sourcing; add Event Sourcing when audit/replay matters.
Combinations are normal: e.g., Clean inside a Modular Monolith module, or Vertical Slices each exposing ports, or Microservices communicating via events with CQRS on the hot path.
Confused pairs (summary — full tables in the tutorial)
- Hexagonal vs Onion vs Clean: ports/adapters vs domain-centered rings vs entities+use-cases rings. Choose Hexagonal when swapping infrastructure matters most; Onion/Clean when domain purity or rule enforcement matters most.
- Layered vs Vertical Slice: technical layers vs feature slices. Choose Vertical Slice when features evolve independently.
- Modular Monolith vs Microservices: one deployable with enforced module boundaries vs many independently deployable services. Choose the monolith first; extract when scaling or deploy independence outweighs ops cost.
- Event-Driven vs CQRS & Event Sourcing: broker-decoupled reactions vs read/write separation with an immutable event log. Choose the latter when reads and writes scale differently or audit/replay matters.
3. Principles
How to use the 110-principle catalog without reading it cover to cover.
By problem type
- Designing a class or module? Start with SOLID (1–5) and General Design (6–20): SRP, OCP, DRY, Composition over Inheritance, Program to an Interface.
- Structuring the codebase? See Architecture (21–33): Dependency Rule, Modularity, Bounded Context.
- Going distributed? See Distributed Systems (34–52): CAP, Idempotency, Retry with Backoff, Circuit Breaker — pair with Event-Driven and Microservices.
- Worried about speed or resources? See Performance (53–61): Premature Optimization, Bounded Resource, Batch Processing.
- Handling auth, input, or secrets? See Security (62–69): Zero Trust, Least Privilege, Fail Securely.
- Writing tests? See Testing (70–77): Test Pyramid, FIRST, Test Isolation.
- Designing an API or message format? See API (78–84): Postel’s Law, Backward Compatibility, SemVer.
- Improving delivery? See Development (85–92): Small Batch, Automation First, SSOT.
- Working functionally or on the BEAM? See Functional (93–100) and BEAM/OTP (101–110): Immutability, Let It Crash, Supervision Trees.
How to apply
- Read the principle’s Rationale before applying it; principles trade off against each other (e.g. DRY vs KISS, Strong vs Eventual Consistency).
- Check the Anti-pattern note to recognize misuse.
- Follow Related links to neighboring principles and canonical pattern/architecture pages.
- When a principle summarizes an architecture pattern (Hexagonal, Clean, Onion, CQRS, Event Sourcing), follow its link to the canonical
architecture/page for the full treatment.
Contributing — Originality and Structure Rules
Part of the unified study index: Home. Single source of truth is
content/— see content/MAPPING.md.
All content here is original study material. Reference catalogs are inspiration only.
Inspiration sources (coverage only)
- refactoring.guru Design Patterns catalog — used to confirm the 23-pattern list and category grouping.
- GeeksforGeeks Catalog of Design Patterns — used to confirm pattern names and the Essential Elements lens (name / problem / solution / consequences).
Do not copy from these or any other source.
No-paste rule
- MUST write every paragraph, diagram, and code example from scratch.
- MUST NOT paste text, images, or code from refactoring.guru, GeeksforGeeks, Wikipedia, or books.
- Diagrams MUST be authored as Mermaid or ASCII in the page — no downloaded images.
- Code MUST be your own minimal scenario; do not port reference-site implementations line-for-line.
Where to put it (single source)
- Author exactly one file under
content/(patterns/,architecture/,principles/,practice/). Root anddocs/paths are symlinked views — do not author duplicates. - New pages MUST be listed in
docs/SUMMARY.mdunder the matching pillar (1 Patterns, 2 Architecture, 3 Principles, 4 Practice, 5 Guides) exactly once. - Selection guidance is canonical in
guides/selection.md(§1 patterns, §2 architecture, §3 principles). Category READMEs link to it; do not create competing decision tables.
Shared explanation shape
- Patterns: follow
content/patterns/TEMPLATE.md— Intent → Motivation → Structure → Consequences → Basic Recap → Complex Scenario → When to Use/Not → Examples → Anti-pattern → Related (same-pillar + cross-pillar) → Exercise → Self-check. - Architecture: follow
content/architecture/TEMPLATE.md— Intent → When It Helps → Structure → Rules → Snippet → Basic Recap → Complex Scenario → Trade-offs → When to Use/Not → Anti-pattern → Related (neighbors + cross-pillar). - Principles: follow
content/principles/TEMPLATE.md— Definition → Rationale → Example → Anti-pattern → Related (neighbors + cross-pillar where applied). - Depth content is merged into standard pages: follow the
## Basic Recap,## Complex Scenario, and expanded## Anti-Pattern / Failure Modesections in the standard templates.
Canonical-place rule (no full duplication)
- Architecture patterns are canonical in
content/architecture/*. Principle entries that overlap (Hexagonal, Clean, Onion, CQRS, Event Sourcing) MUST be summaries linking the canonical page, not re-teachings. - Disambiguate near-duplicates by scope in the title and cross-link counterparts (e.g. Fault Isolation distributed-services vs BEAM supervision; Least Privilege vs Least Common Mechanism; Least Astonishment vs Least Surprise).
Declaration
Every new page or example declares in its PR/commit message:
Original wording, fresh diagram, no reference-site content pasted.
Review checklist
- Single file under
content/;docs/SUMMARY.mdlists it once under the right pillar. - Page follows its pillar TEMPLATE order (patterns / architecture / principles / depth).
- At least one benefit, one cost, one use-when, one avoid-when.
- Anti-pattern with review signal present; depth linked where it exists.
- Related includes at least one cross-pillar link (pattern ↔ architecture ↔ principle ↔ practice).
- Overlaps use summary-plus-canonical-link; no full duplication.
- Mermaid/ASCII diagram renders from source (diagrams optional for principles).
- Example in all four languages runs and prints the documented outcome (patterns only).
- Role-mapping comments present in each example entry file (patterns only).
- All links resolve (
find docs -type lmatchescontent/MAPPING.md; no 404s).
GitHub Pages Setup
This repo ships as an mdBook site.
Local preview
cargo install mdbook --version 0.5.4
cargo install mdbook-mermaid --version 0.17.1
make docs-build # writes ./site
make docs-serve # http://127.0.0.1:3000
Enable Pages (Actions source — recommended)
- Repo → Settings → Pages.
- Source: GitHub Actions.
- Push to
main; theDeploy GitHub Pagesworkflow builds and publishes.
Branch-based fallback
If you prefer a branch source instead of Actions:
make docs-build
# copy the built site to a docs/ folder on main, or push site/ to gh-pages
cp -r site docs
git add docs && git commit -m "docs: publish site" && git push
Then set Pages source to Deploy from a branch → main → /docs.
Notes
book.tomlsetssrc = "docs"andbuild-dir = "site".- Mermaid diagrams render via the
mdbook-mermaidpreprocessor; the required runtime (mermaid.min.js) and initializer (mermaid-init.js) are committed at the repo root and wired throughadditional-jsinbook.toml. - To regenerate the Mermaid assets (e.g. after upgrading
mdbook-mermaid), runmdbook-mermaid installin the repo root and commit the resulting changes. - Internal links are relative and must stay within the repo.
Content Mapping — Single Source of Truth
content/ is the sole authoring location. All other content paths are symlinks
(or the mdBook src = "docs" view onto them). Do not author duplicate trees.
Root symlinks → content/
| Path | Target | Purpose |
|---|---|---|
patterns | content/patterns | GoF catalog (23 patterns + depth + category READMEs) |
architecture | content/architecture | Application (6) + System (7) + depth |
principles | content/principles | 110 principles in 11 category files + index |
practice | content/practice | 6 capstones + index |
Verify: ls -la | grep -E "patterns|architecture|practice|principles"
docs/ view (mdBook src = "docs")
| Path | Target | Purpose |
|---|---|---|
docs/patterns | ../content/patterns | mdBook view of pattern catalog |
docs/architecture | ../content/architecture | mdBook view of architecture tutorial |
docs/principles | ../content/principles | mdBook view of principles catalog |
docs/practice | ../content/practice | mdBook view of capstones |
docs/guides | ../guides | mdBook view of guides |
docs/examples | ../examples | mdBook view of runnable examples |
docs/index.md | ../index.md | mdBook home (mirrors root landing) |
Verify: find docs -type l | sort
Canonical places (no full duplication)
- Architecture patterns are canonical in
content/architecture/*. Principles entries that overlap (Hexagonal #23, Clean #24, Onion #25, Event Sourcing #51, CQRS #52) are summaries that link to the canonical architecture page. - Depth content is merged into the standard pages: each pattern and
architecture page now contains its basic recap, complex scenario, edge cases,
and expanded failure-mode guidance. The former
*/depth/*files andDEPTH-TEMPLATE.mdare removed; their content lives in the standard page. - Selection guidance is canonical in
guides/selection.md(three sections: patterns, architecture, principles). Category READMEs link to it; they do not maintain competing decision tables.
Redirect / move policy
- No content deletions without a mapping entry here.
- If a path moves, keep the old symlink until link check (
5.1) is green, then remove it in a follow-up and record the replacement here. - Current moved paths: none pending — this file establishes the baseline.