A monolith ships the whole application as one deployable unit. Microservices split it into small services that are deployed, scaled and owned independently, each built around a business capability. The choice is less about technology than about team scale and the cost of distribution: microservices buy autonomy and independent releases by paying in network calls, eventual consistency and operational complexity. Most successful systems start as a well-structured monolith and split only where it hurts.
Think of it like
One restaurant kitchen vs a food court
A single restaurant has one kitchen: chefs coordinate by shouting across the room, and a combined order comes out together. But one grease fire closes the whole place, and adding a sushi bar means remodeling everything. A food court gives every stall its own kitchen, staff and suppliers, so each can change its menu or hours independently. The price: a meal that spans three stalls is awkward to coordinate, and someone has to run the shared seating, cleaning and security.
Three shapes of a system
Architectures sit on a spectrum. The real question is not monolith or microservices but where to draw deployment boundaries, and how strictly to enforce module boundaries inside them.
Monolith
- One codebase, one build, one deployable artifact
- Modules call each other in-process: fast and type-checked
- One database, so cross-module ACID transactions are trivial
- Scales by running identical copies behind a load balancer
- Risk: without discipline it decays into a big ball of mud
Modular monolith
- Still one deployable, but split into modules with explicit public APIs
- Each module owns its tables; no reaching into another module's data
- Boundaries enforced by tooling (Java modules, ArchUnit, Packwerk, lint rules)
- Most of the design benefits of services, none of the network costs
- A clean module can be extracted into a service later
Microservices
- Many small services, each independently deployable
- Communicate over the network: HTTP, gRPC or messages
- Each service owns its data (database per service)
- Teams release on their own schedule and choose their own stack
- Paid for with latency, partial failure and operational overhead
Here is a modular monolith handling an order. Press play to see why it is so simple: every hop is a function call inside one process, and one database transaction keeps everything consistent.
Trade-offs at a glance
| Dimension | Monolith | Microservices |
|---|---|---|
| Deployment | One artifact; every change redeploys everything | Each service deploys independently, many times a day |
| Scaling | Scale the whole app, even if only one part is hot | Scale each service to its own load profile |
| Call latency | In-process calls (nanoseconds) | Network calls (roughly 0.5 to a few ms each, plus serialization) |
| Consistency | Local ACID transactions across modules | No cross-service transactions; sagas and eventual consistency |
| Failure modes | A crash or memory leak takes down everything | Partial failures, timeouts, retries, cascading failures |
| Debugging | One stack trace, one log stream | Needs distributed tracing and correlation IDs |
| Team autonomy | Shared codebase; releases need coordination | Teams own services end to end |
| Technology | One language and framework | Polyglot is possible (but costly to support) |
| Operational cost | One pipeline, simple infrastructure | Many pipelines, service discovery, mesh, observability platform |
| Moving boundaries | Easy: move code between modules | Hard: change APIs and migrate data between stores |
Drawing service boundaries
Bad boundaries are the most expensive mistake in microservices. Split by business capability, the things the business does (take orders, bill customers, ship parcels), not by technical layer. Layer-based splits mean every feature touches every service.
Split by technical layer
- UI service, business-logic service, data-access service
- Every feature change crosses all three
- Constant cross-team coordination for releases
- Chatty network calls on every request
Split by business capability
- Catalog, Orders, Payments, Shipping, Accounts
- Most features change one service
- One team owns a capability end to end
- Calls between services follow real business handoffs
Bounded contexts from domain-driven design
Domain-driven design (DDD, Eric Evans, 2003) offers a sharper tool: the bounded context, a boundary inside which every term has one precise meaning. A Product in the Catalog context has descriptions and images; in Inventory it has stock levels and warehouse bins; in Billing it is a price and a tax code. Forcing one shared Product model on all three creates a bloated object that every team fights over.
- Bounded context
- A boundary (model, code and data) within which a domain model is consistent. A strong default for a service boundary.
- Ubiquitous language
- The shared vocabulary of developers and domain experts inside one context. If two teams use the same word differently, you have two contexts.
- Aggregate
- A cluster of objects changed together under one consistency rule, such as an
Orderand its line items. Transactions should not span aggregates, let alone services. - Context map
- A picture of how contexts relate: who is upstream, who conforms to whose model, and where translation happens.
- Anti-corruption layer
- A translation layer that stops a legacy or external model from leaking into your context.
How services communicate
Every cross-service interaction is either a synchronous request (the caller waits for a reply) or an asynchronous message (the caller hands off and moves on). Most systems use both, and choosing well per interaction is a core design skill.
Synchronous (REST, gRPC)
- Simple request/response that is easy to reason about
- Use when the caller needs the answer now (price check, auth)
- Temporal coupling: if the callee is down, the caller fails
- Latency adds up along call chains
- Needs timeouts, retries and circuit breakers (Resilience Patterns)
Asynchronous (queues, event streams)
- Producer publishes and continues; consumers work at their own pace
- Survives consumer downtime: messages wait in the broker
- Natural fit for fan-out (one event, many reactions)
- Eventual consistency; harder to trace end to end
- Needs idempotent consumers and dead-letter queues (Message Queues & Pub/Sub)
The diagram shows a typical mix. Placing an order calls Payments synchronously because the user must know whether the charge worked, then publishes an OrderPlaced event so Shipping and Notifications can react asynchronously, without Orders even knowing they exist.
| Style | Typical tech | Best for | Watch out for |
|---|---|---|---|
| REST over HTTP | JSON, OpenAPI | Public and CRUD-style APIs; universal tooling | Over/under-fetching; versioning |
| gRPC | HTTP/2 + Protocol Buffers | Low-latency internal calls, streaming, strict contracts | Browsers need a proxy; binary payloads are harder to inspect |
| GraphQL | Schema + resolvers | Aggregating many services for UI clients | N+1 resolver calls; HTTP caching is harder |
| Message queue | SQS, RabbitMQ | Work distribution, one consumer per message | Ordering, poison messages |
| Event stream | Kafka, Kinesis, Pulsar | Fan-out, replay, event-driven pipelines | Schema evolution, consumer lag |
Database per service and data ownership
The rule that makes microservices independent: each service owns its data and is the only one that touches it. Others go through its API or listen to its events. If two services share tables, a schema change in one silently breaks the other, and you are back to coordinated releases.
- Private storage: a separate schema, database or even engine per service (Orders on PostgreSQL, product search on Elasticsearch). See SQL vs NoSQL Databases.
- Cross-service queries: compose via APIs (a gateway or backend-for-frontend fans out and joins), or maintain a read-optimized copy fed by events (CQRS, see Event-Driven Architecture, CQRS & Event Sourcing).
- Cross-service writes: there is no distributed ACID. Use a saga, a sequence of local transactions with compensating actions (refund the payment if shipping fails). See Distributed Transactions.
- Reliable events: write the state change and the outgoing event in the same local transaction with the transactional outbox, then relay the event to the broker.
BEGIN;
INSERT INTO orders (id, customer_id, total_cents, status)
VALUES ('ord_81f2', 'cus_19a7', 4999, 'PLACED');
-- Same transaction: the event can never be lost, or sent without the order
INSERT INTO outbox (id, aggregate_id, event_type, payload, created_at)
VALUES ('evt_5c3e', 'ord_81f2', 'OrderPlaced',
'{"orderId":"ord_81f2","customerId":"cus_19a7","totalCents":4999}', now());
COMMIT;
-- A relay (a polling publisher, or CDC such as Debezium tailing the WAL)
-- publishes new outbox rows to Kafka and marks them sent.
-- The relay may publish twice after a crash, so consumers must be idempotent.The distributed monolith anti-pattern
The worst of both worlds: a system deployed as many services but coupled like a monolith. You pay every cost of distribution (network failures, latency, operational overhead) and get none of the independence.
- Services must be deployed together, in a specific order, for a feature to work.
- Several services read and write the same database tables.
- One user request triggers a deep chain of synchronous calls; one slow service stalls everything.
- A shared library of domain models must be upgraded in lockstep across services.
- Teams cannot ship without a cross-team release meeting.
Migrating with the strangler fig
Rewriting a monolith from scratch is notoriously risky: the old system keeps changing while you chase it. The strangler fig pattern (named by Martin Fowler after a vine that grows around a tree until it replaces it) migrates incrementally. Put a routing facade in front, carve out one capability at a time, and send its traffic to the new service while everything else still reaches the monolith.
- 1
Add a facade
Route all traffic through a proxy or API gateway you control. Initially it forwards 100% to the monolith.
- 2
Pick a seam
Choose a capability with clear boundaries and a real reason to extract it: different scaling needs, a high change rate, or a separate team.
- 3
Build and sync
Implement the new service with its own store. Keep data in sync during the transition with change data capture or events.
- 4
Shift traffic gradually
Route one endpoint, then 1%, 10% and 100% of users to the new service. Compare results (even run both in shadow mode) and roll back instantly if needed.
- 5
Delete the old code
Once the new path has carried all traffic for a while, remove the module from the monolith. Then repeat for the next capability.
When to choose which
Start with a (modular) monolith when
- The team is small: one or two teams, a few dozen engineers at most
- The domain is still being discovered and boundaries will move
- You need to ship quickly with minimal infrastructure
- Strong consistency across features matters
- You lack mature CI/CD, observability and on-call practices
Consider microservices when
- Many teams step on each other in one codebase and release train
- Parts of the system have very different scaling or availability needs
- A component needs different technology or isolation (for example PCI scope for payments)
- Boundaries are well understood and stable
- You can afford the platform: automated deploys, tracing, service discovery
Conway's law
Architecture and org chart are mirror images. If your frontend, backend and database teams are separate, you will get layer-shaped components with handoffs exactly where the teams hand off work. Fighting this is futile; use it.
- Inverse Conway maneuver: design the team structure you want the architecture to have. Want independent Orders and Payments services? Create long-lived, cross-functional Orders and Payments teams.
- Small teams: Amazon's two-pizza team heuristic keeps a service's owners small enough to communicate without heavy process.
- Cognitive load: a team should own no more services than it can deeply understand and operate. The book Team Topologies (Skelton and Pais) builds on this idea.
Key takeaways
- Microservices are primarily an organizational scaling tool: they trade in-process simplicity for team autonomy and independent deployment.
- A modular monolith gives most of the design benefits (clear boundaries, owned data) without network costs, and is the best default for new systems.
- Draw boundaries around business capabilities and DDD bounded contexts, not technical layers.
- Each service owns its data; use sagas for cross-service writes and the transactional outbox for reliable events.
- Migrate incrementally with the strangler fig pattern, never with a big-bang rewrite.
- Conway's law: your architecture will mirror your team structure, so design both together.
Common pitfalls
- Building a distributed monolith: services that share a database or must deploy together.
- Splitting too early, before the domain is understood, then paying to move boundaries across network APIs.
- Long synchronous call chains that multiply latency and failure probability.
- Publishing events with a dual write (commit, then publish) instead of an outbox, and losing events on crashes.
- Adopting microservices without the platform to run them: CI/CD, tracing, centralized logging, service discovery.
Interview tips
- Frame the decision around team size, deployment independence and scaling needs, not fashion.
- When you draw services, name the data each one owns and say how cross-service consistency works (saga, events, outbox).
- Mention the strangler fig for migrations and the distributed monolith as the failure mode you are designing to avoid.
Real-world applications
- Amazon and Netflix decomposing early monoliths into hundreds of services owned by small teams.
- Shopify running a very large modular Rails monolith with tooling-enforced boundaries.
- Banks and retailers strangling mainframe or legacy ERP systems one capability at a time.
Test yourself
Which situation is the clearest sign of a distributed monolith?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.