All posts
  • #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 everything
on 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.
InteractiveFairy lights: series vs parallel
tap a bulb
loading the demo…
In series, every bulb sits on the only path the current can take, so one failure stops everything. In parallel, each bulb hangs between two rails and fails alone.

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 coupledTightly coupled
B knows about A…a small promise: A's interfaceA's insides: tables, fields, flags
A changes insidenobody else changesothers must change too
A goes downothers carry on, maybe with a fallbackothers go down with it
Who depends on A?read A's interfacesearch everything and hope

Cohesion: the sibling idea

  • Coupling is about the lines between modules. Cohesion is about what's inside one.
  • A PaymentService that only handles payments has high cohesion. A utils.ts that 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.
Arrange the code

wires crossing a wall9

doors between modules0

Module AModule BModule C
Change one kind of code:

Related code is spread over all three modules, so every wire crosses a wall.

The same nine pieces of code in three modules. Shapes are kinds of code; lines are code that needs to talk. Switch between the two arrangements, then 'change' one kind of code and count the modules you'd have to edit.

Two kinds of coupling

Change-time couplingRun-time coupling
What breaksYou can't edit A without editing BA can't run when B is down or slow
ExampleThree modules read the same table, so renaming a column needs three changes and a coordinated deployCheckout calls recommendations and waits, so when recommendations hangs, checkout hangs too
The fairy lights?NoYes
Main fixInterfaces (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.

  1. 01

    1972 · Parnas

    split systems by what is likely to change; hide each secret

  2. 02

    1974 · Structured Design

    Stevens, Myers and Constantine name coupling and cohesion

  3. 03

    ~2002 · Amazon

    teams may only talk through service interfaces (by Yegge's account)

  4. 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 experimentSplit by flowchart stepsSplit by secrets
The modulesread input, shift words around, sort, printeach hides one design decision likely to change, like how lines are stored in memory
Does it work?YesYes
A likely change touchesmany modulesusually 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

  1. Rung 1 of 7

    Content coupling

    One module reaches inside another and reads or changes its private parts.

    Module A

    _items

    Module B

    public APIprivate
    order._items.push(freeGift)

    How much A must know about BB's private fields

looser: aim here

Each rung down means a module needs to know less about its neighbour. Pick a rung to see what travels between the two modules, or step down with the buttons.

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.

InteractiveThree ways to reach Inventory
pick a wiring, then flip a switch
Checkoutorder confirmed

SELECT qty FROM inventory_stock

Inventoryup

reserve() · public

inventory_stockprivate

skuqtywarehouse

Checkout knows Inventory's table and column names.

WiringSurvives a renameSurvives Inventory down
Reach insidenono
Call an interfaceyesno
Leave a messageyesyes
Renaming a column is a change-time problem; Inventory going down is a run-time problem. The interface fixes the first. Only the queue survives both.

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:

checkout.tsts
// 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."

inventory/index.tsts
// 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 sku and a quantity (data coupling), not a whole Order (stamp coupling) or a mode flag (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.
Checkoutcharges the card, then publishes
Event busholds each message until every reader has it

Readers (each on its own path)

Emailsend the receipt
Shippingbook the parcel
Analyticscount the sale
Inventoryadjust stock
Checkout pins one note on the board and walks away. Each reader picks it up when it's ready; a reader that is down just catches up later.
checkout.tsts
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.

  1. 01

    Call payments

    with a timeout set

  2. 02

    No answer in time

    stop waiting

  3. 03

    Fall back

    "payments are slow, try again in a minute"

  4. 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.

InteractiveBreak a module
tap a box
loading the demo…
Arrows point from a module to the module it needs. Solid arrows are direct calls with requests riding them; dashed blue arrows are messages through the event bus. The tightly coupled store has no timeouts or fallbacks, which is what tight coupling tends to look like in the wild.

Things to try:

  1. In the tight store, break Analytics. Then think about how often anyone checks the analytics dashboard on a Sunday.
  2. Switch to Change it and change Inventory in both wirings. Count the modules marked "must edit".
  3. 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

OptionGood whenThe cost
Keep it gluedthe thing is small, cohesive and changed by few peoplethe 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 databaseyou're small, and one owner is clearly in charge of the schemait 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)
Microservicesteams keep blocking each other and the boundaries are already clearfunction 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 monolithyou want boundaries without paying for a network hopthe walls only hold if a tool checks them (Shopify: case file #3)
Abstract everythingyou've already seen the same change happen several timesevery 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.

Case file #01

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.
Source: Yegge's platforms rant (2011)(opens in a new tab)
Case file #02

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.
Source: Segment: Goodbye Microservices(opens in a new tab)
Case file #03

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.
Source: Shopify Engineering: Deconstructing the Monolith(opens in a new tab)
Case file #04

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.
Source: Uber Engineering: Introducing DOMA(opens in a new tab)
Case file #05

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.
Source: Zerodha Tech: Scaling with common sense(opens in a new tab)

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.
  1. W. P. Stevens, G. J. Myers, L. L. Constantine, "Structured Design" (opens in a new tab), IBM Systems Journal 13(2), 1974.
  2. 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.
  3. Steve Yegge, "Stevey's Google Platforms Rant" (opens in a new tab), 2011 (archived copy).
  4. 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).
  5. 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).
  6. Kirsten Westeinde, "Deconstructing the Monolith" (opens in a new tab), Shopify Engineering, 2019.
  7. Shopify Engineering, "Enforcing Modularity in Rails Apps with Packwerk" (opens in a new tab), 2020.
  8. Adam Gluck, "Introducing Domain-Oriented Microservice Architecture" (opens in a new tab), Uber Engineering, 2020.
  9. Kailash Nadh, "Scaling with common sense" (opens in a new tab), Zerodha Tech, 2020, and "Hello, World!" (opens in a new tab), Zerodha Tech.
  10. Sandi Metz, "The Wrong Abstraction" (opens in a new tab), 2016.
  11. Martin Fowler, "MonolithFirst" (opens in a new tab), 2015.
  12. James Lewis and Martin Fowler, "Microservices" (opens in a new tab), 2014.