System Design: Foundations

Coupling and cohesion

Two measures for judging whether the boundaries you drew are any good, how tightly parts depend on each other and how well each part holds together.

Updated 9 min read

Picture two kitchens. In the first, every cook has a station: one does sauces, one does grill, one does pastry. If the grill cook is off sick, someone else can cover grill, and nobody else’s work changes. In the second kitchen, the salt is in a cupboard that only the pastry cook has the key to, the grill cook borrows the sauce cook’s pans mid-service, and the dishwasher is also the person who takes orders. Everything works on a quiet Tuesday. On a Friday, one person leaving the room stops the whole line. (If you have ever been the only one who knows how a deploy script works, you have worked in the second kitchen.)

The last lesson was about where to cut a system. This one is about how to tell whether you cut well.

Cohesion is how closely the things inside one part belong together. Coupling is how much one part needs to know about, or move with, another part. Good boundaries have high cohesion inside and low coupling across.

Why these two

I think of them as the same question asked from two sides.

  • Cohesion asks: if I open this module, does everything in it exist for one reason?
  • Coupling asks: if I change this module, what else do I have to touch, retest or redeploy?

Both come back to the point from lesson three: boundaries exist to limit the cost of change. Low coupling means a change stays in one place. High cohesion means that place is easy to find, because the things that change together live together.

They also pull on each other. If you pack unrelated things into one part (low cohesion), the neighbours end up depending on it for several different reasons, and coupling goes up. If you split one idea across three parts (also low cohesion), those three parts must constantly talk to each other, and coupling goes up again.

Cohesion: does it have one reason to exist?

The usual way to test cohesion is to try to describe the part in one sentence without using “and”.

  • “Decides which preview environments should be deleted.” Good.
  • “Decides what to delete, formats Slack messages and refreshes the auth token.” That is three parts wearing one name.

A rough ladder, from weak to strong:

Level What holds the part together Example
Coincidental Nothing, really A utils.py with date helpers, a retry decorator and a PDF function
By time It all runs at the same moment A startup() that sets up logging, the database, metrics and a cache
By technology It uses the same tool A rabbitmq/ folder holding publishers for billing, search and email
By feature or purpose It serves one capability A billing module: invoices, prices, payment status

The top level, grouping by purpose, is usually what you want. Grouping by technology looks tidy but spreads one feature across many folders, so a change to “billing” touches the RabbitMQ folder, the Postgres folder and the API folder. That is low cohesion in disguise.

One caution: cohesion is a judgment, not a number. A part can be too small too. If you must open four files to understand one simple rule, the pieces probably wanted to be together.

Coupling: what does it need to know about its neighbour?

Not all dependencies are equal. A few kinds, from the tightest to the loosest:

Kind What the caller depends on Example Why it hurts (or does not)
Shared internals How the other part stores or does things Two services read and write the same orders table A column rename in one silently breaks the other
Shared global state A global both can change A module-level config dict mutated at runtime You cannot reason about one part without the other
Control A flag that steers the other part’s logic send(msg, mode="legacy") where the callee branches on it The caller must know the callee’s internals to pick the flag
Data A defined shape passed in and out should_delete(preview) -> bool Still a dependency, but a small and visible one
Message A message on a queue or an event, nothing more An event order_placed consumed by others Loosest, but you pay in delay and in tracing what happened

The aim is not zero coupling. Parts that never talk are not a system. The aim is to move dependencies down this table, towards narrow, explicit and stable ones.

Coupling at runtime, not just in code

There is a second kind of coupling that code diagrams hide. If service A calls B and C synchronously on every request, then A is only as available as all three together. Roughly speaking, if each is up 99.9% of the time, A can be up at most about 99.7%, and that is before A’s own bugs. Call that runtime coupling. It is why the failure question from lesson one matters here: a boundary that looks clean in code can still be tightly bound in production.

Coupling in time is the same idea. If A needs B to answer right now, they are tied together. If A can drop a message on a queue and carry on, they are less so. The price of breaking that tie is that A no longer knows when, or whether, B did its part, which is its own set of problems for later lessons.

The hidden couplings

The dangerous ones are the ones nobody drew on the diagram:

  • Shared data shapes. Two services agree, by accident, that a user ID is a 36-character string.
  • Shared assumptions. Both assume a message arrives once, or in order.
  • Shared deploys. Two “independent” services that must always be released together are one service.
  • Shared people. If one team must approve every change in three modules, they are coupled through that team.

I have not found a tool that finds these for you. The best test I know is the git history: which files keep changing in the same commit even though they are in different modules? That is coupling you can see.

Imagine a small semantic search feature over internal documents (an illustrative sketch, not a real requirements doc). There are two jobs. An indexer reads documents, turns them into embeddings and stores them. A query service takes a question, embeds it and finds the nearest documents. Say it is FastAPI for the API, PostgreSQL for storage and a worker consuming document changes from RabbitMQ.

A first version is natural: one repository, one embeddings table, a shared embed() function.

Now look for coupling:

  • The indexer and query service both write and read the embeddings table directly, so each knows its columns.
  • Both call the same embedding model, and the vector size is baked into the table definition. If you change the model, both sides must change at the same moment, or queries compare vectors from different models and return plausible-looking nonsense. This is a hidden coupling, and it is a nasty one because nothing crashes.
  • The query service also formats result snippets, and the indexer decides how to chunk text. Chunk size and snippet length quietly depend on each other.

Here is one way to improve it, without rushing to separate services:

Indexer Query service embeddings table + model version Indexer Query service Search store embeddings table Before: both know the table After: one part owns it add(chunks), nearest(q, k)
An arrow means "calls or reads and writes". On the left, two parts share one table and must agree on its details. On the right, a small Search store owns the table and the model version, and the other two only use its two operations.

The change is small: a SearchStore module with two operations, roughly add(chunks) and nearest(question, k). It owns the table, the vector size and the embedding model. The indexer and the query service no longer know any of that.

class SearchStore:
    MODEL = "embedding-model-v1"   # one place that knows the model version

    def add(self, doc_id: str, chunks: list[str]) -> None: ...
    def nearest(self, question: str, k: int = 5) -> list[Hit]: ...

Notice what this does for cohesion too: “everything about how vectors are stored and compared” now lives in one place, and the indexer is left being about chunking and the query service about presenting results. Each can be described in one sentence.

Now the three questions:

  1. More load? Queries grow much faster than indexing, so you may want to scale them separately. Because they only meet at the SearchStore interface, you could later put the query side behind its own service, or give it a read replica, without touching the indexer.
  2. Something breaks? A model change is now a controlled event: bump MODEL, re-embed, then switch. Without the store, “half the rows from the old model” is a bug you find from bad search results, not from an error. The queue between the document source and the indexer also helps: if the indexer is down, changes wait, and search keeps working with slightly old data. That is the runtime coupling being loosened on purpose.
  3. What do we give up? One more module to maintain, and the store becomes a place everyone depends on, so its interface needs care. If it grows into a grab-bag of every storage-related thing, it loses its cohesion and we have rebuilt the problem in a new place. For a weekend prototype, direct table access is perfectly reasonable.

Common mistakes I want to avoid

  • Chasing zero coupling. Parts must depend on something. The goal is narrow, explicit, stable dependencies, not none.
  • Calling a shared database “decoupled”. Separate services that read the same tables are coupled through the schema, and that is the tightest, least visible kind.
  • Grouping by technology. handlers/, models/, queues/ look organised, but a single feature change then crosses all of them.
  • Splitting a single idea across parts. If two modules must always change together, either merge them or find the idea they are both missing.
  • Mistaking a network call for a boundary. Putting an HTTP call between two tightly coupled parts gives you the same coupling plus latency and partial failure.
  • A utils or common dumping ground. It is the classic low-cohesion module, and everything ends up depending on it.
  • Trusting the diagram. Check the git history and the call graph. They show the couplings the boxes do not.

Next up: separation of concerns, which is cohesion applied to the kinds of work a system does, such as business rules, presentation and infrastructure.