Skip to content

Software Architecture Styles

Basic 51 min read Part 10 of 18

The main ways to structure a system: client-server, layered, monolith, SOA, microservices, event-driven, serverless, P2P, cells and actors, and when each fits.

Summary#

An architecture style is a reusable answer to "how should the pieces of this system be divided, and how should they talk to each other?" Client-server, layered, monolithic, service-oriented, microservices, event-driven, serverless, peer-to-peer, cell-based and actor-based are the styles you will meet most often. Each one makes some things easy, such as independent deployment, offline operation or isolation of failures, and others hard, such as debugging, consistency or cost. Choosing a style therefore means choosing which costs you are willing to pay.

Why It Exists#

Every system that lives longer than a weekend runs into the same problems. The code grows until nobody understands all of it. Different parts need to scale differently: search might need fifty machines while account settings need one. Teams step on each other's changes. One bug in a minor feature crashes the whole product. A deployment of one line of code requires re-testing everything.

None of these problems is solved by writing better functions. They are solved by deciding where the boundaries go and what crosses them. That decision has three parts:

  • Decomposition: what the units are. They might be one big program, layers, modules, services, functions, peers, cells or actors.
  • Communication: how the units interact. Options include in-process function calls, network requests, messages on a queue, events on a log, or messages to a mailbox.
  • Deployment and ownership: whether the units are released together or separately, who owns each one, and what fails together.

Architecture styles are named, well-understood combinations of these three choices. Using a named style has two benefits. It lets you reuse decades of experience about where that style breaks. And it gives a team a shared vocabulary: saying "this is a modular monolith with an event-driven integration layer" tells a new engineer more than a hundred-box diagram.

The wrong style is expensive to undo. A team that splits a ten-person product into forty microservices spends its time on network failures, deployment pipelines and distributed debugging rather than features. A team that keeps a three-hundred-engineer product in one tangled codebase spends its time waiting for builds and fixing each other's regressions. Most real systems also mix styles: a client-server web app whose backend is a modular monolith, which publishes events to a few serverless functions.

How It Works#

Every style answers the same three questions differently. The diagram below groups them by their main idea, and the sections that follow go from the simplest and oldest styles to the most specialised.

Two terms appear throughout. Coupling is how much one part must know about, or wait for, another part to do its job. Cohesion is how closely the things inside one part belong together. Good architecture, in any style, aims for high cohesion inside a unit and loose coupling between units. The styles differ in what a unit is and how loose the coupling can get.

Client-server#

The client-server style splits a system into two roles. A client asks for something, and a server provides it. A browser asking a web server for a page, a mobile app calling an API, and an application querying a database are all client-server interactions. The server owns the shared resource, such as data, computation or a device, and many clients share it.

The defining properties are:

  • Asymmetric roles. Clients initiate requests; servers respond. A server does not normally contact a client unless the client opened a connection first, which is why push notifications and WebSockets need special mechanisms.
  • Centralised state. The authoritative data lives on the server side. Clients may cache, but the server is the source of truth.
  • Many-to-one. One server, or a cluster acting as one logical server, serves many clients.

The style dates from the 1980s, when personal computers began to replace dumb terminals connected to a mainframe. Instead of the mainframe doing everything, the PC ran the user interface and a database server stored the data. It remains the base of almost every system you will design: the web is client-server, and so is nearly every API.

Client-server, in depth#

Thin and thick clients. A thin client does little more than display what the server sends, as a classic server-rendered website does. A thick client, also called a fat or rich client, holds significant logic and state locally, as a single-page application, a mobile app or a desktop email client does. Thin clients are easy to update, since all logic is on the server, and work on weak devices. Thick clients feel faster, can work offline and reduce server load, but you must support many versions in the field at once, because users do not update apps the moment you release. A mobile backend often has to accept requests from app versions that are a year old.

Two-tier and three-tier. In a two-tier design the client talks to the database directly, as early desktop business applications did with a database driver on every PC. It is simple but insecure, since every client holds database credentials, and hard to change, since the schema is the API. A three-tier design inserts an application server between client and database. The client calls an API; the application server enforces rules and talks to the database. Almost every modern system is at least three-tier.

Stateless servers. A server that keeps no per-client state between requests, storing sessions in a shared cache or a token instead, can be cloned behind a load balancer. Any server can handle any request, a failed server loses nothing, and adding capacity means adding machines. This is the single most important property for scaling the server side. See Vertical vs Horizontal Scaling and Stateless Design.

Where client-server strains. The server is a central point: it must be scaled, it must stay available, and every byte flows through it. For large files that many people want at once, such as a new game patch, the server's outbound bandwidth becomes the bottleneck, which is the problem peer-to-peer and content delivery networks solve in different ways. For collaborative and offline-first apps, the strict "server is truth" rule conflicts with users editing while disconnected, which is why those systems add sync protocols and conflict resolution on top. See Conflict Resolution, OT and CRDTs.

Push within client-server. Because only clients initiate, server-to-client updates need either the client to ask repeatedly (polling), or the client to hold a connection open that the server can write to (long polling, server-sent events, WebSockets). This is still client-server: the client opened the channel. See Polling, Long Polling, SSE, WebSockets and Webhooks.

Layered (n-tier)#

A layered architecture organises code into horizontal layers, each with one technical responsibility, where each layer only calls the layer directly below it. The classic four layers are:

  1. Presentation: user interface or API handlers. It parses requests, validates input formats and formats responses.
  2. Business logic, also called the application or domain layer: the rules. "An order over 10,000 dollars needs approval." "A user cannot follow themselves."
  3. Persistence, or data access: code that turns business objects into queries and back, such as repositories and object-relational mappers.
  4. Database: the storage itself.

The terms layer and tier are often used interchangeably, but strictly a layer is a logical separation in code, while a tier is a physical separation onto different machines. A three-layer application can run as one tier on one server, or as three tiers: web servers, application servers and database servers.

The benefit is separation of concerns. A front-end developer can change templates without understanding transactions. You can test business rules without a web server. You can swap an ORM without touching controllers. It is the default structure of most web frameworks, such as Rails, Django, Spring and ASP.NET, which is why it is so common.

Layered, in depth#

Closed and open layers. In a strictly closed layered design a request must pass through every layer in order, so the presentation layer never queries the database directly. That keeps changes contained: if the schema changes, only the persistence layer changes. An open layer may be skipped, for example a shared utilities layer that any layer may call. Too many open layers and the structure stops protecting anything.

The sinkhole anti-pattern. When most requests pass straight through every layer without any layer doing real work, for instance a controller calls a service that calls a repository that runs one SELECT, the layers add code and indirection but no value. Mark Richards, in his O'Reilly report "Software Architecture Patterns" (2015), framed it as an 80-20 rule of thumb: roughly 20 percent of requests being simple pass-throughs is normal, but if the share is closer to 80 percent, the layering is probably too rigid for the problem.

Layers do not scale teams. Layers are horizontal, but features are vertical: adding "gift cards" touches the presentation, business and persistence layers at once. If you assign a team per layer, every feature needs three teams to coordinate. That is why large organisations split vertically, by business capability, into modules or services, and keep layering only inside each one.

Ports and adapters, and its relatives. Classic layering makes the business layer depend on the persistence layer, so business rules indirectly depend on the database technology. Hexagonal architecture, described by Alistair Cockburn around 2005 under the name "ports and adapters", inverts this. The domain core defines ports, which are interfaces such as "OrderRepository" or "PaymentGateway", and the outside world plugs in adapters, such as a PostgreSQL repository, an in-memory fake for tests, a REST controller or a Kafka consumer. Dependencies point inward, toward the domain. Onion architecture (Jeffrey Palermo, 2008) and Clean Architecture (Robert C. Martin, 2012) are close variants with more named rings. The practical effect is that business rules can be tested with no database and no web server, and infrastructure can be replaced without touching them.

Physical tiers and latency. Splitting layers onto separate tiers adds a network hop per tier. Inside one data centre a hop costs roughly 0.5 ms round trip plus serialisation, so three tiers add perhaps 1 to 2 ms, which is usually fine. The danger is chatty interfaces across tiers: a page that makes 200 small calls from the web tier to the application tier pays 200 round trips. Design cross-tier interfaces to be coarse-grained, returning what a screen needs in one call.

Monolith and modular monolith#

A monolith is a system built and deployed as one unit. All features, such as users, catalogue, orders and payments, live in one codebase, compile into one artefact, run in one process (usually many identical copies behind a load balancer) and typically share one database. Calls between features are ordinary function calls.

"Monolith" is often used as an insult, but the style has real strengths:

  • Simple to build and run. One repository, one build, one deployment pipeline, one thing to monitor.
  • Fast and reliable internal calls. A function call takes nanoseconds and cannot time out because of the network. A network call between services takes about a millisecond at best and can fail in many ways.
  • Easy transactions. Placing an order and decrementing stock can be one database transaction, with all-or-nothing behaviour, because both tables are in the same database.
  • Easy refactoring. Moving code between features is a change in an IDE, checked by the compiler, not a coordinated API migration between teams.
  • Easy debugging. One stack trace shows the whole request.

The problems appear with size. A big ball of mud, the name Brian Foote and Joseph Yoder gave in 1997 to a system with no discernible structure, is a monolith in which any code can call any other code and read any table. Every change risks breaking something far away. Builds and test suites take an hour. Deployments are rare and scary because they release everybody's changes at once. One memory leak in a rarely used report takes down checkout. And you can only scale everything together: if image processing needs a lot of memory, every copy of the whole app needs that memory.

A modular monolith keeps the single deployable unit but enforces strong internal boundaries. The code is divided into modules by business capability, such as Catalogue, Orders, Payments and Shipping. Each module:

  • exposes a small public interface, such as a set of service classes or functions, and hides everything else;
  • owns its own tables, or its own schema, which other modules may not query directly;
  • communicates with other modules only through those public interfaces, or through in-process events.

You get most of the organisational benefits of services, such as clear ownership, independent reasoning and contained changes, without the network, distributed transactions or deployment sprawl. And if one module later needs to become a separate service, its boundary is already clean, so extraction is a mechanical job rather than an archaeology project.

Monolith and modular monolith, in depth#

Enforcing the boundaries. A modular monolith decays into a ball of mud unless the rules are checked automatically, because the shortcut of importing another module's internals is always one line away. Common enforcement tools:

  • Language visibility: Java modules (JPMS) and package-private classes, C# internal, Go internal/ packages.
  • Build-system boundaries: separate Gradle or Maven modules, Bazel visibility rules, or Nx module boundaries in TypeScript monorepos, so an illegal import fails the build.
  • Architecture tests: ArchUnit for Java, or custom lint rules, asserting "Orders may only depend on Catalogue's api package".
  • Static analysis built for this purpose: Shopify open-sourced Packwerk in 2020 to enforce package boundaries inside its large Ruby on Rails monolith, where language-level visibility is weak.
  • Database permissions: give each module its own schema and database user, so a module physically cannot read another module's tables.

Shopify's example. Shopify has written publicly about keeping its core commerce platform as one Rails codebase and "componentizing" it into well-bounded components instead of breaking it into microservices, using Packwerk to track and reduce violations of the boundaries over time. The lesson is not that microservices are wrong, but that modularity is a design property, and deployment boundaries are only one way to get it.

Scaling a monolith. A monolith scales horizontally like any stateless service: run many identical copies behind a load balancer. The limits come from:

  • The shared database, usually first. Read replicas, caching and eventually sharding help, as described in Pattern: Scaling Reads and Pattern: Scaling Writes.
  • Uneven resource needs. A monolith can still run different roles: the same codebase started as web servers on some machines and background workers on others, each scaled separately. This simple trick removes much of the pressure to split.
  • Build and test time. Incremental builds, test selection by dependency graph and parallel test runners keep large monoliths workable. Companies with very large monorepos rely on build systems such as Bazel for this.
  • Deployment coordination. With hundreds of engineers merging daily, a single release train needs automation: merge queues, canary releases and feature flags, so incomplete features ship dark.

When the monolith is the right choice. For a new product with an uncertain domain, a small team, or a modest scale, a monolith, ideally modular, is almost always the best start. Martin Fowler's 2015 essay "MonolithFirst" argued that teams building microservices from the start usually get the boundaries wrong, because the domain is not yet understood, and that boundaries are far cheaper to move inside one codebase. The detailed decision of when to split is the subject of Monolith vs Microservices.

Service-oriented architecture (SOA)#

Service-oriented architecture, popular in large enterprises from the late 1990s through the 2000s, structures a system as a set of services, each exposing a business function, such as "check credit" or "create customer", through a formal, network-accessible contract. The goal was reuse across the enterprise: instead of every application implementing customer lookup, one Customer service would serve them all.

Typical SOA ingredients:

  • Contracts in WSDL, the Web Services Description Language, with messages in SOAP, an XML envelope format, often over HTTP but also over message queues.
  • An enterprise service bus (ESB), a central middleware layer that routes messages between services, transforms formats, such as an old mainframe record into XML, orchestrates multi-step processes and enforces security policies.
  • WS-* standards for security, reliable messaging and transactions.
  • A service registry, for example based on UDDI, where services were published and discovered.

Service-oriented architecture, in depth#

What SOA got right. It introduced the idea that a business capability should be exposed once, through a stable, explicit interface, and that consumers should depend on the contract, not on the implementation. Contract-first design, versioned interfaces, and wrapping legacy systems behind services so they can be replaced gradually are all SOA ideas still in use.

Why SOA disappointed many teams. Several problems recurred:

  • The ESB became a bottleneck and a monolith. Business logic leaked into bus configurations: routing rules, transformations and orchestrations that only a central integration team understood. Every change to any integration queued up behind that team.
  • Heavyweight standards. SOAP and the WS-* stack were verbose and complex, with tooling that often did not interoperate cleanly between vendors.
  • Reuse over autonomy. A Customer service used by forty applications cannot change without coordinating forty teams, so it becomes frozen. Shared canonical data models across the whole enterprise were hard to agree and harder to change.
  • Shared databases. Many SOA services were thin wrappers over one big shared database, so they were not truly independent.

SOA versus microservices. Microservices are often described as "SOA done right", and the two share the idea of services with contracts. The differences are in emphasis:

AspectSOA, as commonly practisedMicroservices
UnitLarge enterprise service, often shared widelySmall service owned by one team, around one capability
IntegrationSmart central bus"Smart endpoints and dumb pipes": plain HTTP, gRPC or a simple broker
DataOften a shared enterprise databaseDatabase per service
GoalReuse across the enterpriseIndependent change and deployment
GovernanceCentral standards and integration teamDecentralised, team-chosen within guardrails
ProtocolsSOAP, WS-*, XMLREST, gRPC, JSON or Protobuf, events

The phrase "smart endpoints and dumb pipes" comes from James Lewis and Martin Fowler's article "Microservices" (2014), which popularised the term and explicitly contrasted the style with ESB-centric SOA.

Where SOA still fits. Large organisations integrating many purchased and legacy systems, such as ERP, CRM, mainframes and partner systems, still need routing and transformation. Today that role is usually filled by integration platforms, API gateways and event streaming platforms, but the underlying need is the SOA one: make heterogeneous systems talk through managed contracts.

Microservices#

A microservices architecture builds a system as a set of small, independently deployable services. Each one is organised around a business capability, such as search, cart, payments or notifications, and owned by one team. Each service runs in its own processes, owns its own data and talks to other services over the network through APIs or events. In their 2014 article, Lewis and Fowler listed the characteristics: componentisation via services, organisation around business capabilities, products not projects, smart endpoints and dumb pipes, decentralised governance and data management, infrastructure automation, design for failure, and evolutionary design.

The main promise is independent change. The Payments team can deploy ten times a day without coordinating with the Search team, choose a different database, and scale its service to fit its own load. A crash in Recommendations should not take down Checkout.

The price is that the system is now a distributed system, with all the problems that brings. A function call becomes a network call that can be slow, fail, or succeed without you finding out. A database transaction across two services becomes a saga. A stack trace becomes a distributed trace across a dozen services. You need service discovery, load balancing, retries, timeouts, circuit breakers, deployment pipelines per service, centralised logging and monitoring, and versioned APIs. The infrastructure needed to run microservices well is covered in Microservices Infrastructure Patterns.

Microservices, in depth#

Independent deployability is the test. A system is not microservices just because it has many services. If you must deploy services A, B and C together because they share a database schema or a library version, or because a change in one breaks the others, you have a distributed monolith: all the costs of distribution and none of the independence. Signs include lock-step releases, shared database tables, synchronous call chains where one slow service makes everything slow, and a "common" library everyone must upgrade at once.

Database per service. Each service owns its data, and other services get it only through the owning service's API or events. This is what makes independent change possible, since a team can change its schema freely. It also means no cross-service joins and no cross-service ACID transactions. Queries that span services use API composition, where one component calls several services and merges the results, or CQRS-style read models, where a service subscribes to other services' events and keeps its own denormalised copy. Writes that span services use sagas, sequences of local transactions with compensating actions. See Distributed Transactions: 2PC, Sagas and Outbox.

Sizing services. "Micro" is misleading. The right size is set by team ownership and cohesion, not lines of code. A common guideline is that one team, of perhaps five to ten people, owns one or a few services, and that a service is the smallest unit that can be changed without coordinating with others. Services that are too small, such as one per database table, are called nanoservices: they turn every feature into a multi-service change. Domain-Driven Design for Service Boundaries gives the tools for finding boundaries: bounded contexts and aggregates.

The latency and availability arithmetic. If a request calls five services in sequence, each with a 99th-percentile latency of 20 ms, the request's tail latency is at least that of the slowest and can approach the sum, 100 ms. If each service has 99.9 percent availability and all five are required, the request succeeds only about 0.999 to the power 5, roughly 99.5 percent of the time, which is about 3.6 hours of failure a month instead of 43 minutes. Fan-out makes tails worse: a request that waits for 100 parallel calls, each with a 1 percent chance of being slow, is slow about 63 percent of the time, since 1 minus 0.99 to the power 100 is roughly 0.63. This is the problem Jeffrey Dean and Luiz André Barroso described in "The Tail at Scale" (Communications of the ACM, 2013). Microservice designs therefore favour asynchronous calls, caching, timeouts, fallbacks and limits on call-chain depth.

Conway's law. Melvin Conway observed in 1968, in "How Do Committees Invent?", that organisations design systems whose structure copies the organisation's communication structure. Microservices use this deliberately, in what is often called the inverse Conway manoeuvre: shape the teams to match the architecture you want, and give each team a service it fully owns, from code to production on-call. If the team structure does not match the service boundaries, the boundaries erode.

Best practices, briefly. The practices that consistently separate successful microservice systems from painful ones are:

  • one team per service, with you build it, you run it ownership;
  • a separate datastore per service, with no shared tables;
  • automated CI/CD for every service, so deploying is routine;
  • API versioning and backwards-compatible changes, so consumers are not forced to upgrade in step;
  • observability built in: structured logs, metrics and distributed tracing with correlation IDs (see Observability: Logs, Metrics and Traces);
  • resilience defaults: timeouts, retries with backoff and jitter, circuit breakers and bulkheads (see Resilience Patterns: Timeouts, Retries and Circuit Breakers);
  • asynchronous communication where possible, so that one service being down queues work rather than failing it;
  • containers and orchestration, such as Kubernetes, to standardise packaging and scheduling;
  • an API gateway at the edge for authentication, rate limiting and routing (see API Gateway and Backend-for-Frontend).

A note on Amazon and Netflix. Two migrations are often cited. Amazon moved from a large monolithic application, often called Obidos, toward services in the early 2000s, and internal accounts, popularised by Steve Yegge's widely shared 2011 post, describe a mandate that teams expose their functionality only through service interfaces. Netflix began moving from its data-centre monolith to services on AWS after a major database corruption in 2008 that stopped DVD shipping for several days, and announced the cloud migration complete in early 2016. Both moves were driven by organisational scale, hundreds to thousands of engineers, and took years.

Event-driven architecture#

In an event-driven architecture (EDA), components communicate by producing and reacting to events: records of facts that have already happened, such as "OrderPlaced", "PaymentFailed" or "UserSignedUp". A producer publishes an event to a broker and moves on; it does not know or care who listens. Consumers subscribe to the events they need and react in their own time.

This inverts the dependency of request-driven designs. In a request-driven checkout, the Order service calls Inventory, then Payments, then Email, then Analytics, and must change every time a new step is added. In an event-driven checkout, the Order service publishes "OrderPlaced" once. Inventory, Email and Analytics each subscribe. Adding a Loyalty Points feature means adding a new subscriber, with no change to the Order service.

Event-driven is both an architecture style, the whole system organised around events, and an integration style used inside other styles: microservices and modular monoliths frequently integrate through events. The broker can be a message queue, a pub/sub service or a durable log such as Kafka; see Pub/Sub and Event Streaming.

Event-driven, in depth#

Broker and mediator topologies. Richards' report describes two topologies. In the broker topology, there is no central coordinator: each component reacts to events and emits new ones, so the workflow emerges from a chain of reactions. This is choreography. In the mediator topology, a central orchestrator receives the initial event and tells each component what to do in order, handling errors and compensations. This is orchestration. Choreography is maximally decoupled but makes the end-to-end flow hard to see and hard to change; orchestration makes the flow explicit and easier to monitor, at the cost of a central component that knows about everyone. Most mature systems use choreography for loosely related reactions, such as analytics and notifications, and orchestration for business-critical multi-step processes, such as payments and fulfilment. See Pattern: Multi-Step Processes and Workflows.

Kinds of events. Martin Fowler's 2017 essay "What do you mean by Event-Driven?" distinguished several patterns that share the name:

  • Event notification: a thin event, "Order 42 changed", and consumers call back for details. Simple, but creates callback load and coupling.
  • Event-carried state transfer: the event includes the data, so consumers keep their own copy and never call back. More decoupled and resilient, at the cost of duplicated data and eventual consistency.
  • Event sourcing: the events themselves are the system of record, and current state is derived by replaying them. See Event Sourcing and CQRS.
  • CQRS: separate models for writes and reads, often fed by events.

Costs of the style. Event-driven systems trade immediate consistency and visibility for decoupling:

  • Consumers see changes later, from milliseconds to minutes, so the user interface must tolerate eventual consistency.
  • Messages are usually delivered at least once, so consumers must be idempotent. See Delivery Guarantees: At-Most, At-Least and Exactly-Once.
  • Ordering is guaranteed only within a partition or key, so related events must share a key.
  • Debugging means following an event across many consumers, which needs correlation IDs and tracing.
  • Schemas are contracts. Changing an event's shape can break consumers you did not know existed, so events need schema registries and compatibility rules.
  • The dual-write problem, writing to your database and publishing an event without atomicity, needs the outbox pattern or change data capture. See Change Data Capture and the Outbox Pattern.

A real example. McDonald's engineering has written about building a unified event-driven platform on managed Kafka, with a schema registry to validate events and patterns for handling publishing failures, so that teams across its global digital ordering systems could publish and consume events consistently. More of these trade-offs are covered in Event-Driven Architecture.

Serverless#

Serverless means building on services where the cloud provider runs, scales and patches the servers, and you pay only for what you use. There are still servers; you just never manage them. The style has two halves:

  • Functions-as-a-Service (FaaS), such as AWS Lambda, Google Cloud Run functions and Azure Functions. You upload a function. The platform runs it in response to an event, such as an HTTP request, a file landing in object storage, a message on a queue or a timer. It runs as many copies as there are concurrent events, and bills per invocation and per unit of execution time, often in milliseconds.
  • Backend-as-a-Service (BaaS): managed building blocks that need no capacity planning, such as object storage, serverless databases like DynamoDB on-demand, Aurora Serverless or Firestore, managed queues, authentication services and API gateways.

A serverless application is typically a set of small functions glued together by managed services and events.

The appeal is that there is no idle cost and no capacity planning: a function that runs once an hour costs almost nothing, and the same code handles a sudden spike by running thousands of instances. The constraints are limits and cold starts. Functions have a maximum duration, 15 minutes on AWS Lambda; limited memory, up to about 10 GB on Lambda; no durable local state; and a delay of roughly 100 ms to a few seconds when a new instance must be started, a cold start.

Serverless, in depth#

How a function platform runs your code. When an event arrives and no warm instance is free, the platform must find a host, create an isolated sandbox, load your code, start the language runtime and run your initialisation code, before handling the event. AWS built Firecracker, a lightweight virtual machine monitor, to make this fast and safe: each function instance runs in its own micro-VM with a minimal device model. The paper "Firecracker: Lightweight Virtualization for Serverless Applications" (Alexandru Agache and colleagues, NSDI 2020) reported micro-VMs starting in about 125 ms with a few megabytes of memory overhead each, letting thousands run on one host with VM-level isolation between customers. After an instance handles an event, the platform keeps it warm for a while to reuse it, which is why steady traffic sees few cold starts and bursty traffic sees many.

The cost crossover. Pay-per-use is cheap at low or spiky utilisation and expensive at high, steady utilisation. A rough comparison: a function using 1 GB of memory and running for 100 ms per request, at around 0.0000167 dollars per GB-second plus about 0.20 dollars per million requests, costs roughly 1.9 dollars per million requests. At 10 million requests a month, that is about 19 dollars, far less than any always-on server. At 1,000 requests per second sustained, about 2.6 billion requests a month, it is roughly 5,000 dollars a month, while a few always-on containers that could handle the same load might cost a few hundred dollars. Prices vary by provider and change over time, but the shape holds: serverless wins for spiky or low traffic, and containers or VMs win for high, steady traffic.

Where serverless fits. Event glue, such as reacting to uploads, queue messages or database change streams; scheduled jobs; webhooks; APIs with spiky or unpredictable traffic; prototypes; and data processing that fans out widely and briefly. Where it does not: long-running work, latency-critical paths that cannot tolerate cold starts, workloads holding many persistent connections such as WebSockets or database connection pools, heavy steady traffic, and anything needing specialised hardware or local state. A common failure is a fleet of functions that each open database connections, exhausting the database; connection proxies and serverless-friendly databases address this.

Serverless at scale. Meta described its internal function platform in "XFaaS: Hyperscale and Low Cost Serverless Functions at Meta" (SOSP 2023), handling trillions of calls a day. Because most of its workload is delay-tolerant, it defers calls to off-peak times and shares worker pools across functions to keep utilisation high, which shows that the serverless model is as much about scheduling as about isolation. The full treatment, including scaling models, concurrency limits and serverless databases, is in Serverless and Functions-as-a-Service.

Peer-to-peer#

In a peer-to-peer (P2P) architecture, every participant, a peer, is both client and server. Peers share resources, such as files, bandwidth, storage or computation, directly with each other instead of through a central server. Capacity grows with the number of users: each new peer consumes resources but also contributes them.

Well-known examples:

  • File sharing: Napster (1999) used a central index of who had which file, with transfers directly between peers. BitTorrent, designed by Bram Cohen in 2001, splits files into pieces that peers download from each other and upload to each other at the same time.
  • Content distribution: game and software updates have used P2P to offload bandwidth. Spotify's desktop client used a P2P network to serve music in its early years, described in "Spotify: Large Scale, Low Latency, P2P Music-on-Demand Streaming" (Gunnar Kreitz and Fredrik Niemelä, IEEE P2P 2010), before moving to serving from its own servers and CDNs.
  • Blockchains: Bitcoin, described in Satoshi Nakamoto's 2008 paper, is a P2P network where every full node holds and validates the ledger.
  • Real-time media: WebRTC lets browsers send audio and video directly to each other for small calls, after a server helps them find each other.
  • Distributed storage and naming: IPFS uses a distributed hash table to find which peers hold content.

Peer-to-peer, in depth#

Structured and unstructured networks. In an unstructured P2P network, such as early Gnutella, peers connect arbitrarily and find content by flooding queries to neighbours, which is simple but does not scale. A structured network uses a distributed hash table (DHT): every peer and every key gets an ID in the same space, and each key is stored on the peers whose IDs are closest to it. Lookups are routed in a logarithmic number of hops.

  • Chord (Ion Stoica and colleagues, SIGCOMM 2001) arranges IDs on a ring, the same idea as consistent hashing, and each node keeps a finger table of nodes at distances 1, 2, 4, 8 and so on around the ring, so a lookup halves the distance at every hop: about log₂ N hops, 20 for a million nodes.
  • Kademlia (Petar Maymounkov and David Mazières, IPTPS 2002) measures distance as the XOR of two IDs, and keeps lists of contacts for each distance range, called k-buckets. Lookups query several close contacts in parallel, which tolerates slow and departed peers. Kademlia variants are used by BitTorrent's mainline DHT, IPFS and Ethereum's node discovery.

BitTorrent's incentives. A swarm works only if peers upload as well as download. BitTorrent peers preferentially upload to peers that upload to them, a tit-for-tat strategy, and periodically try a random peer, called optimistic unchoking, to discover better partners. Peers download the rarest pieces first, so every piece stays available even if the original seeder leaves. The result is that a popular file downloads faster as more people want it, the opposite of client-server.

The hard problems. P2P trades a central bottleneck for harder problems everywhere else:

  • Churn: peers join and leave constantly, so data must be replicated across peers and routing tables repaired continuously.
  • NAT traversal: most home devices sit behind network address translation and cannot accept incoming connections. Techniques such as STUN, which discovers your public address, and TURN, which relays traffic when direct connection fails, are needed, and a relay is a server again.
  • Trust and security: peers may lie, serve corrupted data or attack the routing, the Sybil attack being one where an attacker creates many fake identities. Content is verified by hashes, and blockchains use proof-of-work or proof-of-stake to make identities and votes costly.
  • Consistency and search: without a coordinator, global queries, such as "find all files about X", and strong consistency are expensive or impossible.

Hybrid designs are the norm. Most successful "P2P" systems keep some central pieces. Napster had a central index; BitTorrent uses trackers or a DHT for peer discovery; WebRTC needs signalling servers; Skype's original design used ordinary peers promoted to supernodes, and later moved to cloud servers. In system design interviews, P2P is mostly relevant for large-file distribution, such as deploying a multi-gigabyte binary to thousands of servers, which systems such as Uber's Kraken and Alibaba's Dragonfly do with P2P inside the data centre, and for local-first or decentralised applications.

Cell-based architecture#

A cell-based architecture splits a whole system, not just one service, into many independent, identical copies called cells. Each cell has its own full stack: load balancers, application servers, caches, queues and databases. Each cell serves only a subset of customers or a subset of data. A thin cell router at the front decides which cell owns each request, usually by customer or tenant ID.

The point is blast-radius reduction. If a bad deployment, a poison message, a runaway customer or a database failure hits one cell, only that cell's customers are affected. With 20 cells, a cell-level failure affects about 5 percent of customers instead of 100 percent.

AWS describes this approach in its Well-Architected guidance, "Reducing the Scope of Impact with Cell-Based Architecture", and uses it for many of its own services. Slack's engineering team has written about moving its systems toward a cellular design built around availability zones, so that a failing zone can be drained of traffic quickly.

Cell-based, in depth#

Cells versus shards versus microservices. Sharding splits one database by key. Microservices split the system by function, so the User service serves every user. Cells split the whole stack by customer, so every cell contains every function for its own customers. Cells are therefore orthogonal to microservices: each cell can itself be a monolith or a set of microservices.

Design rules for cells.

  • Keep the router thin. The router is the one shared component, so it must be simple, heavily cached and highly available. Often it is just a lookup from tenant ID to cell, cached at the edge or embedded in DNS names, such as a per-cell hostname.
  • No cross-cell calls on the request path. If cell 1 calls cell 2 synchronously, a failure in cell 2 spreads. Shared global data, such as a product catalogue, is replicated into each cell asynchronously.
  • Fixed maximum cell size. Cells are sized so that one cell is well within tested limits, for example a database size and request rate you have load-tested. To grow, you add cells rather than growing cells, so you never run beyond tested limits.
  • Deploy in waves. Ship a change to one canary cell first, watch it, then to a few more, then to all. A bad change hurts one cell's customers for a few minutes rather than everyone.
  • Cell migration. Tenants occasionally need to move between cells, because a customer grew or a cell is being retired. That needs a tool for copying data, dual-writing or pausing writes briefly, and flipping the router entry.

Shuffle sharding. A refinement used by AWS, described by Colm MacCárthaigh in the context of Route 53 and in the Amazon Builders' Library, gives each customer a random combination of a few workers out of many, instead of one fixed cell. With 8 workers and each customer assigned 2, there are 28 possible pairs. A "poison" customer that crashes its two workers affects only customers sharing both workers, about 1 in 28. With 100 workers and combinations of 5, there are about 75 million combinations, so almost no two customers share the same set, and one bad customer harms almost no one else entirely.

The costs. Cells multiply infrastructure: 20 copies of every component cost more than one larger copy, because each must have headroom. Operational tooling must handle fleets of cells: deployment waves, per-cell dashboards and cell-aware alerting. Cross-customer features, such as global search across all tenants or analytics, need data pipelines that gather from every cell. And a very large single customer may not fit in one cell at all. Cells pay off for multi-tenant SaaS and infrastructure services where a full outage is very expensive.

Actor model#

The actor model structures a program as many small, independent actors. Each actor has:

  • private state that no other actor can touch;
  • a mailbox, a queue of incoming messages;
  • behaviour: on each message, an actor can update its own state, send messages to other actors it knows the address of, and create new actors.

Actors never share memory and never lock. They process one message at a time, so code inside an actor is effectively single-threaded and free of race conditions, while millions of actors run concurrently across all cores and machines. Communication is asynchronous message passing: sending a message does not wait for a reply.

The model was introduced by Carl Hewitt, Peter Bishop and Richard Steiger in "A Universal Modular ACTOR Formalism for Artificial Intelligence" (IJCAI 1973). Its best-known industrial implementation is Erlang, created at Ericsson in the late 1980s for telephone switches, where its runtime, the BEAM virtual machine, runs millions of lightweight processes. Other implementations include Akka for the JVM, Microsoft Orleans for .NET, and Elixir, which also runs on the BEAM.

Actor model, in depth#

Let it crash, and supervision. Erlang's OTP framework popularised a fault-tolerance philosophy: do not write defensive code for every possible error inside an actor. If something unexpected happens, let the actor crash, and let its supervisor, a parent actor, restart it in a known good state. Supervisors form a supervision tree with restart strategies, such as restarting just the failed child, or all siblings, and limits on how many restarts are allowed per time window before escalating to the supervisor's own parent. Because actors share no memory, a crash cannot corrupt other actors' state. This is why Erlang has been associated with very high-availability telecom systems.

Location transparency. Because actors interact only by messages to addresses, the sender does not need to know whether the receiver is in the same process or on another machine. Frameworks such as Akka Cluster and Orleans distribute actors across a cluster and route messages automatically. That makes it natural to model one actor per entity, such as per user, per device, per game session or per shopping cart, and spread millions of entities over a cluster.

Virtual actors. Orleans, described in "Orleans: Distributed Virtual Actors for Programmability and Scalability" (Philip Bernstein and colleagues, Microsoft Research technical report, 2014), introduced virtual actors, called grains. A grain always exists logically: you send a message to "player 123" and the runtime activates it on some server if it is not already active, loads its state, and deactivates it when idle. The programmer never creates, places or destroys actors. Orleans was used for cloud services of the Halo games, and the same idea appears in other frameworks, such as Dapr's actor building block and Akka's cluster sharding.

Where actors fit. Actors suit many independent, stateful entities with high concurrency: chat sessions, multiplayer game rooms, IoT device twins, trading order books per instrument, telecom calls and WebSocket connections. WhatsApp famously served very large numbers of concurrent connections per server on Erlang with a small engineering team, and Discord built its real-time messaging infrastructure on Elixir. PayPal engineering wrote that its Akka-based framework, squbs, let a service handle over a billion requests a day on a handful of small virtual machines, because actors use threads efficiently instead of blocking one thread per request.

Where actors are awkward. Asynchronous messages are harder to reason about than function calls: no global ordering between different senders, request-reply needs explicit correlation, and mailboxes can grow without bound if an actor is slower than its senders, which needs back pressure. Delivery between machines is usually at most once, so durable workflows need persistence and retries on top. And debugging a system of a million actors exchanging messages needs good tracing.

Other styles you will hear about#

A few more named styles appear in architecture literature and occasionally in interviews.

  • Pipe-and-filter: data flows through a chain of independent processing steps, the filters, connected by pipes. Unix shell pipelines are the classic example; compilers, image-processing chains and data pipelines, such as extract, transform, load, use the same shape. It is ideal when each step is independent and stateless, and poor when steps must interact.
  • Microkernel, or plug-in, architecture: a minimal core system plus independently developed plug-ins that extend it through defined extension points. Web browsers with extensions, IDEs such as VS Code and Eclipse, and many rules engines work this way.
  • Space-based architecture: application state lives in a replicated in-memory data grid that processing units share, with the database updated asynchronously. It targets extreme, spiky concurrency, such as ticket sales or online auctions, by removing the database from the request path, at the cost of complexity and potential data loss on failure.
  • Lambda and Kappa architectures: data-processing styles that combine batch and stream processing, covered in Batch vs Stream Processing.
  • The Twelve-Factor App: not a style but a set of rules, published by Heroku co-founder Adam Wiggins in 2011, for building services that deploy cleanly to cloud platforms: config in the environment, stateless processes, backing services as attached resources, logs as event streams, disposability, and parity between development and production. Most microservice and serverless platforms assume twelve-factor applications.

When each fits#

The table summarises the core trade-off and the typical fit for each style. The decision tree that follows is the practical shortcut.

StyleMain benefitMain costFits when
Client-serverCentral control and simple securityServer is the bottleneck and single authorityAlmost every web, mobile and API system
Layered or n-tierSeparation of technical concernsFeatures cut across layers; pass-through codeSmall to medium applications; inside each service
MonolithSimplicity; fast calls; ACID transactionsCoupling grows; scale and deploy as oneNew products, small teams, uncertain domains
Modular monolithClear ownership without distributionNeeds enforced boundariesGrowing products with up to a few hundred engineers
SOAEnterprise-wide reuse; integrates legacyCentral bus bottleneck; heavy standardsIntegrating many purchased and legacy systems
MicroservicesIndependent deploy and scaling per teamDistributed-systems complexity and ops costMany teams, distinct scaling needs, mature DevOps
Event-drivenDecoupled producers and consumers; easy extensionEventual consistency; harder debuggingMany reactions to the same facts; async workflows
ServerlessNo idle cost; automatic scaling; no servers to runCold starts, limits, cost at steady high loadSpiky or low traffic, event glue, small teams
Peer-to-peerCapacity grows with users; no central bottleneckChurn, NAT, trust, weak consistencyLarge-file distribution, decentralised and local-first apps
Cell-basedSmall blast radius; tested limits; safe deploysDuplicate infrastructure; routing and migration toolingMulti-tenant SaaS and infrastructure with costly outages
Actor modelMassive concurrency without locks; fault isolationAsync reasoning; mailbox growth; at-most-once deliveryMany stateful entities: chats, games, devices, sessions

Two styles sit outside this tree because they are chosen for specific workload shapes. Choose actors when you have many concurrent, stateful entities, and peer-to-peer when distribution bandwidth or decentralisation is the requirement. Choose SOA-style integration when the problem is connecting existing heterogeneous systems rather than building a new one.

When to Use It#

There is no single "use architecture styles" decision. The question is which style to apply to which part of the system. Concrete signals:

  • Fewer than about 10 to 20 engineers, a new product or an uncertain domain: a monolith, made modular from day one. Splitting before you know the domain usually puts the boundaries in the wrong place.
  • Several teams of five to ten engineers are blocked on each other's releases, builds take tens of minutes, and parts of the system have very different scaling or reliability needs: extract microservices along business capabilities, starting with the part that changes most or scales differently.
  • The same business fact triggers many reactions, such as an order triggering emails, analytics, loyalty and fraud checks, or producers and consumers run at very different speeds: event-driven integration.
  • Traffic is spiky, bursty or low, such as a webhook receiver that is idle most of the day, a nightly job, or a launch-day spike of 100 times normal; or the team has no operations capacity: serverless for those workloads.
  • A full outage would be catastrophic, and the system is multi-tenant: cells, so one failure or bad deploy affects a few percent of customers.
  • Millions of concurrent, stateful entities, such as connections, game rooms, devices or sessions, each with frequent small updates: actors.
  • Very large files must reach thousands of machines or users at once, or the product must work without a central server: peer-to-peer, usually hybrid.
  • Many existing systems must be integrated, such as ERP, CRM, mainframe and partner APIs: SOA-style integration through gateways and an event backbone.
  • In an interview: state the overall style in one sentence early, such as "a set of services behind an API gateway, integrated with Kafka for async work", and justify it from the requirements.

When NOT to Use It#

  • Do not start with microservices for a small team or a new product. You pay the distributed-systems tax, network failures, sagas and tracing, before you have the scale or the team structure that justifies it.
  • Do not split by technical layer into services, such as a "database service" and a "business logic service". That multiplies network hops without giving any team independence.
  • Do not use event-driven integration where the user needs an immediate, consistent answer, such as "did my payment go through?", unless you design the user experience around asynchronous completion.
  • Do not use serverless for long-running work over about 15 minutes, latency-critical paths that cannot tolerate cold starts, persistent-connection workloads, or high and steady traffic where reserved compute is much cheaper.
  • Do not build cells for a single-tenant system or a small product; the duplicated infrastructure and tooling cost far exceeds the benefit.
  • Do not reach for actors for ordinary request-response CRUD; a stateless service and a database are simpler.
  • Do not build peer-to-peer when a CDN would solve the bandwidth problem; CDNs give most of the benefit with none of the churn, NAT or trust problems.
  • Do not adopt a style because a large company uses it. Their constraints, thousands of engineers and billions of requests, are not yours.

How to Implement It#

Choosing and applying a style is a design process, not a one-time decision:

  1. Write down the drivers. List the quality attributes that matter most, such as availability, latency, scalability, cost and time to market, with numbers where possible. Also list the organisational facts: team count, skills and operational maturity.
  2. Map the domain. Identify the business capabilities and their data, such as catalogue, orders, payments and accounts, and how tightly they interact. These become modules, and possibly later services.
  3. Pick the default style for the core. Usually a modular monolith, or a small number of coarse services, behind a client-server API.
  4. Pick integration styles per interaction. Use synchronous calls where the caller needs an answer now, and events where the caller only needs to announce a fact.
  5. Choose specialised styles for specific parts. Serverless for spiky glue, actors for stateful real-time entities, cells for blast-radius control, peer-to-peer for mass distribution.
  6. Enforce the boundaries. Use module visibility, build rules, architecture tests and separate database schemas, so the style survives contact with deadlines.
  7. Record the decision. Write a short architecture decision record (ADR): the context, the decision, the alternatives considered and the consequences, so future engineers know why.
  8. Plan the evolution. Define the signals that would trigger the next step, such as "extract Search when it needs separate scaling", and the migration path, such as the strangler fig pattern of routing traffic gradually to new services.

An architecture decision record, in a common short format:

ADR-007: Integrate Orders and downstream services with events
 
Status: Accepted (2026-03-14)
 
Context:
  Order placement triggers email, analytics, loyalty and fraud checks.
  Today Orders calls each synchronously; p99 checkout latency is 900 ms
  and an Analytics outage fails checkouts.
 
Decision:
  Orders writes OrderPlaced to an outbox table in the same transaction
  as the order. A relay publishes to Kafka topic orders.v1, keyed by orderId.
  Email, analytics, loyalty and fraud subscribe as separate consumer groups.
 
Alternatives considered:
  - Keep synchronous calls with circuit breakers: still couples latency.
  - Orchestrate with a workflow engine: overkill for independent reactions.
 
Consequences:
  + Checkout latency no longer depends on downstream services.
  + New reactions need no change to Orders.
  - Consumers see orders seconds later; must be idempotent on orderId.
  - Requires schema registry and consumer-lag alerting.
TechnologyFits when
Rails, Django, Spring Boot, ASP.NET, LaravelMonoliths and modular monoliths with conventional layering
Packwerk, ArchUnit, Nx boundaries, Java modulesEnforcing module boundaries inside one codebase
Kubernetes, Amazon ECS, NomadRunning many containerised services with a common deployment model
gRPC, REST over HTTP, GraphQLSynchronous calls between clients and services
Kafka, Pulsar, RabbitMQ, SNS and SQS, EventBridgeEvent-driven integration and async work
AWS Lambda, Cloud Run, Azure Functions, Cloudflare WorkersServerless functions for events, spiky APIs and edge logic
Erlang and Elixir on the BEAM, Akka, Orleans, Dapr actorsActor-based systems with many stateful entities
WebRTC, libp2p, BitTorrent libraries, Kraken, DragonflyPeer-to-peer media, decentralised apps, large-file distribution
Istio, Linkerd, EnvoyService-to-service traffic control in microservices
Temporal, AWS Step FunctionsOrchestrated multi-step workflows across services

Trade-offs#

OptionProsConsPick when
MonolithSimplest to build, test, deploy and debug; ACID transactionsCoupling grows; whole-app deploys and scalingSmall team, new product, uncertain domain
Modular monolithOwnership and clear boundaries without network costsDiscipline and tooling to keep boundariesDefault for most products up to large size
MicroservicesIndependent deploys, scaling, tech choices and failure isolationNetwork failures, eventual consistency, ops overheadMany teams, clear domains, mature automation
SOA with an ESBIntegrates heterogeneous and legacy systems centrallyCentral bottleneck; heavyweight; slow changeEnterprise integration of existing systems
Event-drivenLoose coupling; easy to add consumers; absorbs spikesEventual consistency; harder tracing; schema governanceMany reactions to one fact; async workflows
ServerlessNo idle cost; scale to zero and to bursts; no serversCold starts, limits, vendor lock-in, cost at steady loadSpiky or low traffic, glue code, small teams
Peer-to-peerScales with users; no central bandwidth bottleneckChurn, NAT, security, weak consistencyMass distribution, decentralisation
Cell-basedContains failures and bad deploys to a few percentDuplicated infrastructure; routing and migration toolingMulti-tenant SaaS with very costly outages
Actor modelLock-free concurrency; supervision; location transparencyAsync reasoning; back pressure; delivery guaranteesMany concurrent stateful entities

Common Pitfalls#

  • The distributed monolith. Services that share a database, deploy together or call each other in long synchronous chains combine the costs of both styles.
  • Choosing by fashion. Microservices, serverless or event-driven designs adopted because they are popular rather than because a requirement demands them.
  • Wrong boundaries. Splitting by technical layer or by noun, such as a "User service" every request depends on, instead of by business capability, creates chatty, tightly coupled services.
  • Ignoring Conway's law. Service boundaries that do not match team boundaries need constant cross-team coordination and erode over time.
  • Unenforced modularity. A "modular" monolith without automated boundary checks becomes a ball of mud within a year or two.
  • Event spaghetti. Long choreographed chains of events that nobody can trace end to end, with no owner for the overall business process.
  • Serverless cost and connection surprises. Functions that exhaust database connections, or a steady high-traffic workload whose bill exceeds that of always-on servers several times over.
  • Cells that share something. A shared database, cache or configuration service behind all cells silently restores the single blast radius you tried to remove.
  • Treating the style as permanent. Architectures should evolve with the product; record decisions and revisit them when the drivers change.

Real-World Examples#

  • Shopify keeps its core commerce platform as a large Ruby on Rails modular monolith, divided into components with boundaries checked by its open-source tool Packwerk.
  • Amazon Prime Video published a 2023 post describing how its audio and video quality monitoring tool, first built as distributed serverless components orchestrated with AWS Step Functions, was rebuilt as a single process on containers, cutting that tool's infrastructure cost by about 90 percent. The lesson concerned that workload's heavy data passing between steps, not serverless in general. More detail is in Monolith vs Microservices.
  • Netflix moved from a data-centre monolith to hundreds of services on AWS between 2008 and 2016, and built open-source tooling for service discovery, resilience and chaos testing along the way.
  • AWS publishes guidance on cell-based architecture and shuffle sharding, and uses both techniques in services such as Route 53.
  • WhatsApp ran its messaging servers on Erlang with a famously small engineering team, and Discord built its real-time messaging infrastructure on Elixir, both on the BEAM actor runtime.
  • Uber open-sourced Kraken, a peer-to-peer Docker registry, to distribute container images quickly across large clusters.
  • Meta runs XFaaS, an internal serverless platform described at SOSP 2023, processing trillions of function calls a day.

In the Interview#

Deep Dive: Coupling, the real variable behind every styleShow

Every style is a different answer to which kinds of coupling to remove, and at what price. It helps to name the kinds.

  • Temporal coupling: A and B must both be up at the same time for work to happen. Synchronous calls have it; queues and events remove it. With temporal coupling, availabilities multiply: if A depends on B, C and D synchronously, each at 99.9 percent, A's ceiling is about 99.7 percent.
  • Deployment coupling: A and B must be released together. A monolith has it by definition; microservices remove it only with backward-compatible contracts.
  • Data coupling: A reads B's tables. It is the strongest coupling, because any schema change in B can break A silently. Database per service and module-owned schemas remove it.
  • Semantic coupling: A depends on the meaning of B's data, such as "status 3 means shipped". Events and APIs do not remove this; only shared, versioned contracts and clear domain language manage it.
  • Location coupling: A must know where B runs. Service discovery, brokers and actor addresses remove it.
  • Platform coupling: A and B must use the same language or runtime. In-process modules have it; network protocols remove it.

A monolith accepts deployment and platform coupling to avoid temporal and network costs. Microservices remove deployment and data coupling, but they introduce network failure and often temporal coupling, unless they integrate asynchronously. Event-driven designs remove temporal and location coupling, but they make semantic coupling harder to see. Cells remove failure coupling between customers. Actors remove shared-memory coupling between concurrent tasks. When you compare styles, ask which couplings hurt your system most today, and pick the style that removes those, accepting the others.

Connascence. A finer-grained vocabulary from Meilir Page-Jones, popularised for architecture by Jim Weirich, describes coupling as connascence: two components are connascent if changing one requires changing the other. Weak forms are connascence of name, where both agree on a name, and of type. Strong forms are connascence of meaning, where both agree that 3 means shipped; of timing, where both must happen in order; and of value, where both must change together. The rule is to keep strong connascence inside a unit and allow only weak connascence across units, which is exactly what good service and module boundaries do.

Deep Dive: Worked numbers for comparing stylesShow

Call overhead. An in-process function call costs nanoseconds. A gRPC call between two services in the same availability zone costs roughly 0.3 to 1 ms at the median, including serialisation, and several milliseconds at the 99th percentile. A request that touches 8 services sequentially therefore spends perhaps 4 to 10 ms on the network alone at the median, and much more in the tail. The same request inside a monolith spends microseconds. This rarely matters for a 200 ms page, but it matters a great deal for a 10 ms latency budget, such as an ad auction or a game tick.

Availability composition. With synchronous dependencies in series, availability multiplies: three dependencies at 99.95 percent give about 99.85 percent. With redundancy in parallel, unavailability multiplies: two independent replicas each at 99 percent give 1 minus 0.01 squared, which is 99.99 percent. Asynchronous integration changes the question from "is the downstream service up?" to "is the queue up, and how far behind is the consumer?", which is why event-driven systems often have better user-facing availability than equivalent synchronous chains.

Blast radius with cells. With N cells and failures confined to one cell, the expected share of customers affected by a cell failure is 1 / N: 20 cells give 5 percent. If deployments go out in waves of 1, then 3, then the rest, with automatic rollback on alarms, a bad deploy usually reaches 1 cell, which is 5 percent of customers for a few minutes, instead of 100 percent.

Serverless versus containers. As computed above, at around 1.9 dollars per million 100-millisecond, 1 GB invocations, 10 million requests a month cost about 19 dollars on functions, against perhaps 30 to 70 dollars for a small always-on container pair with redundancy. At 1,000 requests per second sustained, functions cost roughly 5,000 dollars a month, while a few containers sized for that load cost a few hundred. The break-even for this shape is typically in the range of tens of requests per second sustained; above it, compute you keep running is cheaper.

Team scaling. Communication paths in a group of n people grow as n(n − 1)/2: 10 people have 45 paths, 50 people have 1,225. Splitting 50 engineers into 6 teams of about 8, each owning a module or service with a clear interface, reduces day-to-day coordination to within-team paths plus a few interfaces. This, more than any technical reason, is why architecture styles change as organisations grow.

Deep Dive: How styles evolved, and why the pendulum swingsShow

The history of architecture styles is a pendulum between centralisation for simplicity and distribution for scale and autonomy.

  • Mainframes, 1960s and 1970s: one central computer, dumb terminals. Fully centralised.
  • Client-server, 1980s and 1990s: PCs ran the interface, and database servers held the data. Two-tier, then three-tier with application servers.
  • The web and n-tier, late 1990s: browsers as universal thin clients, with web, application and database tiers. Monolithic applications on application servers.
  • SOA, 2000s: enterprises exposed services through SOAP and ESBs for reuse and integration.
  • Microservices and the cloud, 2010s: cloud infrastructure, containers and automation made running many small services feasible. Kubernetes, released by Google in 2014, standardised it.
  • Serverless, mid-2010s onward: AWS Lambda, launched in 2014, moved the unit of deployment down to a function.
  • Re-consolidation, 2020s: modular monoliths, "macroservices" and fewer, larger services, as teams recognised the costs of over-splitting, alongside cells for resilience at the very largest scales.

Each swing is a response to the costs of the previous one. Centralisation becomes a bottleneck for scale and for teams; distribution then becomes a tax on simplicity and reliability, and the pendulum swings back with better tools. The durable lessons are constant: draw boundaries around business capabilities, keep the strongest coupling inside a unit, make integration contracts explicit and versioned, and let the organisation's size and the system's quality requirements, not fashion, choose the style.

Architecture fitness functions. A practical way to keep a chosen style honest, described in "Building Evolutionary Architectures" (Neal Ford, Rebecca Parsons and Patrick Kua, 2017), is the fitness function: an automated check that measures how well the system preserves an architectural property. Examples are an architecture test that fails if Orders imports Payments' internals, a CI check that no service has more than three synchronous downstream dependencies, a latency budget test, and an alert when a cell exceeds its tested size. Fitness functions turn a style from a diagram into an enforced property.

Key Takeaways#

  • An architecture style is a named choice of how to divide a system, how the parts communicate, and how they are deployed and owned.
  • Client-server and layered designs are the base of almost every system; hexagonal architecture keeps business rules independent of infrastructure.
  • A modular monolith, one deployable unit with enforced internal boundaries, is the right default for most new products and many large ones.
  • Microservices buy independent deployment and scaling per team at the price of distributed-systems complexity; a system whose services must deploy together is a distributed monolith.
  • SOA introduced service contracts and reuse, but its central bus became a bottleneck; microservices favour smart endpoints and dumb pipes.
  • Event-driven integration decouples producers from consumers and absorbs spikes, but brings eventual consistency, idempotent consumers and schema governance.
  • Serverless removes servers and idle cost and suits spiky, event-driven work, but cold starts, limits and steady-load cost rule it out for some paths.
  • Peer-to-peer scales capacity with users and suits large-file distribution, at the cost of churn, NAT traversal and trust problems.
  • Cell-based architecture copies the whole stack per group of customers so one failure or bad deploy affects only a few percent of them.
  • The actor model gives lock-free concurrency and supervised fault isolation for millions of stateful entities, as in Erlang, Akka and Orleans.
  • Choose a style by the coupling you most need to remove, the team structure you have, and the quality attributes you must meet, and record the decision in an ADR.