SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Client-Server
  • Monolithic Architecture
  • Microservices
  • Serverless
  • Event-Driven Architecture
  • Peer-to-Peer (P2P)
  • Hexagonal Architecture
  • CQRS
  • Event Sourcing
  • Domain-Driven Design (DDD)
  • Layered (N-Tier) Architecture
  • Containers and Docker
  • Kubernetes Basics
  • Clean Architecture and Modular Monolith
  • Multi-Tenancy
  • Cloud Basics: Regions, Zones and Edge
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Architectural Patterns

Microservices

Split an app into small services that each do one job and can be deployed on their own.

โฑ 16 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Microservices split one big application into many small services. Each one does one business job, runs on its own, has its own data, and talks to the others over the network.

  • Each service can be built, deployed and scaled on its own, by its own small team.
  • A failure is contained: if Reviews crashes, Checkout can still work.
  • The price is complexity: network calls, many deployments, data spread over many databases, and hard debugging.
  • Most of the patterns in the rest of this part (gateway, discovery, circuit breaker, mesh) exist to tame that complexity.

02Concept: What is it?

In a microservices architecture, each service owns one business capability, such as Catalog, Cart, Payments or Shipping. A service is small enough for a team to understand fully, and independent enough to be released without asking the others.

Services talk through APIs (REST, gRPC) for direct questions, or through events and message queues for things that can happen later. Each service keeps its own database. No other service may read its tables. If the Orders service needs a customer's name, it asks the Users service.

Because the services are separate programs, they can use different languages and databases, and each can run many copies by itself. In front of them there is usually an API gateway, and behind them there is shared tooling for logs, metrics and tracing.

A shop built from services
๐Ÿ“ฑClients
โ†’โ†“
๐ŸšชAPI Gateway
โ†’โ†“
๐Ÿ›๏ธCatalogown DB
๐Ÿ›’Cartown DB
๐Ÿ“ฆOrdersown DB
๐Ÿ’ณPaymentsown DB
โ†•APIs and events between services
Each service has its own code, its own database and its own release.
๐Ÿง One service, one owner, one database
If two services share a database table, they are tied together. A change to the table can break both, and they must be released as a pair. That is a distributed monolith: all the pain and none of the gain.

03Real-Life Example

๐ŸตThe Food Court
Instead of one big restaurant, picture a food court. There is a pizza stall, a sushi stall, a juice bar and a coffee cart. Each has its own kitchen, own staff and own menu. If the sushi stall has a fire, the others keep serving. On a hot day the juice bar adds a second counter without touching anything else. A stall can change its menu at any time. The price: a guest who wants a full meal must visit several stalls and pay several times, and the court needs signs, a manager and rules so everything works together.
Food court
Microservices
One stall with one speciality
One service with one business job
Each stall has its own kitchen
Each service has its own process and database
A fire in one stall
A crash in one service
Juice bar adds a counter
Scale only the busy service
Stalls change menus freely
Independent releases
Guests visit several stalls
One page calls several services (network calls)
Signs and a food court manager
API gateway and service discovery
Cashiers who pass notes between stalls
Messages and events between services
What one checkout can touch
๐Ÿ›’Cart
โ†’โ†“items
๐Ÿ“ฆOrders
โ†’โ†“pay
๐Ÿ’ณPayments
โ‡ขโ‡ฃevent
๐Ÿ””Notifications

04Why Do We Need It?

๐Ÿ“ˆScale what is busy
Search is hot? Run 20 copies of Search only, and leave the rest alone.
๐ŸšขShip independently
A team deploys its service many times a day without a company-wide release.
๐ŸงฏContain failures
A broken service hurts only the features that need it. The rest keeps running.
๐Ÿ‘ฅMatch team structure
Small teams own a service end to end, so they decide and move faster.
๐ŸงฐRight tool for each job
Use the best language and database for each service, such as a graph database for recommendations.
๐Ÿ”„Easier to replace
A small service can be rewritten without touching the rest.
Microservices are mostly a way to organise people and releases at scale. The technology follows from that need.

05Where Do We Use It?

๐ŸขLarge organisations
Many teams working on one product that must release without waiting for each other.
๐Ÿ“ŠUneven load
Some parts get 100x the traffic of others, like search or a feed.
๐ŸŒNeed for fast, frequent releases
Teams that deploy many times a day.
๐Ÿ›ก๏ธDifferent risk levels
Payments needs strict security and audit. A blog does not. Separate services allow separate rules.
๐ŸงฌDifferent technology needs
Machine learning in Python, a high-speed gateway in Go, a ledger in Java.
โ˜๏ธCloud and containers
Docker and Kubernetes make running many small services much easier.
โš ๏ธNot for everyone
With a small team or an unclear product, microservices often slow you down. The extra moving parts need people and tooling. See the Monolithic Architecture topic.

06Types / Parts / How It Works

How the pieces fit

The usual building blocks
Edge
๐ŸšชAPI Gatewayone front door
๐Ÿ”Auth
Services
๐Ÿ›’Cart
๐Ÿ“ฆOrders
๐Ÿ’ณPayments
๐ŸงญService discoverywhere is each one?
Data and messages
๐Ÿ—„๏ธDB per service
๐Ÿ“ฌMessage brokerevents
Edge Business Data
Each box is a problem that appears once you have many services. Later topics cover them one by one.

Two ways services talk

Synchronous (request / response)
REST or gRPC
  • The caller waits for the answer
  • Simple to reason about
  • If the other service is slow or down, the caller suffers
  • Needs timeouts, retries and circuit breakers
Asynchronous (events / queues)
Kafka, RabbitMQ, SQS
  • The sender drops a message and moves on
  • Services are loosely tied
  • Survives a service being down for a while
  • Harder to follow, and results arrive later (eventual consistency)

How to draw the lines between services

Way to splitExampleNote
By business capabilityOrders, Payments, ShippingThe most common and usually best approach
By domain (Domain-Driven Design)A bounded context such as BillingBoundaries follow how the business thinks and talks
By data ownershipThe service that owns the customer tableHelps avoid shared databases
By technical layerA โ€œdatabase serviceโ€ or โ€œUI serviceโ€Usually a mistake: every change touches every service
VisualizerOne big app or small services: failure, speed and availabilityCrash Payments in both modes and count the features still working. Then raise the number of services per page and the network time, and see what the split costs in speed and availability.
How is the shop built?
What breaks?
Five separate services, each with its own process
๐Ÿ›๏ธ
Catalog
up
๐Ÿ›’
Cart
up
๐Ÿ’ฅ
Payments
down
โญ
Reviews
up
โœจ
Recommendations
up
Browse productsCartCheckoutReviewsRecommendations
Features working
4 of 5
after the failure
Page time
50 ms
includes network calls
Availability
99.60%
about 173 min down / month
Payments is down, so Checkout fails. But 4 of 5 features still work: people can browse, fill the cart and read reviews. The failure was kept small (a small blast radius).

A simplified model. Every process is assumed to be up 99.9% of the time, and a page needs every service it calls, so availability multiplies. Timeouts, retries, caching and fallbacks (see Circuit Breaker) bring the real numbers back up.

07How to Use It / Steps / Implementation

Going the microservices way, step by step

  1. 1
    Find the boundaries
    Talk to the business. Use domain-driven design to find bounded contexts. Wrong boundaries are the costliest mistake.
  2. 2
    Give each service its own data
    One owner per table. Other services use its API or listen to its events, never its database.
  3. 3
    Define clear contracts
    Publish the API (OpenAPI, protobuf) and version it. Never break callers without warning.
  4. 4
    Add a gateway and discovery
    Clients use one front door. Services find each other by name, not by fixed addresses.
  5. 5
    Design for failure
    Use timeouts, retries with backoff, circuit breakers and bulkheads. Every network call can fail.
  6. 6
    Prefer events for side effects
    Publish โ€œOrderPlacedโ€ and let other services react, instead of calling them one by one.
  7. 7
    Handle data across services
    No big ACID transaction across services. Use sagas (a chain of local steps with undo steps) and accept eventual consistency.
  8. 8
    Invest in observability
    Central logs, metrics and distributed tracing with a correlation ID. Without them you cannot debug.
  9. 9
    Automate everything
    CI/CD per service, containers and an orchestrator like Kubernetes. Manual deploys do not scale to 50 services.
๐Ÿ’กExtract, do not rewrite
Moving from a monolith? Cut out one capability at a time with the Strangler Fig pattern and keep the product running the whole time.

08Key Terms to Know

TermMeaning in easy words
MicroserviceA small, independently deployable service that owns one business capability
Bounded contextA clear boundary in which one model and one set of words apply (from domain-driven design)
Database per serviceEach service owns its data and no one else touches it directly
API GatewayA single entry point that routes client requests to the right service
Service discoveryHow services find the current address of each other
SagaA series of local transactions with compensating steps, used instead of one distributed transaction
Eventual consistencyData in different services becomes the same after a short delay
Distributed tracingFollowing one request as it passes through many services
Distributed monolithServices that must be released together, with the costs of both styles
Orchestration vs choreographyA central coordinator tells services what to do, or services react to each other's events
Blast radiusHow much a single failure can damage

09Pros, Cons and Trade-offs

โœ… Pros
  • Scale and deploy each service on its own
  • Failures stay local when designed well
  • Small teams own services end to end
  • Free choice of language and database per service
  • Easier to rewrite or replace one part
  • Faster, safer releases at large scale
โš ๏ธ Cons
  • Network calls are slower and can fail
  • Much higher operations and tooling cost
  • Data is spread out, with eventual consistency and sagas
  • Hard to debug, test and trace across services
  • Needs strong DevOps, monitoring and discipline
  • Easy to cut wrong boundaries and build a distributed monolith

Trade-offs

ChoiceWe gainWe lose
Split into servicesIndependent scale, release and failureNetwork cost and many things to run
Database per serviceLoose coupling and free technology choiceNo joins or single transactions across services
Synchronous callsSimple and instant answerTight coupling and chains of failure
Asynchronous eventsLoose coupling and resilienceComplex flow and delayed results
Many small servicesVery focused teamsMore deployments, more network hops, more to monitor
Few bigger servicesLess overheadLess independence

10Common Problems and Mistakes

Common mistakes

  1. Starting with microservices. Without knowing the domain, you draw wrong lines that are costly to move.
  2. Shared database. Services secretly depend on each other's tables. This builds a distributed monolith.
  3. Services too tiny. "Nano-services" create endless calls for one simple action.
  4. Long synchronous chains. A calls B calls C calls D. One slow service slows them all, and availability multiplies down.
  5. No timeouts or circuit breakers. One struggling service drags the whole system into failure.
  6. No observability. When a request fails somewhere in 12 services, you cannot find where.
  7. Ignoring data consistency. Expecting one big transaction across services instead of designing sagas.
  8. Breaking contracts. Changing an API with no versioning breaks other teams.

Things to watch

๐Ÿ•ธ๏ธCascading failure
A slow service piles up waiting callers, which then fail too. Use circuit breakers and bulkheads.
๐ŸงฎAvailability maths
Ten services at 99.9% each give about 99.0% for a request that needs them all.
๐Ÿ”Debugging
Trace IDs and central logs are not optional.
๐Ÿ”€Version drift
Callers and services upgrade at different times. Keep APIs backward compatible.

11Real-World Examples

๐ŸŽฌNetflix
Moved from one monolith to hundreds of services after a big outage, and built tools such as Eureka and Hystrix to run them.
๐Ÿ“ฆAmazon
Teams own services behind APIs. This idea (โ€œyou build it, you run itโ€) shaped AWS.
๐Ÿš—Uber
Grew to thousands of services, later grouped them into domains to tame the complexity.
๐ŸŽตSpotify
Small autonomous squads own services for playlists, search and playback.
๐Ÿ Airbnb
Split a large Rails monolith into services, in steps, over several years.
โš ๏ธSome went back
A few teams have merged services back into a monolith when the overhead was higher than the benefit.
๐Ÿ“Note
Details of company architectures change over time. The common story is: monolith first, then split where team size or scale demands it.
Mini case: Black Friday
๐Ÿ›๏ธCatalogx 10 copies
๐Ÿ›’Cartx 6 copies
๐Ÿ“ฆOrdersx 3 copies
๐Ÿ“งEmailx 1 copy
Only the services under pressure are scaled.

12Related Topics to Read Next

Monolithic Architectureโ†’

The simpler starting point you split from.

API Gateway Patternโ†’

The single front door for all your services.

Service Discoveryโ†’

How services find each other when addresses change.

Circuit Breakerโ†’

Stops one failing service from taking down its callers.

Event-Driven Architectureโ†’

A loose way for services to talk through events.

Strangler Figโ†’

How to move from a monolith to services in small, safe steps.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: many small services, each with one business job, its own data and its own release.
  • โœ”Gain: independent scale and deploy, contained failures, team autonomy.
  • โœ”Cost: network calls, ops overhead, eventual consistency, hard debugging.
  • โœ”Rules: one owner per database, clear versioned APIs, no shared tables.
  • โœ”Talk: sync (REST/gRPC) for questions, async events for reactions.
  • โœ”Needs: gateway, service discovery, circuit breakers, tracing, CI/CD.
  • โœ”Data: use sagas, not one big transaction.
  • โœ”One line: โ€œSplit by business job, and pay for independence with network and operations cost.โ€
โ† Previous
Monolithic Architecture
Next โ†’
Serverless