Skip to content

Lesson 25 of 28Quality and safety

Architecture Anti-Patterns

Recognise the big ball of mud, the distributed monolith, shared databases, god services and wrong abstractions, and know the way out of each.

14 min read0/4 questions

You join a team and are told the system is "microservices". In your first week you learn that a one-line change to the order status needs pull requests in four repos, that every service reads the same orders table, that the checkout page makes 140 network calls, and that a class called OrderManager has 3,000 lines and imports half the codebase. None of this was anyone's plan. Each step was a reasonable local decision under deadline. Anti-patterns are the names for these recurring shapes: solutions that look sensible, are common, and reliably cost more than they save. Knowing the names lets you spot the shape early, explain the cost in a design review, and pick the known way out instead of inventing one.

Why naming them matters

A pattern, as you saw in Design Patterns Overview, is a named solution with known trade-offs. An anti-pattern is the mirror image: a named mistake with known consequences and known refactorings. The name does real work in a meeting. "This is becoming a distributed monolith" is a sentence a staff engineer can act on; "I have a bad feeling about these services" is not.

Each anti-pattern below gets three things: the symptom you can observe, the cause that keeps producing it, and the fix. The causes matter most, because fixing the symptom without the cause just grows it back.

Big ball of mud

Brian Foote and Joseph Yoder named it in 1997: a system with no discernible structure, where any code can call any other code and data is shared freely. Their uncomfortable observation was that it is the most common architecture in the world, because it is what you get by default.

How it happens. Deadline pressure, a team that grows faster than its shared understanding, and no enforced boundaries. Each shortcut ("just import the billing model here") is small and saves an hour. Nothing pushes back, so the shortcuts accumulate until every module depends on every other.

Symptoms. You cannot describe the system in five boxes. Small changes break distant features. Tests need the whole app booted. New engineers take months to become productive. A dependency graph of the modules looks like a hairball, with cycles everywhere.

The way out is almost never a rewrite. It is the patient work from Code Smells and Refactoring and Coupling and Dependencies: find seams, pull one capability at a time behind a small public interface, give it its own tables, and then enforce the boundary with an architecture test (import-linter or dependency-cruiser, from Contract Tests and Architecture Tests) so it cannot erode again. The destination is usually a modular monolith, not microservices. Splitting a ball of mud into services gives you a distributed ball of mud.

The distributed monolith

Monolith vs Microservices introduced this one: services that are separate in deployment but coupled in every way that matters. It is the most expensive anti-pattern on this list, because you pay all the costs of a distributed system (network failures, tracing, N pipelines) and get none of the benefits (independent deploys, fault isolation, team autonomy).

Use this checklist. Two or more "yes" answers and you have one:

  • Do you regularly need to deploy several services together, in a specific order?
  • Do services share a database or read each other's tables?
  • Does a typical user request flow through a synchronous chain of three or more services?
  • Do services share a "common" library of domain models that must be upgraded in lockstep?
  • Does one service going down take most of the product down with it?
  • Do you need a shared staging environment with every service running to test any change?
Anatomy of a distributed monolith
API gatewayAPI gatewayorders-svcorders-svcpricing-svcpricing-svcstock-svcstock-svcusers-svcusers-svcOne shared Postgres: everyone reads ordersOne shared Postgreseveryone reads orderscommon-models v14: shared domain classescommon-models v14shared domain classessyncsyncsync

A synchronous chain. Each hop adds latency, and availabilities multiply: at 99% each, three in a row are up about 97% of the time. If stock is slow, every order is slow.

1/4

The fix depends on whether the split was worth it. If the services exist because microservices sounded modern, merging them back into a modular monolith is often the fastest win a team can make, and there is no shame in it. If the split is justified (separate teams, different scaling), cut the couplings one at a time: give each service its own data, replace the chain with events or with a local copy of the data it needs, and keep shared libraries to technical plumbing (logging, auth clients), never domain models.

Shared database integration

Integration through a shared database deserves its own entry because it is so tempting. Two services need the same data, the data is already in Postgres, so the second service just reads the table. It works perfectly on day one.

The problem is that the schema has become a public API with no owner and no versioning. The team that owns orders can no longer rename a column, split a table, or change what status = 3 means without breaking consumers they may not know about. Worse, other services start writing to it, so the rules about valid orders now live in several codebases. Locks and slow queries from one service hurt the other.

Fixes, in rough order of effort: expose what others need through an API owned by the data's owner; publish events (via the outbox pattern from Event-Driven Architecture) so consumers keep their own copy; or use change data capture (Debezium reading the write-ahead log) to stream changes out. For reporting, copy data into a warehouse instead of letting analysts query production tables. Inside a modular monolith, the same rule applies at module level: one module owns each table, and nobody else joins into it.

God objects, god services and the utils folder

A god object knows and does too much: OrderManager, AppService, Helpers. It starts as the natural home for "order stuff" and becomes the place every change lands, because it already imports everything. The symptoms are easy to measure: thousands of lines, dozens of dependencies, a file that appears in most pull requests, and merge conflicts on it every week.

The service-level version is the god service: one "core" or "platform" service that every other service calls for everything, owned by one overloaded team that becomes the bottleneck for the whole company.

Names are the tell. Manager, Processor, Handler, Helper and utils describe that code does something, not what. A utils.py with string formatting, tax calculation and S3 retries is three modules that have not been named yet. The fix is to split by reason to change (single responsibility, from SOLID): move each function to the module whose concept it serves, so tax.py lives in billing and the retry helper lives with the S3 adapter. A genuinely generic helper, like a date formatter, can stay in a small shared module, but it should be boring and rarely change.

Quick check
OrderService has 2,400 lines, 31 constructor dependencies, and appears in 60% of pull requests. What is the best first step?
Need a nudge? A hint rules out a wrong answer.

Chatty APIs and synchronous chains

A chatty interaction needs many small calls to do one job. The classic is N+1 across services: fetch an order, then call the product service once per line item. In a monolith that loop is N fast in-process queries (still a smell, but survivable). Over the network, every call pays a round trip and adds a chance to fail.

Python
NETWORK_MS = 4 # one round trip inside a data centre, roughly def call(work_ms): # Each call pays network latency plus the provider's own work. return NETWORK_MS + work_ms def order_page_chatty(item_count): total = call(5) # GET /orders/9 for _ in range(item_count): total += call(2) # GET /products/{id}, one per line item return total def order_page_batched(item_count): return call(5) + call(2 + 0.2 * item_count) # GET /products?ids=1,2,3... for n in [3, 30, 300]: print(f"{n:>3} items chatty={order_page_chatty(n):>6.0f} ms batched={order_page_batched(n):>4.0f} ms") # Fan-out: one page calls 10 services in parallel. Each is slow (over its p99) 1% of the time.p_all_fast = 0.99 ** 10print(f"page is slow {100 * (1 - p_all_fast):.1f}% of the time")
Output
Press Run (⌘ Enter) to see what happens.

Two different maths problems hide here. Chains multiply availability: five services at 99% each, called in series, give about 95%. Fan-out multiplies tail latency: if a page waits for ten parallel calls and each is slow 1% of the time, the page is slow nearly 10% of the time. Your p99 becomes your users' p90. This is why Google's "The Tail at Scale" paper argued that large fan-out systems must treat rare slowness as a design problem.

Predict the outputPython

What does this print?

calls = 20
p_one_fast = 0.99
print(round(100 * (1 - p_one_fast ** calls)))
Need a nudge? Hints walk you through it.

Fixes: batch endpoints (GET /products?ids=...), a backend-for-frontend or GraphQL layer that composes data in one place close to the services, keeping a local read model of data you need often (populated by events), caching, and making work asynchronous when the user does not need the result now. For fan-out, set tight timeouts and return partial results, or send a hedged second request when the first is slow.

The wrong abstraction and speculative generality

Sandi Metz put it memorably: duplication is far cheaper than the wrong abstraction. The story goes like this. Two pieces of code look alike, so someone extracts a shared function. A new case arrives that is slightly different, so the function gets a parameter. Then a flag. Then a second flag that only matters when the first is false. Two years later the "shared" function is a maze of conditionals that every caller is afraid to touch. Her advice for the way out is counter-intuitive: inline the abstraction back into each caller, delete the branches each one does not use, and then look again for what is truly shared.

Speculative generality is the same mistake made in advance: plugin systems with one plugin, an AbstractPaymentProviderFactory for the one provider you have, config options nobody sets. It is YAGNI ignored, and it makes the code harder to change in the direction you actually need.

The inner-platform effect is speculative generality at its peak: a system so configurable that it becomes a poor copy of the platform it runs on. A "rules engine" stored in database rows that is really a programming language with no debugger, no tests and no version control. Or a generic entities table with key and value columns that reimplements a database inside a database. When business users need to change rules without a deploy, give them a narrow, well-tested configuration, not a general-purpose language in disguise.

Golden hammer, resume-driven development and cargo cults

The golden hammer is using the tool you know for every problem: Kafka for a queue that handles ten messages a day, a graph database for data that is a simple table, Kubernetes for one container. Resume-driven development is its cousin, where technology is chosen because the team wants it on their CV. Premature microservices combine both: a five-person startup with twelve services, a service mesh and a platform team of one.

Cargo-cult architecture copies the visible shape of a successful company without its reasons. Netflix runs hundreds of services because it has thousands of engineers and extreme scale. Copying the services without the engineers, the tooling and the scale gives you the costs without the problem they solved.

The fix is a habit, not a refactoring: write down the problem before the solution, in an architecture decision record, with the simplest option considered seriously. "Postgres with a jobs table" and "one container on a managed platform" must lose on stated criteria before Kafka and Kubernetes win.

Lava flow and dead code

Lava flow is code that solidified in place: half-finished features, experiments nobody removed, a v1 path still running beside v2 "just in case". Nobody knows if it is used, so nobody dares delete it, and every new engineer has to read it to rule it out. It is common after reorganisations, when the people who knew why the code exists have moved on.

Fixes: measure before you guess. Add a counter or log line to the suspect path and watch it in production for a few weeks. Remove feature flags as soon as a rollout completes (put the removal date on the ticket that adds the flag). Delete with confidence, because version control remembers. Dead code is not free: it is read, compiled, scanned for vulnerabilities and kept compatible on every upgrade.

A field guide

Anti-patternSymptomUsual causeWay out
Big ball of mudEvery change breaks something far awayNo enforced boundaries, deadline shortcutsSeams, modules, architecture tests
Distributed monolithServices deploy togetherSplit by layer, shared dataMerge back, or own data and use events
Shared databaseNobody can change a columnIntegration taken as the easy pathAPI or events from the data's owner, CDC
God object or serviceOne file or team in every changeNatural "home" that attracts everythingSplit by reason to change
Chatty APILatency grows with item countPer-item calls over the networkBatch endpoints, composition, local read models
Wrong abstractionShared code full of flagsMerging code that only looked alikeInline, then re-extract what is truly shared
Golden hammerHeavy tools for small problemsFamiliarity, CV, copying big companiesDecision records with the simple option
Lava flowCode nobody dares deleteLost context, no flag cleanupMeasure usage in production, then delete
Match the pairs0/6 matched

Spot the anti-pattern in each case.

Choose an item, then its match on the other side.
Quick check
Two services read and write the same customers table. What is the cleanest long-term fix?
Need a nudge? A hint rules out a wrong answer.
Key terms
anti-pattern
A common solution that looks reasonable but reliably costs more than it saves, with a known way out.
big ball of mud
A system with no real structure, where any code can depend on any other and boundaries have eroded.
distributed monolith
Separately deployed services that are still coupled, so they must change and deploy together.
god object
A class or service that knows and does too much and attracts most changes.
chatty API
An interaction that needs many small network calls, often one per item, to do one job.
wrong abstraction
Shared code that merged cases which only looked alike, and grows flags and branches to cope.
lava flow
Old, unclear code left in place because nobody knows whether it is safe to remove.