πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Microservices

ArchitectureService Architecture🟒 Free Lesson

Advertisement

System Design - Architecture

Microservices

Microservices decompose a system into small, independently deployable services that communicate over well-defined APIs. This guide covers when to use microservices, how to decompose a system, and the infrastructure patterns that make them work.

  • Decomposition - Splitting by business capability or subdomain
  • Service Discovery - How services find each other in a dynamic environment
  • API Gateway - Single entry point for external clients

Do not start with microservices. Start with a monolith and extract services when you have clear boundaries.

Monolith vs Microservices

DfMonolithic Architecture

A monolithic architecture deploys the entire application as a single unit. All components share the same process, memory, and database. It is simpler to develop, test, and deploy initially but becomes harder to scale and modify as the system grows.

DfMicroservices Architecture

A microservices architecture decomposes a system into small, independent services, each owning its data and business logic. Services communicate via lightweight protocols (HTTP, gRPC, messaging). Each service can be developed, deployed, and scaled independently.

MonolithAll Components in One ProcessSingle DatabaseShared MemorySingle DeploymentTightly CoupledOne Codebase, One TeamMicroservicesAuth ServiceUser ServiceOrder ServicePayment SvcNotify ServiceSearch ServiceEach service owns its dataIndependent deploymentLoosely coupled

When to Use Microservices

FactorMonolithMicroservices
Team sizeSmall (< 10 engineers)Large (multiple teams)
Domain complexitySimple, well-understoodComplex, multiple bounded contexts
Deployment frequencyLow to moderateHigh (multiple times per day)
Scaling needsScale as a unitScale individual components
Technology diversitySingle stackPolyglot (best tool per service)
Organizational maturityLow to moderateHigh (DevOps culture required)

Start with a monolith. The "Monolith First" approach (Martin Fowler) recommends building a well-structured monolith first, then extracting services when you have clear domain boundaries and the organizational capability to operate them.

Decomposition Strategies

By Business Capability

Decompose along organizational lines: User Management, Order Processing, Payment, Notification.

By Subdomain (DDD)

Apply Domain-Driven Design to identify bounded contexts:

DfBounded Context

A bounded context is a linguistic and organizational boundary within which a particular domain model applies. Each microservice should correspond to a bounded context, owning its domain model and data.

Decomposition Principles

  1. Single Responsibility: Each service does one thing well
  2. High Cohesion: Related functionality lives together
  3. Low Coupling: Services interact through well-defined APIs
  4. Data Ownership: Each service owns its data (no shared databases)
  5. Team Autonomy: Each service is owned by a small, autonomous team

The "Two Pizza Rule" (Amazon): A team should be small enough that it can be fed with two pizzas (6-8 people). This maps well to microservice team size.

Service Discovery

In a dynamic environment where services scale up and down, services need to find each other.

DfService Discovery

Service discovery is the mechanism by which services locate the network addresses of other services. It solves the problem of dynamic service instances in a microservices architecture where instances are constantly being created and destroyed.

Discovery Patterns

PatternDescriptionExample
Client-sideClient queries registry, load balances itselfNetflix Eureka
Server-sideLoad balancer handles discoveryAWS ELB, Kubernetes Service
DNS-basedServices registered as DNS entriesConsul, CoreDNS
ClientService RegistrySvc A (v1)Svc A (v2)Svc A (v3)1. Lookup2. Return instances3. Direct connection

API Gateway

An API Gateway provides a single entry point for external clients.

DfAPI Gateway

An API Gateway is a server that acts as a single entry point for a set of microservices. It handles cross-cutting concerns such as authentication, rate limiting, request routing, protocol translation, and response aggregation.

API Gateway Responsibilities

ResponsibilityDescription
Request routingRoute external requests to appropriate internal services
AuthenticationVerify client identity (JWT, OAuth)
Rate limitingProtect services from abuse
Load balancingDistribute requests across service instances
Request aggregationCombine multiple service responses into one
Protocol translationConvert external protocols (HTTP) to internal (gRPC)
Response cachingCache responses to reduce backend load
Logging and monitoringCentralized observability

API Gateway vs Direct Communication

PatternProsCons
GatewayCross-cutting concerns centralized, simplified clientSingle point of failure, added latency
DirectNo gateway overhead, direct service communicationCross-cutting concerns duplicated

Use an API Gateway for external-facing APIs. For internal service-to-service communication, use a service mesh (Istio, Linkerd) instead of routing through a gateway. This avoids the gateway becoming a bottleneck.

Inter-Service Communication

Synchronous Communication

ProtocolDescriptionUse Case
REST/HTTPStandard, widely supportedSimple APIs, external clients
gRPCHigh-performance, contract-firstInternal service communication

Asynchronous Communication

PatternDescriptionUse Case
Message queuePoint-to-point task distributionBackground jobs, work queues
Event streamingPub/sub event distributionEvent sourcing, data pipelines
Event busDecoupled event notificationDomain events, choreography

The Twelve-Factor App

The Twelve-Factor App methodology provides best practices for building microservices:

  1. Codebase: One codebase in version control, many deploys
  2. Dependencies: Explicitly declare and isolate dependencies
  3. Config: Store config in the environment
  4. Backing services: Treat backing services as attached resources
  5. Build, release, run: Strictly separate build and run stages
  6. Processes: Execute the app as one or more stateless processes
  7. Port binding: Export services via port binding
  8. Concurrency: Scale out via the process model
  9. Disposability: Maximize robustness with fast startup and graceful shutdown
  10. Dev/prod parity: Keep environments as similar as possible
  11. Logs: Treat logs as event streams
  12. Admin processes: Run admin/management tasks as one-off processes

Practice Exercises

  1. Design: You are tasked with decomposing a monolithic e-commerce application into microservices. Identify the bounded contexts and define service boundaries. What data does each service own?

  2. Trade-offs: Compare REST and gRPC for inter-service communication in a microservices architecture. When would you choose each?

  3. Architecture: Design an API Gateway for a system with 20 microservices. How do you handle authentication, rate limiting, and request aggregation without creating a bottleneck?

  4. Migration: Your team has a large monolith serving 50M users. Outline a strategy for incrementally extracting microservices without disrupting production traffic.

Key Takeaways:

  • Start with a monolith; extract microservices when you have clear domain boundaries and organizational maturity
  • Decompose by business capability or bounded context (DDD)
  • Service discovery enables dynamic service location in elastic environments
  • API Gateway centralizes cross-cutting concerns for external clients
  • Service mesh handles internal service-to-service communication
  • Follow the Twelve-Factor App methodology for building cloud-native services

What to Learn Next

-> CAP Theorem Consistency models, availability, and partition tolerance.

-> Load Balancing Algorithms, health checks, and L4 vs L7.

-> Message Queues Kafka, RabbitMQ, event-driven architecture.

-> API Design REST, GraphQL, gRPC, versioning, and rate limiting.

-> Databases SQL vs NoSQL, indexing, replication, and sharding.

-> Scalability Fundamentals Vertical vs horizontal scaling and capacity planning.

⭐

Premium Content

Microservices

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert System Design Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement