Microservices Patterns - Complete Internal Map
// Decomposition · communication · data · reliability · observability · security · deployment · transactions
46 total patterns
Decomposition
Communication
Data
Reliability
Transactions
01Decomposition Patterns- How to split a system into microservices
📋Decompose by Business Capabilitydecompose
Split services around stable business capabilities such as users, orders, billing, and shipping.
Business capabilities
├─ User Management -> UserService
├─ Order Processing -> OrderService
├─ Billing -> BillingService
└─ Shipping -> ShippingService
e.g.: Amazon teams for Cart, Search, Checkout
🏛️Decompose by Subdomain (DDD)DDD
Use Domain-Driven Design bounded contexts to create services with their own language and model.
Core domain -> OrderService
Supporting -> InventoryService
Generic -> AuthService
Each context owns its model
e.g.: DDD by Eric Evans, Vaughn Vernon
🔄Strangler Fig Patternmigration
Incrementally extract services from a monolith while routing selected traffic to the new system.
Monolith handles all
-> extract UserService
-> route user traffic
-> extract OrderService
-> retire monolith
e.g.: Real-world monolith to microservice migrations
📦Self-Contained Servicedesign
Design services to answer requests from local ownership data instead of chaining synchronous calls.
Chatty: Client -> A -> B -> C
Self-contained: Client -> A
A uses local read model
Other services sync async
e.g.: Event-driven microservices with local projections
02Communication Patterns- How services talk to each other
↩️Synchronous REST / gRPCsync
Direct request-response communication where the caller waits for a downstream service.
Service A -> HTTP/gRPC -> Service B
Service A waits for response
Failure in B affects A
e.g.: Express REST, gRPC with Protobuf, GraphQL
📨Asynchronous Messagingasync
Services communicate through a broker so producers and consumers can scale independently.
Producer -> Broker topic/queue
Consumer A pulls
Consumer B pulls
Producer does not wait
e.g.: Kafka, RabbitMQ, SQS, NATS
🔔Event-Driven Communicationevents
Services publish domain events when important business facts happen.
OrderService emits OrderPlaced
EmailService reacts
InventoryService reacts
AnalyticsService reacts
e.g.: Kafka events, EventBridge, Node EventEmitter
🌐API Gateway Patterngateway
A single entry point routes, authenticates, rate-limits, and protects backend services.
Client -> API Gateway
-> auth
-> rate limit
-> route to service
e.g.: Kong, AWS API Gateway, Nginx, Traefik
🔍Service Discoverydiscovery
Services register and discover dynamic endpoints instead of hardcoding hostnames or IPs.
Service starts -> registry
Client asks registry
Registry returns healthy endpoints
e.g.: Consul, Kubernetes DNS, Eureka
🛰️Microservices Communication Deep Divecommunication
Interactive deep dive on service discovery, load balancing, resilience, and live communication behavior.
Client -> Discovery -> Load Balancer -> Service Instance
Failures -> Retry / Circuit Breaker
Health checks -> dynamic routing
e.g.: Service discovery + round robin + circuit breaker simulation
03Service Design Patterns- How individual services are structured internally
🛸Sidecar Patterninfra
Run a helper container beside the app to handle cross-cutting infrastructure concerns.
Pod
├─ Main App
└─ Sidecar
logs, proxy, certs, metrics
e.g.: Istio Envoy sidecar, Datadog agent, Fluentd
🏗️Backends for Frontends (BFF)design
Create a tailored backend/API layer per client type such as web, mobile, or TV.
Mobile -> Mobile BFF -> services
Web -> Web BFF -> services
TV -> TV BFF -> services
e.g.: Netflix, SoundCloud BFF architecture
🤝Ambassador Patternproxy
Use a local proxy to handle network concerns for a service.
App -> Ambassador proxy -> remote service
proxy handles retry, auth, logging
e.g.: Envoy, Ambassador API Gateway, Linkerd
🕸️Service Meshinfra
A mesh of sidecar proxies manages service-to-service traffic transparently.
Service A -> Proxy A -> Proxy B -> Service B
mesh handles mTLS, retries, tracing
e.g.: Istio, Linkerd, Consul Connect
🔄Anti-Corruption Layer (ACL)DDD
Translate between your clean domain model and an external or legacy model.
Your Domain <-> ACL adapter <-> Legacy/external system
translation both ways
e.g.: Legacy adapters, SDK wrappers, domain mappers
04Data Patterns- How services manage and share data
🗄️Database per Servicedata
Each service owns its database and no other service reads or writes it directly.
UserService -> User DB
OrderService -> Order DB
PaymentService -> Payment DB
No cross-DB access
e.g.: Microservices data ownership best practice
✂️CQRSdata
Separate write models from read models so each can optimize for its own workload.
Commands -> Write model
Events/projector -> Read model
Queries -> optimized read DB
e.g.: Event-sourced systems, denormalized read stores
📜Event Sourcingevents
Store every state change as an immutable event and rebuild state by replaying events.
AccountOpened
MoneyDeposited
MoneyWithdrawn
Replay -> current balance
e.g.: EventStoreDB, Axon, custom event logs
📤Transactional Outboxreliable events
Write business data and outgoing event records in one local database transaction.
DB transaction:
1. update order
2. insert outbox event
Poller publishes event later
e.g.: Debezium outbox transform, custom outbox poller
🔀API Compositionquery
Aggregate data from multiple services into one response.
Client -> Composer
-> UserService
-> OrderService
-> PaymentService
<- combined response
e.g.: GraphQL resolvers, BFF aggregators
👂Change Data Capture (CDC)CDC
Capture database changes and publish them as events.
DB commit -> transaction log
CDC connector -> event stream
Consumers update projections
e.g.: Debezium, Kafka Connect, database logs
05Reliability Patterns- Keep services resilient under failure
⚡Circuit Breakerresilience
Stop calling a failing dependency to prevent cascading failures.
[CLOSED] -- failures >= threshold --> [OPEN]
[OPEN] -- resetTimeout elapsed --> [HALF-OPEN]
[HALF-OPEN] -- probe success --> [CLOSED]
[HALF-OPEN] -- probe failure --> [OPEN]
OPEN behavior: fast-fail + fallback
e.g.: opossum, Resilience4j, Hystrix
🚢Bulkhead Patternisolation
Isolate resources so one failing area does not take down the whole system.
Pool A: checkout
Pool B: search
Pool C: reports
Report failure cannot sink checkout
e.g.: Thread pools, connection pools, K8s namespaces
🔁Retry with Exponential Backoffretry
Retry transient failures with progressively longer waits and jitter.
fail -> wait 100ms
fail -> wait 200ms
fail -> wait 400ms + jitter
success or give up
e.g.: axios-retry, got retry, AWS SDK retry
⏱️Timeout Patterntimeout
Never wait forever for an outgoing call.
Call starts
Deadline set
No response by deadline
-> fail fast
e.g.: fetch AbortController, axios timeout, gRPC deadline
🏃Health Check / Readiness Probeops
Expose endpoints that tell orchestrators whether the service is alive and ready.
Liveness: should restart?
Readiness: should receive traffic?
Startup: finished booting?
e.g.: Kubernetes livenessProbe, readinessProbe, Consul health
06Observability Patterns- See what happens inside distributed services
🔎Distributed Tracingobserve
Follow one request across services using trace IDs and spans.
Gateway span
-> UserService span
-> OrderService span
-> DB span
Find slow hop
e.g.: OpenTelemetry, Jaeger, Zipkin, AWS X-Ray
🪵Centralized Logginglogs
Aggregate structured logs from all services into one searchable place.
Service logs -> collector -> central store
Search by traceId, userId, error
e.g.: ELK, Loki + Grafana, Datadog logs, CloudWatch
📊Metrics & Monitoringmetrics
Emit numeric service and resource measurements for dashboards and alerts.
RED: rate/errors/duration
USE: utilization/saturation/errors
Dashboards + alerts
e.g.: Prometheus + Grafana, Datadog, New Relic
🏷️Correlation IDobserve
Thread a unique request ID through headers, logs, and downstream calls.
Gateway creates X-Request-ID
All services forward it
All logs include it
e.g.: X-Request-ID, express-request-id, Morgan logger
🔍Log Aggregation + Alertingalerts
Trigger alerts from logs and metrics before users report problems.
Metric/log rule
-> threshold/anomaly
-> alert
-> on-call response
e.g.: PagerDuty, OpsGenie, Grafana Alerts, CloudWatch Alarms
07Security Patterns- Secure service-to-service and client-to-service communication
🔒Mutual TLS (mTLS)security
Both client and server services verify each other with certificates.
Service A cert <-> Service B cert
Both verify identity
Encrypted channel
e.g.: Istio mTLS, Linkerd, SPIFFE/SPIRE
🎫Token-Based Auth (JWT)auth
Use signed tokens to propagate identity and authorization claims.
Auth service issues JWT
Client sends token
Services validate signature locally
e.g.: jsonwebtoken, jose, Auth0, Keycloak, Cognito
🚫Zero Trust Architecturesecurity
Authenticate and authorize every request, even inside the private network.
Old: internal = trusted
Zero trust: verify every request
identity + policy + audit
e.g.: BeyondCorp, SPIFFE/SPIRE, Istio AuthorizationPolicy
🔑Secrets Managementsecrets
Store and rotate credentials in a vault instead of hardcoding them.
Service starts
-> fetch secret from vault
-> use short-lived credential
-> rotate safely
e.g.: HashiCorp Vault, AWS Secrets Manager, encrypted K8s Secrets
08Deployment Patterns- How microservices are deployed and released safely
🔵🟢Blue-Green Deploymentdeploy
Run two identical environments and switch traffic after the new one passes checks.
Blue = live v1
Green = deploy v2
Test green
Switch traffic to green
Blue becomes rollback
e.g.: AWS CodeDeploy, Kubernetes service switching
🐦Canary Deploymentdeploy
Release to a small percentage of traffic, monitor, then gradually increase.
5% -> v2 canary
95% -> v1 stable
Monitor errors/latency
Increase or rollback
e.g.: Argo Rollouts, Flagger, Spinnaker, Istio weights
🔄Rolling Updatedeploy
Replace old instances with new instances gradually.
[v1][v1][v1]
-> [v2][v1][v1]
-> [v2][v2][v1]
-> [v2][v2][v2]
e.g.: Kubernetes Deployment default rollout
👻Shadow / Mirror Deploymentdeploy
Mirror production traffic to a new version, but discard shadow responses.
User traffic -> v1 live
Mirror same request -> v2 shadow
Discard shadow response
Compare logs/metrics
e.g.: NGINX mirror module, Envoy traffic shadowing, Istio mirror
💥Recreate Deploymentdeploy
Stop old version first, then start the new version.
Stop v1
Downtime window
Start v2
Serve traffic again
e.g.: Kubernetes strategy: Recreate, controlled maintenance windows
⚖️A/B Testing Rolloutexperiment
Route different user segments to different versions to compare outcomes.
Segment users by rule
Group A -> version A
Group B -> version B
Compare conversion and engagement
e.g.: LaunchDarkly, Statsig, Optimizely, custom feature-flag routers
🏗️Immutable Infrastructuredeploy
Never patch running instances; build a new image and replace them.
Bad: patch live server
Good: build image v2
Deploy replacement
Terminate old
e.g.: Docker, Kubernetes, Packer AMIs, GitOps with ArgoCD
🎯Deployment Interview Cardinterview
Layer-level interview focus across deployment strategies.
Q: Blue-Green vs Canary - when to choose each?
A: Blue-Green for instant rollback and strict cutover.
A: Canary for gradual risk control with live metrics.
Tip: mention rollback speed, observability, and infra cost tradeoffs.
09Distributed Transaction Patterns- How to maintain data consistency across services
⚗️Saga Pattern - Choreographytransactions
Services publish and react to events without a central coordinator.
OrderCreated
-> PaymentService charges
-> StockService reserves
Failure -> compensating events
e.g.: Kafka choreography, EventBridge rules
🎛️Saga Pattern - Orchestrationtransactions
A central orchestrator commands each service step and handles compensation.
Orchestrator
-> reserve stock
-> charge payment
-> ship order
failure -> compensate
e.g.: Temporal.io, AWS Step Functions, Conductor, Camunda
📤Outbox + Inbox Patternconsistency
Use outbox records for reliable sends and inbox records for idempotent receives.
Sender DB transaction:
write data + outbox
Receiver:
check inbox messageId
process once
e.g.: Debezium outbox, custom outbox poller, inbox table
🔒Two-Phase Commit (2PC)consistency
A coordinator asks participants to prepare, then commits or rolls back all participants.
Phase 1: prepare all
All yes -> commit all
Any no -> rollback all
e.g.: XA transactions; rarely preferred in microservices
Production microservices use patterns from many categories together: boundaries, communication, data ownership, failure handling, observability, security, release safety, and consistency all matter.