Skip to content

Monolith vs Microservices

Intermediate 45 min read Part 10 of 18

When one deployable app beats many services and when it does not: costs, modular monoliths, when to split, data ownership, strangler-fig migration, real cases.

Summary#

A monolith ships the whole application as one deployable unit; microservices ship it as many small services, each owned by one team and deployed independently. Microservices buy independent deployment, scaling and failure isolation, and pay for them with network calls, distributed data and much more operational work. For most systems the best path is a modular monolith first, then extracting services only where a concrete signal justifies the cost, migrating gradually with the strangler fig pattern.

Why It Exists#

"Should this be a monolith or microservices?" is one of the most consequential and most frequently misjudged decisions in software. Both failure modes are common and expensive.

The monolith that grew too big. Imagine a 300-engineer company with one codebase. A full build and test run takes 90 minutes. Twenty teams merge into the same branch, so the release train ships everyone's changes together once a week, and a bug in one team's code rolls back everyone's work. The search feature needs 64 GB machines, so every copy of the app, including the ones serving simple profile pages, runs on 64 GB machines. An unbounded query in the reporting module exhausts the connection pool and takes down checkout. Nobody can upgrade the web framework, because it touches every team's code at once.

The microservices that came too early. Now imagine a 6-engineer startup that read about Netflix and built 25 services on day one. Each feature touches four services, so every change needs four pull requests, four deployments and a careful release order. A user's sign-up flow spans three services and sometimes half-completes, leaving an account without a profile. Debugging means correlating logs across a dozen pods. The team spends more time on Kubernetes manifests, service discovery and flaky integration tests than on the product, and the domain model, still changing weekly, keeps cutting across the service boundaries they drew too soon.

The comparison exists to avoid both outcomes. It gives you a way to match the architecture to the size of the organisation, the maturity of the domain and the real scaling needs, and a safe way to move from one to the other when those change.

How It Works#

Both architectures can deliver the same features to users. They differ in where the boundaries between features are enforced and what crosses them: function calls in one process, or network messages between processes.

The monolith: what you get and what it costs#

A monolith is one codebase built into one artefact, such as a JAR, a container image or a Rails app, and deployed as a whole. You scale it by running many identical copies behind a load balancer. The copies usually share one database.

What you get:

  • One thing to build, test, deploy and monitor. A single pipeline, one set of dashboards, one on-call rotation.
  • In-process calls. Calling the pricing code from the order code takes nanoseconds and never fails because of the network.
  • Local ACID transactions. Creating an order, decrementing stock and recording a payment intent can be one database transaction: all or nothing.
  • Easy cross-cutting changes. Renaming a field used by five features is one commit, checked by the compiler and the test suite.
  • Simple debugging. One process, one log stream, one stack trace per request.

What it costs, as it grows:

  • Coupling creeps in. Without enforced boundaries, any code can call any other code and read any table, so changes ripple unpredictably.
  • One release for everyone. Every deployment ships every team's changes, so one team's bug blocks or rolls back all others.
  • Scale as one. You cannot give the image-resizing feature more memory without giving it to every copy.
  • One failure domain. A memory leak, infinite loop or exhausted connection pool in one feature affects all features in that process.
  • One technology stack. Changing language, framework or major library version is an all-or-nothing project.

The monolith, in depth#

Monoliths scale further than their reputation suggests. Stack Overflow is a well-known example: its engineers have described for years serving one of the most visited sites on the web from a small number of servers running a largely monolithic .NET application on SQL Server. The levers are ordinary: stateless app servers behind a load balancer, aggressive caching, read replicas, careful indexing and query tuning, and later partitioning of the biggest tables. A single modern PostgreSQL or MySQL primary on good hardware handles thousands to tens of thousands of transactions per second; caching and replicas multiply read capacity many times over. Most products never exceed what this can handle.

Process roles. One codebase can still run as several roles: the same build started as web servers, background job workers, scheduled-task runners and stream consumers, each on its own pool of machines and scaled separately. This gives much of the independent scaling of services, without network calls between features, because each role still calls the code in-process. Many teams that "need microservices for scaling" really need separate worker pools.

Deployment at scale. Large monoliths stay deployable with the same tools large microservice systems use: trunk-based development, merge queues that test each change against the latest main branch, feature flags so incomplete features ship disabled, canary releases to a small percentage of hosts, and automated rollback on error-rate alarms. With these, companies have run monoliths with hundreds of engineers deploying many times a day.

Build times. The worst monolith pain is often the build. A monolith with millions of lines can still build in minutes with incremental compilation, remote build caches and test selection by dependency graph, so that a change to the Shipping module runs Shipping's tests and those of modules depending on it, not the whole suite. Build systems such as Bazel, Gradle with build caching and Nx for TypeScript provide this.

The failure domain is the hardest limit. Unlike build time or scaling, failure isolation inside one process is genuinely hard. A thread pool or connection pool is shared; a garbage-collection pause stops everything; a crash kills every in-flight request. Bulkheads, separate thread pools and connection pools per feature, plus running separate roles for risky workloads, help, but a process boundary is the only strong isolation. When one feature's failures repeatedly hurt critical paths, that is a real reason to split it out.

Microservices: the benefits#

Microservices structure the system as many small services, each built around a business capability, owned by one team, running in its own processes with its own data, and deployed independently. The benefits are real, but each one comes with a precondition.

  • Independent deployment. A team ships its service whenever it wants, without a release train. Precondition: backward-compatible APIs and no shared database, otherwise services must deploy together.
  • Independent scaling. The search service runs on 50 memory-heavy machines; the settings service runs on two small ones. Precondition: the load profiles genuinely differ.
  • Failure isolation. A crash in recommendations does not take down checkout. Precondition: callers use timeouts, circuit breakers and fallbacks, and critical paths do not depend synchronously on non-critical services.
  • Team autonomy and ownership. A team owns a service end to end, from design to production on-call, and can move fast within its boundary. Precondition: the service boundaries match the team boundaries.
  • Technology freedom. A team can use Go for a high-throughput gateway and Python for a machine-learning service. Precondition: a paved road of shared tooling, so freedom does not become chaos.
  • Smaller codebases. Each service is small enough for one team to understand fully, with fast builds and tests.
  • Easier replacement. A well-bounded service can be rewritten without touching the rest.

Microservices benefits, in depth#

The real benefit is organisational. Almost every technical benefit of microservices, such as scaling, isolation and fast builds, can be approximated inside a monolith with roles, bulkheads and build caching. The benefit that cannot be approximated is removing coordination between teams. When 30 teams share one deployable unit, every team's release depends on all 29 others. When each team owns its own deployable unit with a stable contract, each team's release depends only on itself. That is why microservices pay off with organisational scale and rarely before.

DORA metrics as evidence. The DevOps Research and Assessment program, summarised in "Accelerate" (Nicole Forsgren, Jez Humble and Gene Kim, 2018), found that loosely coupled architectures, where teams can test and deploy their part independently, correlate strongly with high deployment frequency, short lead times and low change-failure rates. Notably, the finding is about loose coupling, not about microservices as such: a well-modularised monolith with independent testability shows similar effects, and a distributed monolith does not.

Scaling precision. Suppose image processing needs 8 CPU cores and 16 GB per instance and handles 200 requests per second per instance, while the rest of the app needs 2 cores and 4 GB and handles 2,000 requests per second per instance. At peak you need 20 image instances and 5 app instances. As one monolith, every instance must be the large size, so 25 large instances. Split, you run 20 large and 5 small instances. The saving is real, but here it amounts to five machines; it matters only when the disparity and the scale are both large, which is why separate worker roles often achieve the same result.

The costs of microservices#

Martin Fowler called the extra cost the microservice premium ("MicroservicePremium", 2015): a fixed overhead you pay before you get any benefit, which only becomes worthwhile above a certain level of complexity. The premium includes:

  • Network unreliability. Every call between services can be slow, fail, time out, or succeed without the caller knowing. You need timeouts, retries with backoff, idempotency and circuit breakers on every call.
  • Latency. Each hop adds roughly 0.5 to 2 ms within a data centre, plus serialisation. Deep synchronous call chains also multiply tail latency.
  • Distributed data. No joins across services and no ACID transactions across services. Consistency across services is eventual, through sagas and events.
  • Operational load. Dozens or hundreds of deployable units, each needing a CI/CD pipeline, monitoring, alerting, logging, scaling rules, security patches and on-call ownership.
  • Infrastructure. Service discovery, an API gateway, often a service mesh, centralised logging, distributed tracing, secrets management and container orchestration.
  • Testing. End-to-end tests across many services are slow and flaky, so you need contract tests and good staging environments.
  • Harder refactoring. Moving a responsibility between services is a cross-team API migration, not a commit.
  • Versioning. Every API change must be backward compatible, or coordinated across consumers.

The costs of microservices, in depth#

The availability arithmetic. If a page needs five services synchronously and each is available 99.9 percent of the time, the page is available at most about 99.5 percent of the time: roughly 3.6 hours of failures a month instead of 43 minutes. Each additional required dependency lowers the ceiling. The remedies are to keep critical paths shallow, call non-critical services asynchronously or with fallbacks, and cache the data you need from other services.

Fallacies of distributed computing. The list attributed to L. Peter Deutsch and colleagues at Sun Microsystems in the 1990s, that the network is reliable, latency is zero, bandwidth is infinite, the network is secure, topology does not change, there is one administrator, transport cost is zero and the network is homogeneous, reads like a checklist of microservice incidents. Every one of them becomes your problem the moment a function call becomes a network call. See Distributed Systems Fundamentals.

The distributed monolith. The worst outcome is a system that has the costs of microservices and the coupling of a monolith. Symptoms:

  • services must be deployed together or in a specific order;
  • several services read or write the same tables;
  • a change to one feature requires changes in many services;
  • a shared library containing domain models forces simultaneous upgrades;
  • long synchronous call chains, A calls B calls C calls D, so latency adds up and one failure cascades;
  • teams spend most of their time in cross-team coordination meetings.

A distributed monolith is usually the result of splitting along the wrong boundaries, often by technical layer or by data entity rather than by business capability, or of splitting before the domain was understood.

Testing costs. In a monolith, an integration test runs the real code paths in one process. In microservices, an equivalent test needs every dependency running, at compatible versions, with test data in every database. Such suites become slow and flaky. Teams instead use a test pyramid adapted for services: many unit tests, component tests of one service with its dependencies stubbed, consumer-driven contract tests, such as those written with Pact, where each consumer publishes the exact requests and responses it relies on and the provider's build verifies them, and only a few end-to-end smoke tests in staging. Production practices, such as canary releases and feature flags, then catch what tests miss.

The headcount cost. A rule of thumb used by several platform teams is that a mature microservice platform needs a dedicated platform or infrastructure team, often 10 to 20 percent of engineering, to build and run the paved road: deployment pipelines, service templates, observability, the mesh and the gateway. For a 15-engineer company, that is two or three engineers not building product, which is often the deciding argument against microservices at small scale.

The modular monolith as the default#

A modular monolith is one deployable application whose code is divided into modules with enforced boundaries. Each module corresponds to a business capability, such as Catalogue, Orders, Payments or Shipping. Each one:

  • exposes a small public API, a set of functions, service classes or commands and queries, and hides everything else;
  • owns its own data: its own tables in its own schema, which no other module queries directly;
  • talks to other modules only through their public APIs or through in-process domain events;
  • has one owning team, recorded in a code-ownership file.

This gives most of the benefits that matter early, namely clear ownership, contained changes, understandable code and cheap refactoring, with none of the network or distributed-data costs. It also keeps the door open: a module with a clean API and its own schema can later be extracted into a service by replacing in-process calls with network calls.

Modular monolith, in depth#

Why it is the default. Three arguments make the modular monolith the right starting point for most products.

  1. Boundaries are easiest to get right late. Early on, the domain is still being discovered. Moving a responsibility between modules is a refactor; moving it between services is a migration. Martin Fowler's "MonolithFirst" (2015) observed that almost all successful microservice stories he had heard started with a monolith that grew too big, and that systems built as microservices from scratch often ended in trouble.
  2. The premium is paid only when it buys something. You extract a service when a specific module needs independent deployment, scaling or isolation, so each extraction has a measurable payoff.
  3. Most of the organisational benefit is available. With module ownership, boundary enforcement and test selection, teams of up to a few hundred engineers can work in one codebase, as Shopify and others have shown.

Enforcing the module boundaries. Boundaries decay unless a machine checks them. Use language features, such as Java modules, C# assemblies with internal types, or Go's internal/ directories; build-tool rules, such as Gradle modules, Bazel visibility or Nx module-boundary lint rules; architecture tests, such as ArchUnit rules that only a module's api package may be imported from outside; and database separation, with one schema and one database role per module, so that cross-module SQL fails with a permission error.

Communication inside the monolith. Modules call each other through public interfaces, synchronously, for queries and commands that need an immediate answer. For reactions, use in-process domain events: Orders publishes OrderPlaced on an in-process bus, and Shipping and Notifications handle it. If the handlers must run reliably even if the process crashes, write the event to an outbox table in the same transaction and process it asynchronously. That is the same pattern a service would use, so extraction later is easier. See Change Data Capture and the Outbox Pattern.

Transactions across modules. Because all modules share one database server, a use case can still span modules in one ACID transaction. This is a convenience, and also a trap: every cross-module transaction is a coupling that must be replaced by a saga if either module is extracted. A good discipline is to make cross-module transactions explicit and rare, so you know exactly what extraction would cost.

When the modular monolith stops being enough. Signals that a module should leave:

  • it needs a different deployment cadence and its releases are blocked by, or block, others;
  • it has a very different resource profile, such as GPUs, huge memory or extreme bursts, and separate roles have not been enough;
  • its failures keep hurting critical paths despite bulkheads;
  • it needs a different technology, such as a different language runtime;
  • it has strict compliance isolation requirements, such as card data in a PCI-scoped environment;
  • the organisation has grown so that many teams contend on one deployment pipeline.

When to split#

Split a part of the system into a separate service when a specific, measurable pain points to it, and the expected gain exceeds the microservice premium. The question is never "monolith or microservices?" for the whole system, but "should this module be a service now?"

Strong signals to extract a service:

  • Team contention: more than a few teams, typically above roughly 30 to 50 engineers on one deployable, regularly blocked by each other's releases.
  • Divergent scaling: one part needs an order of magnitude more capacity, or very different hardware, than the rest.
  • Divergent reliability: one part must stay up when others fail, such as checkout versus recommendations, or one part is risky and should not take others down.
  • Divergent change rate: one area changes many times a day while the rest is stable.
  • Compliance or security isolation: payments, personal data or secrets that must live in a separate, audited environment.
  • A clean, stable boundary already exists: the module has a narrow API, owns its data, and has had few cross-boundary changes in recent months.

Weak or false signals:

  • "Microservices are modern" or "big companies use them".
  • "The code is a mess": a messy monolith becomes a messy distributed system; fix the modularity first.
  • "We want to use a new language": possible, but rarely enough on its own.
  • "It will scale better": usually solved more cheaply by caching, replicas, worker roles or database tuning.

When to split, in depth#

Which module to extract first. Good first candidates are modules that are loosely coupled to the rest, valuable to separate and low risk. Examples are notification sending, image or video processing, search indexing and PDF generation: they are mostly downstream consumers with narrow interfaces, easy to drive asynchronously, and a failure in them rarely corrupts core data. Poor first candidates are the core of the domain, such as orders or accounts, which everything depends on and which participate in many transactions. Extracting an edge module first also builds the platform, the pipelines, observability and the on-call practice, at low risk before you need it for critical services.

Measuring coupling before you split. Version-control history is a cheap coupling detector. If files in the Orders module and files in the Inventory module change in the same commit 40 percent of the time, splitting them into separate services would turn 40 percent of changes into cross-service changes. Tools for "change coupling" or "temporal coupling" analysis compute this from the git log. Likewise, count cross-module calls and cross-module transactions: a module with dozens of synchronous inbound calls per request is a poor candidate.

Granularity. After deciding to split, the next mistake is splitting too finely. A useful default is one service per team, or a few, rather than many services per team. Uber's engineering team described in 2020 how, after growing to around 2,200 critical microservices, it introduced Domain-Oriented Microservice Architecture (DOMA), grouping related services into domains behind gateway interfaces, to reduce the complexity of thousands of fine-grained services. Larger, coarser services, sometimes called macroservices, are often the better trade.

Moving back. Merging services back is a legitimate decision. Segment's engineering team described in 2018 ("Goodbye Microservices: From 100s of problem children to 1 superstar") how it had split each integration destination into its own service and queue, found that the operational overhead and shared-library drift across more than a hundred services overwhelmed a small team, and consolidated them into one service with better test infrastructure. The lesson is the same as for splitting: architecture follows the team's size and needs, in both directions.

Decomposition by business capability#

A business capability is something the business does to create value, described in business terms rather than technical ones: "manage the product catalogue", "take orders", "process payments", "fulfil and ship", "manage customer accounts", "recommend products". Capabilities are stable: an online retailer has had catalogue, ordering, payment and shipping capabilities for decades, even as its software changed many times.

Decomposition by business capability makes each module or service correspond to one capability. That gives three properties:

  • High cohesion: all the code and data for one business concept, such as pricing rules, lives in one place, so most changes touch one service.
  • Stable boundaries: because capabilities change slowly, the boundaries rarely need to move.
  • Natural ownership: a team can own a capability, with a product manager, domain experts and engineers aligned to it.

Decomposition by business capability, in depth#

Alternatives, and why they fail. Several other ways of splitting are common and usually worse.

  • By technical layer: a "front-end service", a "business logic service" and a "data service". Every feature still crosses all three, so nothing is independent, and every request pays extra network hops.
  • By data entity, or noun: a "Customer service", an "Order service" and a "Product service", each a thin create-read-update-delete wrapper over one table. Business rules that involve several entities, such as "a gold customer gets free shipping on orders over 50 dollars", end up scattered or in an orchestration layer that calls everything, and the entity services become shared dependencies of everything.
  • By verb or use case: a "PlaceOrder service" and a "CancelOrder service". These share the same data and rules, so they are tightly coupled.
  • By current org chart alone: if the teams were formed around projects or technologies, the services inherit those arbitrary boundaries.

Subdomains and bounded contexts. Domain-driven design refines capability decomposition. It distinguishes the core subdomain, which gives competitive advantage, such as matching riders and drivers for a ride-hailing app; supporting subdomains, which are necessary but not differentiating; and generic subdomains, such as authentication or email, which you should buy or reuse. Each subdomain is modelled in a bounded context, an area where words have one precise meaning. "Product" means a sellable item with a price in Catalogue, and a physical item with weight and dimensions in Fulfilment; forcing one shared Product model on both creates coupling. Service boundaries usually follow bounded contexts. See Domain-Driven Design for Service Boundaries.

Testing a boundary. A candidate boundary is good if:

  • most user-facing changes, judged from the last few months of feature requests, would touch one side only;
  • the two sides can agree on a narrow interface, a handful of commands, queries and events;
  • each side can own its data without needing the other's tables for most operations;
  • operations that must be atomic, meaning invariants that must hold at every moment such as "stock never goes negative", fall on one side;
  • one team can own it.

Invariants decide the boundary. The most useful single rule is to keep each strong invariant inside one service. If "the account balance must never go below zero" requires checking balance and writing the debit atomically, the balance and the debits belong to the same service, the same aggregate, in the language of domain-driven design. Rules that can tolerate being temporarily violated and corrected, such as "loyalty points reflect purchases", can span services through events.

Database per service#

Database per service means each service owns its data privately. Only the owning service reads and writes its tables; every other service accesses that data only through the owner's API or by consuming its events. Ownership can be implemented at different strengths:

  • Private tables in a shared database server, protected by convention and permissions.
  • Schema per service on a shared server, with a separate database user per service.
  • Database server per service, which also gives performance isolation, so one service's heavy queries cannot slow another's.
  • A different database technology per service where it fits, such as PostgreSQL for orders, Elasticsearch for search, Redis for carts and Cassandra for activity feeds. This is called polyglot persistence.

Why it matters: a shared database is the strongest form of coupling. If the Shipping service reads the Orders table directly, the Orders team can no longer rename a column, split a table or change a status code without breaking Shipping, so the two services must be changed and deployed together, which defeats the purpose of splitting them. Shared databases also couple performance, since one service's slow query locks rows or saturates I/O for another, and availability, since a database failure takes down every service that uses it.

The price is that joins and transactions across services are gone, so cross-service queries and cross-service writes need patterns.

Database per service, in depth#

Querying across services. Two patterns cover nearly every case.

  • API composition: a composer, which may be an API gateway, a backend-for-frontend or the calling service, calls each owning service and merges the results in memory. It is simple and always current, but latency is that of the slowest call, availability is the product of all of them, and large joins, such as "all orders over 100 dollars by customers in France", are impractical because they require fetching and filtering large sets in memory.
  • Replicated read models, or CQRS views: a service subscribes to other services' events and maintains its own denormalised copy of the data it needs to query, such as an order-history table that includes customer name and shipping status. Queries are fast and local, and work even when the source services are down. The cost is eventual consistency: the view lags the source by milliseconds to seconds, and you must handle duplicate and out-of-order events. See Event Sourcing and CQRS.

Writing across services. A business operation that changes data in several services, such as placing an order which reserves stock and charges a card, cannot use one ACID transaction. Options:

  • Saga: a sequence of local transactions, one per service, where each step publishes an event or reply that triggers the next, and a failure triggers compensating transactions that undo earlier steps semantically, such as releasing the reserved stock or refunding the charge. Sagas can be choreographed, with services reacting to each other's events, or orchestrated, with a coordinator telling each service what to do.
  • Transactional outbox: to update the database and publish the event without the dual-write problem, the service writes the event to an outbox table in the same local transaction, and a relay or change data capture publishes it.
  • Two-phase commit across services is technically possible but rarely used, because it couples availability and holds locks across the network. See Distributed Transactions: 2PC, Sagas and Outbox.

Reference data. Some data is needed by many services but owned by one, such as product names, currencies or country lists. Instead of every service calling the owner on every request, owners publish changes as events and consumers keep a local cache or replica, accepting slight staleness. For data that must be exact at the moment of a transaction, such as a price, the consuming service copies it into its own record when the transaction happens: an order stores the price at the time of purchase rather than referencing the catalogue's current price. This is not only a technical convenience; it is usually the correct business behaviour.

Reporting and analytics. Business reports often need joins across every service's data. Do not satisfy them by querying service databases directly, which recreates the shared-database coupling. Instead, stream every service's changes, using change data capture or published events, into a data warehouse or lake, where analysts can join freely. See Data Pipelines, Warehouses and Lakes.

Splitting a shared database, step by step. When extracting a service from a monolith, the data is the hardest part. A common sequence:

  1. Identify the tables the new service will own, and every place in the monolith that reads or writes them.
  2. Route all access through one module inside the monolith, so that only that module's code touches those tables. This alone often takes most of the effort.
  3. Remove cross-module joins and foreign keys involving those tables, replacing them with API calls or denormalised copies.
  4. Move the tables to a separate schema, then to a separate database, synchronised during the transition, often with change data capture from the old tables to the new ones.
  5. Switch reads, then writes, to the new service, behind a feature flag, with verification by comparing results.
  6. Drop the old tables when nothing reads them, after a safety period.

Migration with the strangler fig#

The strangler fig pattern, named by Martin Fowler in 2004 after the tropical figs that grow around a host tree until they replace it, migrates a system incrementally. Instead of rewriting the monolith in one "big bang", you put a routing layer in front of it, build new functionality, or extract existing functionality, as separate services, and shift traffic one capability at a time, until the old system handles nothing and can be removed.

The steps:

  1. Insert a facade. Put a proxy, API gateway or load balancer in front of the monolith. At first it routes 100 percent of traffic to the monolith, which changes nothing and proves the facade is safe.
  2. Pick a capability to move, ideally a loosely coupled one with clear value, such as notifications or search.
  3. Build the new service, either new code or code extracted from the monolith, with its own data.
  4. Synchronise data between the old and new stores while both are live, usually with change data capture from the monolith's tables or by having the monolith publish events.
  5. Shift traffic gradually: shadow traffic first, where the new service receives a copy of requests and its results are compared but not used; then a small percentage of real users; then all.
  6. Remove the old code path from the monolith once the new service has run all traffic safely for a while.
  7. Repeat for the next capability.

Because each step is small and reversible, the business keeps running, value is delivered continuously, and a failed step is rolled back by flipping the route back. Big-bang rewrites, by contrast, freeze feature work for months or years, have to chase a moving target as the old system keeps changing, and often fail outright.

Strangler fig, in depth#

Routing techniques. The facade can route by URL path, such as /search going to the new service; by HTTP method, for example sending reads to the new service before writes; by user or tenant, sending internal staff first and then 1, 10, 50 and 100 percent of customers; or by header or feature flag. Routing by a stable hash of the user ID keeps each user consistently on one side, which avoids confusing behaviour when the two implementations differ slightly.

Intercepting inside the monolith. Not every capability is reachable at the edge. When an internal function needs to move, such as tax calculation called from deep inside checkout, use branch by abstraction: introduce an interface inside the monolith in front of the existing implementation, make all callers use the interface, add a second implementation that calls the new service, and switch between them with a feature flag. Once the new implementation is proven, delete the old one and the flag. Event interception is a third option: if the monolith publishes events, or you capture its database changes, a new service can react to them without the monolith changing at all.

Data during the migration. The data synchronisation strategy decides whether migration is safe:

  • Dual writes from application code, where the monolith writes to both the old and new stores, are simple but unsafe: if one write succeeds and the other fails, the stores diverge silently.
  • Change data capture from the old database is safer: a connector, such as Debezium reading the MySQL binlog or the PostgreSQL write-ahead log, streams every committed change into the new service's store in commit order, so the new store is a reliable replica.
  • Backfill then stream for existing data: take a consistent snapshot of the old tables, load it into the new store, then apply the change stream from the snapshot's log position onward, so nothing is missed or applied twice.

Zero-downtime cutover with change data capture. For moving writes, the usual sequence is:

  1. Snapshot and backfill the new store; start streaming changes from the old store to the new one.
  2. Verify: compare row counts and checksums, and run shadow reads that query both stores and log mismatches, until mismatches are near zero.
  3. Move reads to the new store, keeping writes on the old one, with replication lag monitored to be within a second or so.
  4. Move writes: either pause writes for a few seconds, wait for the stream to drain, and flip the write target; or, for no pause at all, make the new service the writer and reverse the replication direction so the old store keeps receiving changes as a fallback.
  5. Keep reverse replication running for a safety period, so you can roll back without data loss.
  6. Decommission the old tables.

See Online Data Migrations and Schema Evolution and Change Data Capture and the Outbox Pattern.

Verification with shadow traffic. For read paths, send each request to both implementations, return the old result to the user, and compare the two results asynchronously, logging differences. GitHub open-sourced Scientist, a Ruby library for this kind of experiment, in 2016. It runs the old and new code paths side by side and records mismatches and timing. Teams typically aim for a mismatch rate close to zero before switching, and investigate every class of difference, since some differences reveal bugs in the old system rather than the new.

Avoiding a half-strangled system. The common failure of strangler migrations is stopping halfway: the easy capabilities are extracted, the hard core remains in the monolith, and the organisation now runs both a monolith and services indefinitely. That can be fine if it was intended, but it should be a decision rather than an accident. Set explicit end states, track how much traffic and code remain in the old path, and budget for the hard parts, especially the data, up front.

Real examples: Amazon Prime Video and Shopify#

Two widely discussed cases show that the right answer depends on the workload and the organisation, not on fashion.

Amazon Prime Video's monitoring service. In 2023 the Prime Video technology blog published "Scaling up the Prime Video audio/video monitoring service and reducing costs by 90%". The service checks the quality of video streams that customers watch, looking for defects such as frozen frames, block corruption and audio-video synchronisation problems.

  • The original design was distributed and serverless: a media conversion step split each stream into video frames and audio buffers, stored them in Amazon S3, and a set of detector functions, coordinated by AWS Step Functions, read them and ran checks.
  • The problems: the orchestration performed many state transitions for every second of every stream, which was expensive and hit account limits, and passing large intermediate frames through S3 meant a very large number of storage requests. The post reported that the design hit a hard scaling limit at around 5 percent of the expected load.
  • The redesign moved all components into a single process, running in containers on Amazon ECS, with frames passed in memory between the conversion step and the detectors. To scale further, they ran multiple instances and split detectors across them.
  • The result, as reported: infrastructure costs for this tool fell by over 90 percent, and it could scale to monitor many more streams.

The lesson is precise. The workload moved huge volumes of data between tightly coupled steps at high frequency, which is the worst case for network hops and per-transition billing. It is not evidence that microservices or serverless are wrong in general; the same team runs many services, and the redesigned monitor is itself one service among them. It is evidence that components exchanging large data at high frequency belong in one process.

Shopify's modular monolith. Shopify runs one of the largest Ruby on Rails applications in the world, its core commerce platform. Rather than splitting it into microservices, Shopify's engineers described in a series of posts starting with "Deconstructing the Monolith" (2019) how they restructured the codebase into components, each corresponding to a business domain such as checkout, orders, shipping or billing, with:

  • a clear owner for every component;
  • a defined public interface per component, with internal code private;
  • dependency rules between components, made visible and enforced with Packwerk, a static analysis tool they open-sourced in 2020 that reports privacy and dependency violations, so the number of violations could be tracked and driven down over time.

Shopify kept the advantages of one codebase, such as one deployment, in-process calls and easy cross-cutting refactors, while gaining ownership and contained changes. It does run separate services where they make sense, for example for specific infrastructure and high-throughput needs, but the core stays a modular monolith. The lesson: modularity, not distribution, is what large teams need first, and boundaries can be strong without a network between them.

Real examples, in depth#

Why the Prime Video post generated so much debate. Many readers took it as "Amazon abandons microservices". The post itself described re-architecting one tool, and the essential factor was the data gravity of the workload: video frames are large, the checks run on every frame, and moving every frame through object storage and an orchestration step costs far more than moving it through memory. A useful general rule follows: if two components exchange more data than they compute on, they probably belong together.

What Shopify's approach required. A modular monolith at Shopify's scale depends on investments that are not free: tooling for boundary enforcement, ownership metadata, test selection for a very large test suite, and a deployment pipeline that can ship a huge codebase many times a day. Those are the same kinds of platform investments microservices need, aimed at a single codebase instead. The choice was not between investment and no investment, but between which coupling problems to solve with which tools.

Other cases worth knowing. Netflix moved from a monolith to services on AWS over about seven years, from 2008 to 2016, driven by reliability and the scale of its engineering organisation, and built much of the open-source tooling that later became standard. Segment moved in the opposite direction for one subsystem, consolidating more than a hundred per-destination services into one. Uber regrouped thousands of fine-grained services into domains. Each case matched the architecture to the team size, the workload's data flows and the operational capacity available.

Microservices best practices#

If you do run microservices, the practices that consistently separate healthy systems from painful ones are:

  1. Design around business capabilities, one team owning each service end to end, including production on-call: "you build it, you run it".
  2. Own your data: a private datastore per service, no shared tables, and integration through APIs and events only.
  3. Keep services independently deployable: backward-compatible API changes, versioned contracts, consumer-driven contract tests, and no lock-step releases.
  4. Prefer asynchronous communication for anything that does not need an immediate answer, so a downstream outage queues work instead of failing it.
  5. Make every remote call resilient: timeouts on every call, retries with exponential backoff and jitter only for idempotent operations, circuit breakers, bulkheads and fallbacks.
  6. Make every operation idempotent where it can be retried, using idempotency keys, so at-least-once delivery and client retries are safe. See Idempotency and Safe Retries.
  7. Automate everything: a CI/CD pipeline per service, infrastructure as code, and standard service templates, the paved road, so creating a new service is cheap and consistent.
  8. Build observability in: structured logs with correlation IDs, standard metrics such as request rate, errors and duration, and distributed tracing across every hop.
  9. Secure service-to-service traffic: mutual TLS between services, authentication at the gateway, and least-privilege authorisation per service.
  10. Containerise and orchestrate: package services as containers and run them on a scheduler such as Kubernetes, with health checks, autoscaling and rolling deployments.
  11. Keep the call graph shallow: avoid long synchronous chains, and design each service to answer most requests with its own data.
  12. Document and own APIs: an API specification, such as OpenAPI or Protobuf, published per service, with clear deprecation policies.

Microservices best practices, in depth#

The essential components of a production microservice system. Every serious microservice deployment converges on roughly the same supporting pieces:

  • An API gateway at the edge, handling authentication, rate limiting, TLS termination and routing to services. See API Gateway and Backend-for-Frontend.
  • Service discovery, a registry such as Consul, etcd or Kubernetes' own DNS, so services find each other's current instances.
  • Load balancing between instances, client-side or through a proxy.
  • A message broker, such as Kafka, RabbitMQ or a cloud queue, for asynchronous communication and events.
  • Configuration and secrets management, such as Kubernetes ConfigMaps and Secrets or HashiCorp Vault, so configuration lives outside the code.
  • Observability: centralised logs, metrics with dashboards and alerts, and distributed tracing, such as OpenTelemetry exporting to Jaeger or a commercial backend.
  • A container platform and CI/CD per service.
  • Often a service mesh, such as Istio or Linkerd, which moves retries, timeouts, mutual TLS and traffic shifting into sidecar or node proxies.

The details of each are in Microservices Infrastructure Patterns.

API evolution without lock-step releases. The rule that keeps services independent is never break a consumer. In practice: add fields, never remove or rename them in place; make new fields optional; accept unknown fields; version only when a breaking change is unavoidable, running the old and new versions side by side until consumers migrate; and track consumers so you know who to notify. Protobuf and Avro schemas make compatibility rules checkable in CI; a schema registry can reject incompatible event schemas before they are published.

Chatty services are a design smell. If rendering one page requires 30 calls between services, the boundaries are probably wrong, or the services need read models. A useful budget is that a user-facing request should touch at most a few services synchronously. Measure fan-out with tracing, and treat growth in call depth as a regression.

Paved roads. Netflix and others popularised the idea of a paved road: a supported, default way to build a service, including a template, libraries for resilience and telemetry, a deployment pipeline and dashboards, which teams may leave but rarely want to. It turns the microservice premium from a per-team cost into a shared platform cost, which is the only way the premium stays affordable as the number of services grows.

When to Use It#

Use a monolith, made modular, when:

  • the engineering team is up to roughly a few dozen engineers, or a few teams;
  • the product or domain is new, and boundaries are still moving;
  • most features cut across what would be service boundaries;
  • you lack a platform team or the operational maturity for many services;
  • strong consistency across features matters and is easy with one database;
  • traffic fits comfortably on a horizontally scaled app plus a well-tuned database, which covers the vast majority of products.

Use microservices, extracted gradually, when:

  • many teams, roughly above 30 to 50 engineers on one deployable, are blocked by each other's releases or builds;
  • parts of the system have very different scaling, hardware or availability requirements;
  • some capabilities must be isolated for compliance or security;
  • the domain is well understood, with stable boundaries;
  • you have, or will build, a platform: CI/CD, observability, service templates and on-call practices.

When NOT to Use It#

  • Do not start a new product with microservices unless you have a strong, specific reason, such as an existing platform and teams already organised by capability.
  • Do not split to fix messy code. Modularise inside the monolith first; a messy monolith becomes a messier distributed system.
  • Do not split tightly coupled components that exchange large amounts of data at high frequency, as the Prime Video monitoring case showed.
  • Do not split along technical layers or database tables; split along business capabilities.
  • Do not split without data ownership. Services that share tables are a distributed monolith.
  • Do not do a big-bang rewrite of a working monolith into services; migrate incrementally with the strangler fig.
  • Do not keep a monolith whose team contention, scaling divergence or failure coupling is measurably hurting the business just because migration is hard; plan an incremental extraction.

How to Implement It#

A practical path from monolith to the right mix of monolith and services:

  1. Measure the pain. Collect deployment frequency, lead time, build time, incident causes and team wait times. Identify which modules cause which pain.
  2. Map capabilities and ownership. Draw the business capabilities, assign an owning team to each, and record ownership in the code.
  3. Modularise in place. Create modules per capability with public APIs, move code behind them, give each module its own schema, and enforce boundaries automatically.
  4. Remove cross-module data coupling. Replace cross-module joins and foreign keys with API calls, events or local copies; make remaining cross-module transactions explicit.
  5. Build the paved road. CI/CD templates, observability, service discovery, a gateway and on-call practices, before the first critical extraction.
  6. Extract the first, low-risk service with the strangler fig: facade, new service, data sync through change data capture, shadow traffic, gradual cutover, removal of old code.
  7. Repeat only where signals justify it. Each extraction should address a measured pain; stop when the remaining monolith is not causing problems.
  8. Review regularly. Track coupling metrics, such as cross-service changes per feature, synchronous fan-out and lock-step deploys, and merge services back if they are too fine-grained.

A strangler-fig routing layer can be as simple as a reverse proxy. Here, NGINX sends search and 10 percent of order reads to new services and everything else to the monolith:

upstream monolith   { server monolith.internal:8080; }
upstream search_svc { server search.internal:8080; }
upstream orders_svc { server orders.internal:8080; }
 
# Stable 10 percent of users, by user ID cookie, go to the new orders service
split_clients "${cookie_uid}" $orders_backend {
    10%   orders_svc;
    *     monolith;
}
 
server {
    listen 80;
 
    location /api/search/ {           # fully migrated
        proxy_pass http://search_svc;
    }
 
    location ~ ^/api/orders/ {        # reads being migrated gradually
        if ($request_method != GET) { proxy_pass http://monolith; }
        proxy_pass http://$orders_backend;
    }
 
    location / {                      # everything not yet migrated
        proxy_pass http://monolith;
    }
}
TechnologyFits when
Rails, Django, Spring Boot, ASP.NET Core, LaravelBuilding the monolith or modular monolith
Packwerk, ArchUnit, Nx module boundaries, Java modules, Go internal packagesEnforcing module boundaries inside one codebase
NGINX, Envoy, Kong, AWS API Gateway, cloud load balancersThe routing facade for strangler-fig migration
Debezium with Kafka, AWS DMSStreaming data from monolith tables to new services during migration
GitHub Scientist and similar experiment librariesComparing old and new code paths before cutover
LaunchDarkly, Unleash, OpenFeatureFeature flags for branch by abstraction and gradual rollout
Kubernetes, Amazon ECS, NomadRunning many services on a common platform
PactConsumer-driven contract tests between services
OpenTelemetry, Jaeger, Grafana, DatadogTracing and monitoring across services
Temporal, AWS Step FunctionsOrchestrated sagas across services

Trade-offs#

OptionProsConsPick when
Unstructured monolithFastest to start; simplest operationsCoupling grows unchecked; hard to scale teamsPrototypes and very small teams, short term
Modular monolithOne deploy and database; strong boundaries; cheap refactoringShared failure domain and release train; needs toolingDefault for most products, up to large teams
Monolith plus a few extracted servicesPay the premium only where it buys somethingTwo operating models to supportSpecific modules with clear scaling, isolation or cadence needs
Coarse services, one per teamTeam autonomy with modest operational costSome cross-service coordinationMedium to large organisations with stable domains
Fine-grained microservicesMaximum independence and scaling precisionHigh operational cost; chatty calls; distributed dataVery large organisations with a strong platform
Big-bang rewriteClean slateHigh risk, frozen features, moving targetAlmost never; only for small systems or forced platform changes
Strangler-fig migrationIncremental, reversible, continuous deliveryRuns two systems for a long timeMigrating any live system of significant size

Common Pitfalls#

  • Starting with microservices before the domain or team structure justifies them, and paying the premium for years.
  • The distributed monolith: shared databases, lock-step deployments, shared domain libraries and long synchronous chains.
  • Splitting by entity or layer, creating thin CRUD services that every feature must coordinate.
  • Ignoring data ownership during extraction, leaving the new service reading the monolith's tables "temporarily", which becomes permanent.
  • Dual writes during migration, silently diverging data; use change data capture or an outbox instead.
  • No platform: each team building its own pipelines, logging and resilience code, inconsistently.
  • Big-bang rewrites that freeze the product and fail to catch up with the old system.
  • Stopping halfway by accident, leaving a permanent hybrid nobody planned for.
  • Too many services per team, so engineers spend more time on deployment and dependency upgrades than on features.
  • Treating the decision as one-way; merging services back is sometimes the right move.

Real-World Examples#

  • Amazon Prime Video reported cutting the infrastructure cost of its audio and video quality monitoring tool by over 90 percent by moving it from distributed serverless components to a single process on containers, because its steps exchanged large data at high frequency.
  • Shopify keeps its core commerce platform as a modular Rails monolith, divided into owned components with boundaries enforced by its open-source tool Packwerk.
  • Netflix migrated from a data-centre monolith to services on AWS between 2008 and 2016, after a database corruption that halted DVD shipping for days, and built widely used open-source resilience and discovery tooling along the way.
  • Segment consolidated more than a hundred per-destination microservices back into a single service in 2018, citing operational overhead for a small team.
  • Uber introduced Domain-Oriented Microservice Architecture in 2020 to group roughly 2,200 critical microservices into domains with gateways, reducing the complexity of a very fine-grained system.
  • Stack Overflow has long been cited for serving very high traffic from a largely monolithic application on a small number of servers.

In the Interview#

Deep Dive: A cost model for the microservice premiumShow

It helps to think of the decision as a cost curve rather than a debate.

Fixed costs per service. Each service needs a repository, pipeline, deployment configuration, dashboards, alerts, on-call ownership, dependency upgrades, security patches and API documentation. Even with a good paved road, estimates from platform teams commonly put this in the range of a few engineer-days per service per quarter. With 10 services that is manageable; with 300 services it is a substantial share of engineering time, which is why fine-grained architectures need heavy automation.

Coordination costs that services remove. In a shared deployable with T teams, each release potentially conflicts with the work of all other teams. Merge conflicts, broken builds and release rollbacks grow roughly with the number of teams and the rate of change. If each of 20 teams loses one engineer-day a week to release coordination, broken main branches and rollbacks caused by others, that is 20 engineer-days a week, about four full-time engineers. Splitting into independently deployable units removes most of it, but only if the units are truly independent.

Runtime costs. Network calls add serialisation CPU, often several percent of fleet CPU in service-heavy systems, plus proxies if you use a mesh, which adds its own CPU and memory per instance or per node. Each service also needs its own headroom, because small services cannot share spare capacity as effectively as one large pool, so total utilisation is typically lower than for one big fleet.

The break-even. Plot coordination cost, which rises with team count in a shared deployable, against the microservice premium, which is roughly fixed per service and grows with service count. For a handful of teams, coordination cost is low and the premium dominates, so the monolith wins. For dozens of teams, coordination cost dominates, so independent services win, provided the boundaries are right. The modular monolith shifts the curve, delaying the crossover, because module ownership and test selection reduce coordination costs without paying the premium. This is the quantitative intuition behind "monolith first".

Deep Dive: Detecting and fixing a distributed monolithShow

Detection metrics.

  • Co-deployment rate: the share of releases that require deploying more than one service together. Healthy systems are near zero.
  • Change coupling: from version control, how often commits or pull requests for one feature touch several services. If most features touch three or more services, boundaries are wrong.
  • Synchronous fan-out and depth: from tracing, how many services a typical request touches and how deep the chain is. Depth above three or four on critical paths is a warning sign.
  • Shared data access: any service reading another service's tables, found through database audit logs or connection users.
  • Shared libraries with domain models: libraries that every service must upgrade together.
  • Incident correlation: incidents where one service's failure took down others.

Fixes, in order of cost.

  1. Break synchronous chains with caching, local read models fed by events, and asynchronous commands, so a service can answer from its own data.
  2. Remove shared tables by assigning each table one owner and replacing other access with APIs or events.
  3. Replace shared domain libraries with published contracts, such as API schemas and event schemas, and let each service own its internal models.
  4. Merge services that always change together into one; this is often the cheapest fix and is underused.
  5. Redraw boundaries around business capabilities and invariants, moving responsibilities until most features touch one service.

Merging as a strategy. Teams resist merging because it feels like going backwards, but two services that are always deployed together, share data and call each other on every request are already one component; merging them removes network hops, distributed failure modes and duplicated infrastructure at no loss of independence, since there was none.

Deep Dive: Testing and releasing in each architectureShow

In a modular monolith, the test suite can exercise real cross-module flows in one process with a real database, which catches integration bugs cheaply. The challenge is suite size and time: test selection by module dependency graph, parallel runners and flaky-test quarantine keep feedback within minutes. Releases use trunk-based development, merge queues, feature flags and canaries. Because everything ships together, feature flags are the unit of release: a feature is deployed dark and enabled separately, decoupling deployment from release.

In microservices, each service has fast, independent tests, but integration confidence must come from elsewhere:

  • Consumer-driven contract tests catch breaking API changes at build time. Each consumer records the requests it makes and the responses it expects; the provider's pipeline replays them against the new version.
  • Component tests run one service with real infrastructure, such as its database in a container, and its dependencies stubbed.
  • A small set of end-to-end tests run against staging for critical user journeys only.
  • Progressive delivery in production: canary deployments to a small percentage of traffic with automatic rollback on error or latency regressions, and traffic shadowing for risky changes.

Release independence depends on compatibility discipline. The expand-and-contract approach applies to APIs as well as schemas: first add the new field or endpoint while keeping the old one, migrate consumers, then remove the old one. A service that can only be released after its consumers update is not independently deployable, whatever the architecture diagram says.

Key Takeaways#

  • A monolith deploys everything as one unit, giving simplicity, fast in-process calls and local transactions, but coupling, shared releases and a shared failure domain grow with size.
  • Microservices give independent deployment, scaling, failure isolation and team autonomy, but each benefit depends on preconditions such as data ownership and backward-compatible APIs.
  • The microservice premium of network failures, distributed data, operations, testing and platform work is paid up front, so microservices pay off mainly at organisational scale.
  • A modular monolith, one deployable with enforced module boundaries and module-owned schemas, is the right default and keeps future extraction cheap.
  • Split a module into a service only for a measured reason, such as team contention, divergent scaling or reliability, compliance isolation or a different change rate, and only when its boundary and data are already clean.
  • Decompose by business capability and keep each strong invariant inside one service; splitting by layer or by table creates a distributed monolith.
  • Database per service is what makes services independent: cross-service queries use API composition or event-fed read models, and cross-service writes use sagas with an outbox.
  • Migrate with the strangler fig: a routing facade, one capability at a time, change data capture for data, shadow traffic for verification, and reversible cutovers.
  • Prime Video's monitoring tool shows that components exchanging large data at high frequency belong in one process, and Shopify shows that strong modularity does not require a network.
  • Microservice best practices are ownership, private data, independent deployability, async communication, resilient and idempotent calls, automation, observability and a shared paved road.