- #architecture
- #modularity
- #microservices
Tight Coupling: Why One Dead Bulb Darkens the Whole Tree
What coupling and cohesion really mean, where the ideas came from, how interfaces, events and queues loosen things up, and how to avoid the over-abstraction trap. With real case files from Amazon, Segment, Shopify, Uber and Zerodha.
Akshit Bansal20 min readPart 1
grab a chai, and click everythingon this page
In one minute
- Coupling is how much one part of a system has to know about another. The test: if I change or break A, how many other parts change or break with it?
- Tight coupling is fairy lights wired in series: one dead bulb and the whole string goes dark. Loose coupling is parallel wiring: each part fails alone.
- Two kinds, two fixes. Interfaces stop changes spreading. Events and queues, plus timeouts and fallbacks, stop failures spreading.
- Splitting code into services is not the same as decoupling it. Amazon, Segment, Shopify, Uber and Zerodha each found that the right number of boxes is the fewest that keep a change in one place.
Words you need
Module
Any chunk of a system with a boundary around it: a function, a class, a file, a package, a service, even a team.
Like a room in a house
Interface
The small set of questions a module promises to answer, in a fixed shape. How it answers stays private. Also called its public API or contract.
Like the studs on a LEGO brick
Coupling
How much one module has to know or assume about another in order to work.
Like how many strings tie two puppets together
Tight vs loose
Tight: change or break A, and others change or break too. Loose: others don't notice, as long as A keeps its promises.
Like fairy lights in series vs in parallel
Cohesion
How well the things inside one module belong together. High cohesion: one clear job. Low: a bit of everything.
Like a tidy toolbox vs a junk drawer
Change-time coupling
You can't edit A without also editing B.
Like a recipe that says 'see page 12': rewrite page 12 and the recipe breaks
Run-time coupling
A can't run when B is down or slow.
Like a shop that can't open until the delivery van turns up
Synchronous call
A asks B something and waits for the answer before it does anything else.
Like a phone call: you hold until they answer
Event
A small message that says 'this happened', such as OrderPlaced. The sender doesn't wait for anyone to read it.
Like a note pinned on a noticeboard
Event bus / message queue
The box in the middle that holds events until each reader picks them up. Kafka, RabbitMQ and Amazon SQS are popular ones.
Like the noticeboard itself
Timeout and fallback
Stop waiting after a set time, then do something sensible instead of hanging.
Like giving up on a late bus and taking an auto
Information hiding
Keep each decision that is likely to change inside one module, behind its interface.
Like a restaurant kitchen hidden behind a menu
Abstraction
A general shape (an interface, a plugin system, an adapter) that hides details so parts can be swapped.
Like a universal travel adapter
Database schema
The tables a database has, their columns, and what each column means.
Like the labelled shelves in a shared fridge
Deploy
Putting a new version of the code live.
Like swapping in a new menu at a restaurant
CI
Continuous integration: checks that run on every commit and can fail the build if a rule is broken.
Like an inspector at the factory gate
Monolith
One application, built and deployed as a single unit.
Like one big shop under one roof
Microservice
A small service that owns its own data, is deployed on its own, and talks to others over the network.
Like separate stalls in a market
Modular monolith
One deployable application, split inside into modules whose walls a tool enforces.
Like one apartment building with a locked door on every flat
Distributed monolith
Services split across a network that still have to change and deploy together.
Like separate houses you can only renovate all at once
Shared library
Code that many services pull in and use. Each copy can drift to a different version.
Like one recipe book that every branch kitchen photocopies
Fault isolation
When one part fails, the failure stays in that part.
Like a fuse that trips in one room, not the whole house
The night the whole tree went dark
If you grew up with old fairy lights for Christmas or Diwali, you know the ritual: plug in the string, nothing happens, then test every bulb to find the one dead one.
- Many older strings were wired in series. Current had one path: through bulb one, bulb two, bulb three, to the end and back.
- One burned-out filament broke that path, so every bulb went dark.
- Modern strings work around it. Many mini-lights have a tiny shunt in each bulb that lets current skip a dead filament, and better strings wire bulbs in parallel, so each bulb has its own path to power.
Software does this too. A small, boring part fails or changes, and the checkout page, the mobile app and the nightly report all break with it. Engineers call "these parts are wired in series" tight coupling.
What coupling is
Every module needs some others. Checkout needs payments, payments needs a bank. That's fine: software is parts working together. Coupling is about how much each part has to know about the others.
| Loosely coupled | Tightly coupled | |
|---|---|---|
| B knows about A… | a small promise: A's interface | A's insides: tables, fields, flags |
| A changes inside | nobody else changes | others must change too |
| A goes down | others carry on, maybe with a fallback | others go down with it |
| Who depends on A? | read A's interface | search everything and hope |
Cohesion: the sibling idea
- Coupling is about the lines between modules. Cohesion is about what's inside one.
- A
PaymentServicethat only handles payments has high cohesion. Autils.tsthat formats dates, sends emails and calculates GST has low cohesion: it's a junk drawer. - The two are linked. Scatter related code across modules and those modules have to keep talking. Keep it together and most conversations stay inside one module.
- Hence the old slogan: low coupling, high cohesion.
wires crossing a wall9
doors between modules0
Related code is spread over all three modules, so every wire crosses a wall.
Two kinds of coupling
| Change-time coupling | Run-time coupling | |
|---|---|---|
| What breaks | You can't edit A without editing B | A can't run when B is down or slow |
| Example | Three modules read the same table, so renaming a column needs three changes and a coordinated deploy | Checkout calls recommendations and waits, so when recommendations hangs, checkout hangs too |
| The fairy lights? | No | Yes |
| Main fix | Interfaces (information hiding) | Events and queues; timeouts and fallbacks |
Quick check: Three modules read the same database table, so renaming one column means changing all three and deploying them together. Which kind of coupling is that?
Where the idea came from
The idea is old, and it keeps coming back at a bigger scale.
- 01
1972 · Parnas
split systems by what is likely to change; hide each secret
- 02
1974 · Structured Design
Stevens, Myers and Constantine name coupling and cohesion
- 03
~2002 · Amazon
teams may only talk through service interfaces (by Yegge's account)
- 04
2014 · Microservices
Lewis and Fowler name small, separately deployed services
- Larry Constantine's ideas reached a wide audience through the 1974 IBM Systems Journal paper "Structured Design" by Wayne Stevens, Glenford Myers and Constantine. It gave the two properties the names that stuck: coupling and cohesion.
- David Parnas's 1972 paper "On the Criteria To Be Used in Decomposing Systems into Modules" took one small program, a keyword index generator, and split it into modules two ways.
| Parnas's experiment | Split by flowchart steps | Split by secrets |
|---|---|---|
| The modules | read input, shift words around, sort, print | each hides one design decision likely to change, like how lines are stored in memory |
| Does it work? | Yes | Yes |
| A likely change touches | many modules | usually one |
The coupling ladder
Structured design also ranked the kinds of coupling, from worst to best. The exact list varies a little between textbooks; this is how it's usually taught today.
tighter: avoid
Rung 1 of 7
Content coupling
One module reaches inside another and reads or changes its private parts.
Module A
_items
Module B
public APIprivateorder._items.push(freeGift)How much A must know about BB's private fields
looser: aim here
Rung 1 of 7
Content coupling
One module reaches inside another and reads or changes its private parts.
Module A
_items
Module B
order._items.push(freeGift)How much A must know about BB's private fields
Quick check: sendReceipt(user) receives the whole user object but only reads user.email. Which rung is that, and what's the step down?
How loose coupling works
A tiny online store: Checkout needs to reserve stock in Inventory. Here are three ways to wire that, from tightest to loosest. Pick one, then break things.
SELECT qty FROM inventory_stock
Inventoryup
reserve() · public
inventory_stockprivate
skuqtywarehouse
Checkout knows Inventory's table and column names.
| Wiring | Survives a rename | Survives Inventory down |
|---|---|---|
| Reach inside | no | no |
| Call an interface | yes | no |
| Leave a message | yes | yes |
Step 1: spot the secret
Ask Parnas's question: what about Inventory is likely to change?
- How stock is stored: a table today, maybe a separate warehouse system tomorrow.
- How reservations expire.
- Which warehouse fulfils which pin code.
Those are Inventory's secrets. Nobody else should depend on them. Here's the tightly coupled version, where Checkout knows Inventory's table names and column meanings:
// Tightly coupled: Checkout knows Inventory's tables.const row = await db.query( "SELECT qty FROM inventory_stock WHERE sku = $1 AND warehouse_id = 3", [sku],);if (row.qty < quantity) throw new Error("Out of stock");await db.query("UPDATE inventory_stock SET qty = qty - $1 WHERE sku = $2", [quantity, sku]);- If Inventory renames
qty, adds a second warehouse or moves to another database, Checkout breaks. - So do the three other modules that copied this snippet.
Step 2: put the secret behind an interface
An interface is a promise: "ask me these questions, in this shape, and I'll answer in this shape."
// The only thing other modules may import.export interface Inventory { reserve(sku: string, quantity: number): Promise<{ ok: boolean; reservationId?: string }>;}// checkout.ts: loosely coupledconst result = await inventory.reserve(sku, quantity);if (!result.ok) return showOutOfStock(sku);- Checkout now knows one function and two fields. Inventory can rewrite everything behind
reserve()and Checkout never notices. That's the LEGO stud. - It's also a step down the ladder: Checkout passes just a
skuand aquantity(data coupling), not a wholeOrder(stamp coupling) or amodeflag (control coupling).
Step 3: don't wait when you don't have to
Interfaces fix change-time coupling. Run-time coupling needs one more idea.
- When an order is placed, a lot should happen: ship the parcel, email a receipt, update analytics, adjust stock.
- Checkout doesn't need to wait for any of that before saying "order confirmed". It only needs payment to succeed.
- So it publishes one event and moves on.
Readers (each on its own path)
await payments.charge(order.total); // the one thing we must wait forawait bus.publish({ type: "OrderPlaced", orderId: order.id, items: order.items });return confirm(order);// email/worker.ts: a separate module that listensbus.subscribe("OrderPlaced", async (event) => { await sendReceipt(event.orderId);});- If the email service is down for ten minutes, its notes wait on the board, and it catches up when it's back.
- That's the parallel wiring from the fairy lights. One dead bulb doesn't kill the string.
Step 4: for calls you must make, plan for failure
Some calls really are synchronous: you can't confirm an order without charging the card. For those, loose coupling means not trusting the other side to always be there.
- 01
Call payments
with a timeout set
- 02
No answer in time
stop waiting
- 03
Fall back
"payments are slow, try again in a minute"
- 04
Rest of the site stays up
the product page never waited on payments
Try it: break a module
The same store, eight modules, wired both ways. Break things and watch where the failure goes.
Things to try:
- In the tight store, break Analytics. Then think about how often anyone checks the analytics dashboard on a Sunday.
- Switch to Change it and change Inventory in both wirings. Count the modules marked "must edit".
- In the loose store, break the Event bus.
Quick check: In the loose store, Email is down for ten minutes. What happens to new orders?
Other ways to untangle things
Interfaces plus events is the default toolkit, not the only one. Each alternative has an everyday picture and a real cost.
Keep it glued, on purpose
A 200-line script, a prototype, or a function that does one job doesn't need interfaces between its parts. Tight coupling inside a small, cohesive unit is fine; it's between units that it hurts.
Share one database
Several apps read and write the same database. It's fast to build and works while you're small.
Split everything into microservices
Microservices enforce boundaries physically: you can't reach into another service's memory, because it's on another machine.
A modular monolith
One deployable app. Modules may only use each other's public APIs, and a check in CI fails the build when someone sneaks around them.
Abstract everything, just in case
Interfaces, plugin systems, factories, adapters and config flags for changes that might never come.
Which one, when
| Option | Good when | The cost |
|---|---|---|
| Keep it glued | the thing is small, cohesive and changed by few people | the cost of tangles grows with size, people and rate of change. A two-person startup can live in a tangle; a 500-person company can't |
| Share one database | you're small, and one owner is clearly in charge of the schema | it hides coupling instead of removing it. Any team can come to depend on any column, and you find out when a rename breaks production. Amazon banned this back door (case file #1) |
| Microservices | teams keep blocking each other and the boundaries are already clear | function calls become network calls, which can be slow, fail halfway or arrive twice. You need service discovery, retries, tracing and on-call for each one. Wrong boundaries give you a distributed monolith (Segment, Uber: case files #2 and #4) |
| Modular monolith | you want boundaries without paying for a network hop | the walls only hold if a tool checks them (Shopify: case file #3) |
| Abstract everything | you've already seen the same change happen several times | every interface is a guess about the future. Guess wrong and the code is still coupled, now through a badly shaped interface, and harder to read |
When the "alternative" wins
Sometimes the less fashionable option is the better choice, and good teams say so out loud:
- Segment moved back from well over a hundred microservices to a single service, because the boundaries cost them more than they protected.
- Shopify chose a modular monolith over microservices for its core app, and built tooling to enforce boundaries inside one codebase.
- Zerodha, one of India's largest stockbrokers, publicly argues for keeping systems simple and avoiding complexity for its own sake.
- Martin Fowler's "MonolithFirst": most successful microservice systems he's seen started as monoliths that were split once the right boundaries became clear.
In the wild: case files
Real companies, real problems, all publicly documented. Sources are linked on each card and listed at the end.
Amazon
Big tech · early 2000s
no back doors. ever.
- The problem
- By Werner Vogels's account, Amazon.com started as a two-tier monolith: a web application on top of a shared database. As the company grew, teams were entangled through shared code and shared data, and changing one part safely meant coordinating with many others.
- The fix
- According to engineer Steve Yegge's widely read 2011 recollection, Jeff Bezos issued a mandate around 2002: every team must expose its data and functionality through service interfaces, and teams must talk to each other only through those interfaces. No direct linking, no reading another team's data store, no shared memory, no back doors. Interfaces had to be designed as if outside developers would use them.
- The lesson
- In a 2006 ACM Queue interview, Vogels described the result as a decentralised services platform where each service owns its data, and teams own their services end to end ('you build it, you run it'). Yegge argues this habit of building everything as a platform later helped Amazon offer its infrastructure to the world. Note that the mandate's exact wording comes from Yegge's memory, not an official Amazon document.
Segment
Startup (now part of Twilio) · 2015–2018
split ≠ decoupled
- The problem
- Segment sends customer data to hundreds of third-party tools it calls destinations. To stop one slow destination from blocking the rest, each destination got its own service and queue. As destinations multiplied, the shared libraries they all used drifted to different versions across repos. Changing shared code meant updating and redeploying many services, and the operational load kept growing.
- The fix
- In 2017 they consolidated the destinations into a single service and a single repository, with one version of each shared library, and invested in a reliable test suite for it.
- The lesson
- Their 2018 write-up reports 46 improvements to shared libraries in the year after the move, compared with 32 in 2016. They were also candid that they gave up some fault isolation. The services had been separate, but the shared code meant they were never really decoupled.
Shopify
Big tech (e-commerce) · 2017–2020
one deploy, many locked doors
- The problem
- Shopify's core Rails application grew for years with no internal boundaries. Code for calculating shipping rates sat right next to checkout code, and anything could call anything. Coupling made changes slower and riskier as the team grew.
- The fix
- Instead of splitting into microservices, they reorganised the monolith into components by business domain, each with a public API. They built an internal tool, Wedge, to track how isolated each component was, and in 2020 open-sourced Packwerk, which checks boundary violations in CI.
- The lesson
- You can get most of the benefits of boundaries without paying for a network hop. Enforcement matters: boundaries that a tool doesn't check tend to erode.
Uber
Big tech · 2018–2020
microservices need modules too
- The problem
- Uber grew to around 2,200 critical microservices. Their engineering blog describes how this made the system hard to reason about: understanding a dependency chain could mean digging through many services owned by many teams, and even small features could require changes across lots of them.
- The fix
- They introduced Domain-Oriented Microservice Architecture (DOMA). Related services are grouped into domains, each domain is reached through a single gateway, domains are arranged in layers that limit what can depend on what, and teams extend another domain through defined extension points instead of changing its code.
- The lesson
- Coupling comes back at every scale. Once you have enough services, you need the same tools as inside a codebase: cohesive groups, narrow interfaces and rules about dependency direction.
Zerodha
Indian fintech · 2020
simple scales
- The problem
- As one of India's largest stockbrokers, Zerodha serves heavy market-hours traffic. The industry default for that kind of scale is often lots of distributed components.
- The fix
- CTO Kailash Nadh's post 'Scaling with common sense' warns against reaching for a service mesh of microservices where a couple of simpler components would do, and its TL;DR is 'Simple scales'. Zerodha's tech blog also says the team aims to avoid both 'microservice hells and monolith monsters'.
- The lesson
- Loose coupling is a means, not a goal. The right number of boxes is the smallest number that keeps changes local and failures contained.
Learn next and sources
- Next ideas: event-driven design and how message queues deliver (at least once, in order or not); timeouts, retries and circuit breakers for the synchronous calls you keep; tools that enforce module boundaries in CI, like Shopify's Packwerk.
- The best short read on this: Parnas's 1972 paper. It's short, and its two designs of the same program are still the clearest picture of information hiding.
- W. P. Stevens, G. J. Myers, L. L. Constantine, "Structured Design" (opens in a new tab), IBM Systems Journal 13(2), 1974.
- D. L. Parnas, "On the Criteria To Be Used in Decomposing Systems into Modules" (opens in a new tab), Communications of the ACM 15(12), 1972.
- Steve Yegge, "Stevey's Google Platforms Rant" (opens in a new tab), 2011 (archived copy).
- Jim Gray and Werner Vogels, "A Conversation with Werner Vogels" (opens in a new tab), ACM Queue 4(4), 2006. Summary with excerpts: InfoQ (opens in a new tab).
- Alexandra Noonan, "Goodbye Microservices: From 100s of problem children to 1 superstar" (opens in a new tab), Segment, 2018. Follow-up talk: InfoQ, "To Microservices and Back Again" (opens in a new tab).
- Kirsten Westeinde, "Deconstructing the Monolith" (opens in a new tab), Shopify Engineering, 2019.
- Shopify Engineering, "Enforcing Modularity in Rails Apps with Packwerk" (opens in a new tab), 2020.
- Adam Gluck, "Introducing Domain-Oriented Microservice Architecture" (opens in a new tab), Uber Engineering, 2020.
- Kailash Nadh, "Scaling with common sense" (opens in a new tab), Zerodha Tech, 2020, and "Hello, World!" (opens in a new tab), Zerodha Tech.
- Sandi Metz, "The Wrong Abstraction" (opens in a new tab), 2016.
- Martin Fowler, "MonolithFirst" (opens in a new tab), 2015.
- James Lewis and Martin Fowler, "Microservices" (opens in a new tab), 2014.