Quick Reference

September 8, 2026 ยท View on GitHub

Essential Patterns and Practices for Microservices Architecture

This quick reference provides at-a-glance guidance for common microservices patterns, best practices, and decision points. Use this as a handy reference during design sessions, code reviews, and architectural discussions.


๐Ÿ—๏ธ Design Principles

Core Principles Checklist

  • Single Responsibility: Each service has one reason to change
  • Loose Coupling: Minimal dependencies between services
  • High Cohesion: Related functionality grouped together
  • Autonomy: Independently deployable and scalable
  • Resilience: Designed to handle failures gracefully

Adaptive Granularity Governance: The Khan Microservice Pattern

Do not choose fine / medium / coarse from a vibe table. Score the boundary. Chapter 11 is the only source of truth for the formula.

RVx bandMeaningFirst move
> 0.7Healthy on the declared profileKeep publishing E, S, L beside the composite
0.4โ€“0.7At-riskDiagnose the weak signal before you split or merge
< 0.4Not earning its keepInvestigate; do not celebrate a bounce the code cannot explain

Signals (names only; definitions in Chapter 11): E from traces, S from merged PRs (not raw commits), L from static analysis over org-capacity from a system of record.

Social rule (Chapter 23): never use the score in an individual performance review.

KM3 staircase (Chapter 20): Ad hoc โ†’ Instrumented โ†’ Governed โ†’ Portfolio-managed โ†’ Self-correcting.


๐Ÿ“ก Communication Patterns

Synchronous vs Asynchronous

AspectSynchronousAsynchronous
CouplingHigherLower
LatencyDirectIndirect
ResilienceLowerHigher
ComplexityLowerHigher
Use CasesReal-time queriesEvent processing

Communication Pattern Selection

Query Data โ†’ REST/GraphQL
Commands โ†’ Async Messages
Events โ†’ Event Streaming
Real-time โ†’ WebSockets/gRPC

REST API Best Practices

# Good URLs
GET /api/v1/orders/123
POST /api/v1/orders
PUT /api/v1/orders/123
DELETE /api/v1/orders/123

# Bad URLs
GET /api/getOrder?id=123
POST /api/createOrder
PUT /api/updateOrder
DELETE /api/deleteOrder

๐Ÿ—„๏ธ Data Management Patterns

Database per Service Rules

  • โœ… Each service owns its database
  • โœ… Access data only through service APIs
  • โŒ Never share databases between services
  • โŒ No direct database access from other services

Data Consistency Patterns

PatternUse CaseComplexityConsistency
Strong ConsistencyFinancial transactionsHighImmediate
Eventual ConsistencyUser profilesMediumDelayed
Saga PatternMulti-service workflowsHighCompensating
Event SourcingAudit trailsHighEvent-based

CQRS Decision Tree

Need different read/write models? โ†’ Yes โ†’ Consider CQRS
High read/write ratio? โ†’ Yes โ†’ Consider CQRS
Complex queries? โ†’ Yes โ†’ Consider CQRS
Simple CRUD? โ†’ No โ†’ Skip CQRS

๐Ÿ›ก๏ธ Resilience Patterns

Essential Resilience Patterns

PatternPurposeWhen to Use
Circuit BreakerPrevent cascade failuresExternal service calls
RetryHandle transient failuresNetwork operations
TimeoutPrevent hanging requestsAll remote calls
BulkheadIsolate resourcesCritical vs non-critical
FallbackGraceful degradationUser-facing features

Circuit Breaker States

CLOSED โ†’ Normal operation
OPEN โ†’ Failing fast (no calls)
HALF-OPEN โ†’ Testing recovery

Retry Strategy

# Exponential backoff with jitter
delay = base_delay * (2 ** attempt) + random_jitter
max_attempts = 3

๐Ÿ” Service Discovery

Discovery Patterns

PatternProsConsBest For
Client-SideSimple, fastClient complexityInternal services
Server-SideClient simplicityAdditional hopExternal clients
Service MeshRich featuresOperational complexityLarge deployments

Health Check Endpoints

GET /health
{
  "status": "UP",
  "checks": {
    "database": "UP",
    "external-service": "DOWN"
  }
}

๐Ÿ” Security Patterns

Authentication & Authorization

API Gateway โ†’ JWT Validation โ†’ Service Authorization

Security Checklist

  • Use HTTPS everywhere
  • Implement JWT token validation
  • Apply principle of least privilege
  • Secure service-to-service communication
  • Implement rate limiting
  • Log security events

JWT Token Structure

{
  "header": {
    "alg": "RS256",
    "typ": "JWT"
  },
  "payload": {
    "sub": "user123",
    "iat": 1516239022,
    "exp": 1516242622,
    "roles": ["user", "admin"]
  }
}

๐Ÿ“Š Observability

Three Pillars of Observability

  1. Metrics โ†’ What is happening?
  2. Logs โ†’ Why is it happening?
  3. Traces โ†’ Where is it happening?

Essential Metrics

TypeExamplesPurpose
BusinessOrders/minute, RevenueBusiness health
ApplicationResponse time, Error rateApp performance
InfrastructureCPU, Memory, DiskResource usage

Distributed Tracing

Request ID: 12345
โ”œโ”€โ”€ Service A (10ms)
โ”œโ”€โ”€ Service B (50ms)
โ”‚   โ”œโ”€โ”€ Database Query (30ms)
โ”‚   โ””โ”€โ”€ External API (15ms)
โ””โ”€โ”€ Service C (25ms)

Log Levels

ERROR โ†’ System errors, exceptions
WARN โ†’ Potential issues, degraded performance
INFO โ†’ Important business events
DEBUG โ†’ Detailed diagnostic information

๐Ÿš€ Deployment Patterns

Deployment Strategies Comparison

StrategyDowntimeRiskComplexityRollback
Blue-GreenNoneLowMediumInstant
CanaryNoneVery LowHighGradual
RollingNoneMediumLowGradual
RecreateYesHighLowManual

Container Best Practices

# Multi-stage build
FROM node:16-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:16-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY . .
EXPOSE 3000
USER node
CMD ["npm", "start"]

Kubernetes Deployment

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-service
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
  template:
    spec:
      containers:
      - name: my-service
        image: my-service:v1.0
        ports:
        - containerPort: 8080
        readinessProbe:
          httpGet:
            path: /health
            port: 8080
        livenessProbe:
          httpGet:
            path: /health
            port: 8080

๐Ÿงช Testing Strategies

Testing Pyramid for Microservices

    /\
   /  \  E2E Tests (Few)
  /____\
 /      \ Integration Tests (Some)
/__________\ Unit Tests (Many)

Test Types

Test TypeScopeSpeedCostPurpose
UnitSingle functionFastLowLogic validation
IntegrationService boundariesMediumMediumInterface validation
ContractAPI contractsFastLowAPI compatibility
E2EFull workflowSlowHighUser journey validation

Contract Testing

# Consumer contract
interactions:
- description: "Get user by ID"
  request:
    method: GET
    path: /users/123
  response:
    status: 200
    body:
      id: 123
      name: "John Doe"

โš ๏ธ Anti-Patterns to Avoid

Common Anti-Patterns

Anti-PatternDescriptionSolution
Distributed MonolithTightly coupled servicesProper service boundaries
Chatty ServicesToo many service callsCoarser-grained interfaces
Shared DatabaseMultiple services, one DBDatabase per service
Lack of AutomationManual deploymentsCI/CD pipelines
Premature DecompositionToo many small servicesStart with monolith

Warning Signs

๐Ÿšจ Red Flags:

  • Services always deployed together
  • Frequent cross-service database queries
  • Cascading failures
  • Long deployment times
  • Difficulty tracing requests

๐Ÿ“ Sizing Guidelines

Service Size Indicators

Too Small (Nano-service):

  • Single function services
  • High communication overhead
  • Difficult to maintain

Too Large (Mini-monolith):

  • Multiple business capabilities
  • Large team required
  • Difficult to deploy independently

Just Right:

  • Single business capability
  • Owned by one team
  • Independently deployable
  • Clear boundaries

Team Size Rule

Team Size = 2-8 people (Amazon's "Two Pizza Rule")
Services per Team = 1-3 services

๐Ÿ”ง Technology Stack Recommendations

Java Ecosystem:

Spring Boot + Spring Cloud
Netflix OSS (Eureka, Hystrix, Zuul)
Apache Kafka + Docker + Kubernetes

Node.js Ecosystem:

Express.js + Consul
RabbitMQ + Docker + Kubernetes

Polyglot Approach:

API Gateway: Kong/Ambassador
Service Mesh: Istio/Linkerd
Monitoring: Prometheus + Grafana
Logging: ELK Stack

๐Ÿ“‹ Decision Checklists

Microservices Readiness Checklist

Organizational Readiness:

  • DevOps culture and practices
  • Automated testing and deployment
  • Monitoring and alerting capabilities
  • Team autonomy and ownership
  • Failure handling processes

Technical Readiness:

  • Container orchestration platform
  • Service discovery mechanism
  • API gateway solution
  • Distributed tracing system
  • Centralized logging

Service Boundary Checklist

  • Aligns with business capability
  • Can be owned by single team
  • Has clear data ownership
  • Minimal dependencies on other services
  • Can be deployed independently

๐ŸŽฏ Quick Wins

Start Here (Low Risk, High Value)

  1. Extract Read-Only Services: Start with services that only read data
  2. Implement API Gateway: Centralize cross-cutting concerns
  3. Add Health Checks: Enable better monitoring and deployment
  4. Implement Circuit Breakers: Improve system resilience
  5. Centralize Logging: Improve observability

Avoid These Initially (High Risk)

  1. Distributed Transactions: Complex and error-prone
  2. Event Sourcing: High complexity for beginners
  3. Fine-Grained Services: Start coarser, refine later
  4. Custom Service Mesh: Use proven solutions first

๐Ÿ“š Essential Resources

Must-Read Books

  1. "Building Microservices" - Sam Newman
  2. "Microservices Patterns" - Chris Richardson
  3. "Domain-Driven Design" - Eric Evans

Key Websites

  • microservices.io - Pattern catalog
  • 12factor.net - Application methodology
  • martinfowler.com - Architecture insights

Tools to Evaluate

  • API Gateways: Kong, Ambassador, Zuul
  • Service Mesh: Istio, Linkerd, Consul Connect
  • Monitoring: Prometheus, Grafana, Jaeger
  • Orchestration: Kubernetes, Docker Swarm

๐Ÿ†˜ Troubleshooting Guide

Common Issues and Solutions

ProblemSymptomsSolution
Cascade FailuresMultiple services failingImplement circuit breakers
Slow ResponsesHigh latencyAdd caching, optimize queries
Data InconsistencyStale dataImplement eventual consistency
Deployment IssuesFailed deploymentsImprove health checks
Monitoring GapsUnknown system stateAdd distributed tracing

Performance Optimization

  1. Cache Frequently Accessed Data
  2. Use Async Communication Where Possible
  3. Implement Connection Pooling
  4. Optimize Database Queries
  5. Use CDN for Static Content

This quick reference is designed to be printed or bookmarked for easy access during development. For detailed explanations, refer to the full chapters in this book.

Last Updated: February 2026