The design patterns still worth using every week in backend work are the ones that guard a boundary or a failure. These are a gateway around every outside service, a plain function for a rule that varies, an idempotent consumer for messages that arrive twice, a transactional outbox when a database write must be followed by a message, and a strangler fig when you replace a system piece by piece. A query object or a repository joins them only when the same query keeps appearing. The patterns to drop are the ones that prepare for a change nobody has asked for.
I am Ash, a Staff engineer in Toronto. I designed a fraud detection platform on Apache Flink and Kafka that runs the same logic in batch and in real-time streaming. I led a team of 7 that restructured a tangled MVC codebase, in place, with domain-driven design, until it was easy to read and maintain. In my own products I call every model through one provider-neutral layer. This article is for staff engineers and tech leads who want a short list to keep, a test for the rest, and the cost of each. The choices are my opinion, and every claim about a pattern links to its source. I ran the Ruby examples on Ruby 3.4.8.
A pattern pays when it removes a cost you already have
Before I add a pattern, I name the cost it removes, such as a change that touches many files, a failure I have seen in production, or a test that needs a network. If I cannot name one, the pattern is ceremony, which means extra classes that nobody asked for.
The Gang of Four book, Design Patterns: Elements of Reusable Object-Oriented Software, is described by its publisher as a catalog of “simple and succinct solutions to commonly occurring design problems”. It holds 23 patterns, and the key words are “commonly occurring”. In my experience the name is the most useful part in a design review, because “put a gateway in front of that” is quick to say.
Gateway: one class knows the outside service
Martin Fowler’s Gateway is “an object that encapsulates access to an external system or resource”. Many engineers call the same idea an adapter, and I use the two words for the same job. Your code speaks its own words, and one class knows the vendor’s API and translates.
Fowler writes that a gateway “should only include logic that supports this translation between domestic and foreign concepts”, and that any logic building on it belongs to its clients. When a gateway starts deciding things, I have two places to look when something breaks. He also notes that a test can stub out the gateway’s connection and skip the slow remote call.
His page says that being able to swap the external system is “hardly ever a reason to use a gateway”, because “just encapsulating the foreign API is justification enough”. I agree for most vendors. My own products are the exception. I call every model through one provider-neutral layer, so the model for each job is a config value, and each job gets the cheapest model from any provider that passes a measured check on real data. There, swapping is the whole point, and the gateway is what makes it a one-line change. Eric Evans calls the bigger version an anticorruption layer in the DDD reference, an isolating layer that gives you the other system’s functionality “in terms of your own domain model”.
Here it is in Ruby. Two vendors with different shapes return the same small Completion struct, and a config hash picks the gateway for each job.
Completion = Struct.new(:text, :tokens, keyword_init: true)
class VendorAGateway
def initialize(client) = @client = client
def complete(prompt)
r = @client.create(input: prompt)
Completion.new(text: r.dig("choices", 0, "message", "content"), tokens: r.dig("usage", "total"))
end
end
class VendorBGateway
def initialize(client) = @client = client
def complete(prompt)
r = @client.generate(prompt: prompt)
Completion.new(text: r["output"], tokens: r["n_tokens"])
end
end
GATEWAYS = { "a" => VendorAGateway, "b" => VendorBGateway }.freeze
def gateway_for(job, config, clients) = GATEWAYS.fetch(config.fetch(job)).new(clients.fetch(config.fetch(job)))
I ran it with two fake vendor clients. A config of { "summarise" => "a", "classify" => "b" } gave {text: "A says: hello", tokens: 12} and {text: "B says: hello", tokens: 9}, with identical calling code.
It turns into ceremony when you wrap code you own and will not replace, or when you rename a vocabulary everyone knows. Fowler describes teams that did that because “they didn’t like the names”.
Strategy: a rule that varies is usually a function
When a rule varies by customer, region or plan, I do not write an interface and three classes. In Ruby, a lambda or any object that responds to call is the strategy, and a hash keyed by name selects it.
It pays when variants multiply and change on their own schedules, such as tax rules or pricing tiers. It is ceremony for two branches that rarely change.
The Apache Flink documentation says that a job over bounded input “will produce the same final results regardless of the configured execution mode”, meaning batch or streaming. My fraud detection platform ran the same logic in both. My opinion is that this works only when the rule is a function of its input events and does not know whether they came from a file or a topic. The rule is the strategy, and the batch job and the streaming job are two runners that call it.
Idempotent consumer: assume every message arrives twice
Most message brokers promise at-least-once delivery, which means a message can be delivered again. Chris Richardson’s idempotent consumer pattern states the consequence plainly, that “the outcome of processing the same message repeatedly must be the same as processing the message once”. His fix is to record the IDs of processed messages in the database, in the same transaction as the change.
I ran that idea in Ruby with SQLite. The primary key on (subscriber_id, message_id) does the work, because the second insert fails and the transaction rolls back.
def handle_debit(db, message)
db.transaction do
db.execute "INSERT INTO processed_messages VALUES ('ledger', ?)", [message[:id]]
db.execute "UPDATE accounts SET balance = balance - ? WHERE id = ?", [message[:amount], message[:account_id]]
end
:applied
rescue SQLite3::ConstraintException
:duplicate
end
I sent the same message twice to an account with a balance of 100 and a debit of 30. The calls returned :applied and then :duplicate, and the balance was 70.
The same thinking applies to calls you make. The AWS Builders’ Library article on timeouts, retries and backoff with jitter says that a timeout or failure “doesn’t necessarily mean that side effects haven’t happened” and that APIs with side effects “aren’t safe to retry unless they provide idempotency”. So I retry only operations that carry a key, and I add randomness to the wait so clients do not all return at once. The cost is a table that grows, so decide how long to keep the IDs. It is ceremony for work that is naturally repeatable, such as setting a field to a value.
Transactional outbox: when a write and a message must agree
If a service saves a row and then publishes an event, it can crash between the two. The transactional outbox pattern explains why the usual fix fails. A distributed transaction across the database and the broker is often not viable, and sending a message in the middle of a transaction is not reliable, because the transaction might not commit. The solution is to store the message in the database in the same transaction as the business change, and let a separate process send it.
The cost is a second moving part, and the relay can send a message twice. The AWS Prescriptive Guidance page lists duplicate messages as an issue and recommends that the consuming service tracks the processed messages. So the outbox and the idempotent consumer come as a pair. I skip the outbox when there is no broker, or when losing an event is acceptable, such as a metrics ping.
Strangler fig: replace a system one piece at a time
Fowler’s Strangler Fig article describes the alternative to a big rewrite. He writes that he and his colleagues have seen the simple-sounding plan of building a new system that does the same thing “go down in flames most of the time”. The gradual approach, he says, begins with small additions built on top of, and separate from, the legacy code, while behaviour moves across a piece at a time. He admits the cost, because people balk at building transitional architecture that will be thrown away, and argues that “the reduced risk and earlier value from the gradual approach outweigh its costs”.
I lead a move from a monolith to services, sponsored by the CTO, that starts with one team. At a company I worked at, I led the migration of 120 services to Kubernetes with no downtime. Traffic moved one service at a time, and each move had a tested way back. I think the tested way back is the part people skip, and it makes the fig safer than a rewrite. The other half is the seam, where old and new meet and a translation layer, the gateway again, keeps the new model clean. I wrote about the Kubernetes work in how to migrate many services without downtime.
It is ceremony when the system is small enough to replace in one release. It is the wrong first step when the pieces are not clear yet, and then I would enforce module boundaries inside one deployable first, as in when a modular monolith is better than microservices.
Query object and repository: only when the query repeats
Rails ships with a pattern already. The Rails guide to Active Record quotes Fowler’s definition of Active Record as “an object that wraps a row in a database table, encapsulates the database access, and adds domain logic to that data”. A repository on top of that is a second layer that must earn its place.
I go in steps. A repeated condition becomes a scope. A query that is long, or used in several places, becomes a query object, which Fowler describes as “an object that represents a database query”. A repository, which mediates between the domain and the data mapping layers with a collection-like interface, comes last. It pays when domain code must run without a database and you have a real domain model with rules. Evans is restrained about it in the DDD reference, which says to provide repositories “only for aggregate roots” that need direct access. The restructure I led with domain-driven design was done in place and did not split anything into services. A repository for every table is the kind of pattern I would stop at the first sign.
What I would drop, and what every pattern costs
I would drop the singleton, because it is a global variable with a class around it, and in Ruby a module with constants already gives you one instance. I would drop the abstract factory, because plain functions and keyword arguments build objects. I would drop the visitor, because in business code a method on each class reads better. And I would drop any interface with one implementation and no second one planned, because every reader pays for it and nobody gets anything back.
Fowler calls the Anemic Domain Model an anti-pattern, meaning objects that are “little more than bags of getters and setters” while service objects hold all the logic. I read it as a domain that was never modelled.
Every pattern costs a name to learn, a file to open and one more step when you debug. That is fine when it removes a bigger cost.
A plan for the first week
- List every outside service your code calls and check that one class knows each API.
- For every message consumer, ask what happens when the same message arrives twice, and write down the answer.
- Find every place that saves a row and then sends a message, and mark the ones that lose the message if the process dies in between.
- Pick the next piece of any system you are replacing and write down its seam and its way back before you start.
- List your interfaces with one implementation, name the cost each removes, and delete the ones where you cannot.
A small vocabulary that the whole team uses beats a big one that only the author knows.
Frequently asked questions
Are the Gang of Four design patterns still relevant?
Yes, but not all 23 and not in textbook form. The ones that guard a boundary, such as the adapter, keep paying. The ones that work around a language’s limits, such as the visitor, rarely do.
What is the difference between an adapter and a gateway?
In the way I use them, nothing. Both are a class that translates between your code’s words and an outside system’s API.
Do I need an outbox if I already use a message broker?
You need it when a database write and a message must both happen or neither. A broker does not give you that across your database. Pair it with an idempotent consumer, because the relay can send a message more than once.
Is a repository worth it with Rails and Active Record?
Not by default. Start with scopes and query objects, and add a repository when domain code has to be tested without a database.
When is a strangler fig the wrong choice?
When the system is small enough to replace in one release, or when you do not yet know where the pieces split. Draw module boundaries inside one deployable first.