Which design patterns still earn their place?
Strategy, adapter, state machine, outbox, idempotency key and retry with backoff solve problems every backend has. Abstract factories, visitors and deep decorator stacks mostly solve problems we no longer have. The patterns I reach for, with real examples, and the signs of an over-patterned…
The verdict, as we’ll see it earned: the patterns that survive are the ones that solve problems every service has: varying behaviour, wrapping vendors, controlling state, and surviving failure.
- Everyday: strategy, adapter, state machine, repository (lightly), and middleware.
- Distributed systems: outbox, idempotency key, retry with backoff and jitter, circuit breaker.
- Rarely needed in modern backend code: abstract factory, visitor, singleton (as a class), and long decorator chains. Language features (first-class functions, interfaces, closures) cover most of what they were for.
Here’s the case. You open a codebase and find OrderFactoryProvider, and you can’t tell whether you’re looking at hard-won wisdom or ceremony. I have a soft spot for design patterns. At their best they’re compressed experience: someone hit the same problem a hundred times and gave the answer a name we can all share. The mystery is telling the ones that still pull their weight from the ones our languages have quietly absorbed.
Case file
The case OrderFactoryProvider: wisdom or ceremony?Suspects Abstract factory, visitor, singleton, decorator stacks Culprit Patterns that language features have already absorbed The fix Keep the patterns that name a real, recurring problem Evidence The blogging platform’s email adapters, storepackage and middleware
The usual suspects, and the ones with alibis #
These are the patterns that keep turning up at the scene of real problems. Each has a clear motive: a problem it solves, and a simplest form that does the job without fuss.
| Pattern | Problem it solves | Simplest form | Example |
|---|---|---|---|
| Strategy | Choose behaviour at run time | A function or a one-method interface | Choosing an email provider; a pricing rule per customer tier |
| Adapter | Wrap a vendor API in your own terms | One type per vendor implementing your interface | The blogging platform’s Sender implementations for SES, Postmark, Resend, Mailgun and SMTP |
| State machine | Only allow valid transitions | A table of allowed from → to moves, checked in one place (ideally also in the database) |
Order: pending → confirmed → shipped; a post: draft ↔ published, with allowed values enforced by a CHECK constraint |
| Repository | Keep SQL out of handlers | A package of query functions | The blogging platform’s store package |
| Middleware | Cross-cutting concerns around every request | func(http.Handler) http.Handler |
CSRF checks, security headers, request logging, tenant resolution |
| Outbox | Update the database and publish an event without losing either | Insert the event in the same transaction; a relay publishes it | multi-tenant-event-driven-ref |
| Idempotency key | Retries mustn’t create duplicates | A unique key stored with the result | Payment and order APIs; webhook receivers |
| Retry with backoff and jitter | Transient failures | Exponential delay with randomness and a cap | Email delivery queue; calls to flaky APIs |
| Circuit breaker | Stop hammering a dependency that’s down | Fail fast for a while after repeated failures | Calls to a slow third-party API |
A table proves little on its own, though. Let’s watch three of them work actual cases.
Clue 1: the email providers #
The situation: the platform admin chooses which email provider to use, and tests must never send real email.
Who solved it: adapter plus strategy, working as a pair.
- Each provider’s API is wrapped in an adapter that implements one interface,
Send(ctx, email) error. That’s the adapter. - At run time, the saved settings pick which adapter to use. That’s the strategy.
- Tests use a recorder that implements the same interface.
What I admire here is what’s missing. No factory class, no registry framework: a switch on the provider ID returns the right implementation. Two classic patterns, and almost no ceremony. The pattern is in the shape of the code, not in the class names.
Clue 2: the order that went backwards #
The situation: orders move through states, and some moves are illegal (a shipped order can’t go back to pending).
Who solved it: a small state machine.
- List the allowed transitions explicitly, in one place.
- Every change goes through one function that checks the transition and records it.
- Back it with the database: a
CHECKconstraint on allowed status values, and a conditional update (UPDATE ... SET status = 'confirmed' WHERE id = $1 AND status = 'pending') so two concurrent requests can’t both confirm.
The usual culprit for illegal states is scattered if order.status == ... checks across handlers; that’s how they creep in. The lovely part is the conditional update: the database itself refuses the second confirm, so the rule holds even when your code races. One WHERE clause turns a whole class of bug into something that simply cannot happen.
Clue 3: the retry that charged twice #
The situation: a service creates an order and publishes OrderCreated; a consumer charges the card. Networks fail at the worst moments.
Who solved it: outbox, idempotency key, retry with backoff, each covering a gap the others leave.
- The outbox guarantees the event is published if, and only if, the order was committed.
- Delivery is at least once, so the consumer uses an idempotency key (the event or order ID) to make processing the same event twice harmless.
- Failed calls are retried with exponential backoff and jitter, with a cap and a dead-letter queue for what never succeeds.
Together they fit like interlocking pieces: the outbox makes “lost” impossible, the key makes “twice” harmless, and backoff makes “flaky” survivable. The consistency without 2PC post and the delayed retries post follow these leads in depth.
Diagram source
flowchart LR
O["Order committed"] --> OB["Outbox row, same transaction"]
OB --> R["Relay publishes OrderCreated"]
R --> CS["Consumer"]
CS --> K{"Idempotency key seen?"}
K -- yes --> S["Skip: already charged"]
K -- no --> CH["Charge card"]
CH -- fails --> B["Retry with backoff and jitter"]
B --> CH
B -- "never succeeds" --> DLQ["Dead-letter queue"]
The red herrings: patterns to reach for less #
None of these are guilty of being bad ideas; they were good answers to problems many of us no longer have. They just keep getting blamed for, or credited with, work our languages now do.
- Abstract factory, factory method: usually a constructor function or a
switchdoes the job. - Singleton: a package-level value or one instance created at start-up and passed in. Hidden global state makes testing hard.
- Visitor: rarely needed outside compilers and document trees; a
switchon type is clearer in most languages. - Decorator stacks: fine as HTTP middleware; confusing when five wrappers each change behaviour slightly and you can’t tell which one ran.
- Observer / event emitters in-process: easy to start, hard to follow; prefer a direct call, or a real queue if decoupling is the point.
Fingerprints of an over-patterned codebase #
If you suspect the patterns have taken over, these are the marks they leave:
- Class names that are pattern names:
OrderFactoryProvider,NotificationStrategyManager. - Interfaces with exactly one implementation and no test fakes.
- You need a debugger to find which code actually runs.
- Adding a field means touching five files that only pass it along.
Remember this
- Name things after the domain, not the pattern.
- A function or a
switchreplaces most factories and visitors.- Outbox makes “lost” impossible, the key makes “twice” harmless, backoff makes “flaky” survivable.
Case closed: what I’d do by default #
- Name things after the domain, not the pattern.
- Use functions and small interfaces before reaching for classic object-oriented patterns (the OOP or functional post picks up that thread).
- Always use the reliability patterns (outbox, idempotency, retries with backoff) wherever money, messages or external calls are involved.
- Make state machines explicit and back them with the database.
- Remove a pattern when the variation it was built for never arrived.
The patterns that last are the ones that name a real, recurring problem. That’s the quiet beauty of them: use them as a shared vocabulary rather than a checklist, and they save every team from relearning the same lessons the hard way.
Comments
No comments yet.
Sign in to comment. We'll email you a link; no password needed.