Microservice Design Patterns: Decomposition, Integration, Data, and Observability Strategies
This article systematically categorizes and explains core microservice design patterns across decomposition, integration, database, event-driven, observability, and cross-cutting concerns, providing practical guidance for architects building resilient, scalable distributed systems.
Decomposition Patterns
Decomposition patterns define how to break a monolith or greenfield application into loosely coupled services.
Decompose by Business Capability
Apply the Single Responsibility Principle: define services that map to business capabilities — value-creating activities such as Order Management or Customer Management. Each capability typically corresponds to a business object.
Decompose by Subdomain (DDD)
When business-capability decomposition hits a "god class" shared across services, use Domain-Driven Design subdomains. Subdomains fall into three types: Core (competitive advantage), Supporting (related but not core, can be outsourced), and Generic (not business-specific, use off-the-shelf software). Example: an Order Management subdomain may contain Product Catalog, Inventory Management, Order Management, and Delivery Management services.
Decompose by Transaction / Two-Phase Commit (2PC)
Services are split along transaction boundaries. A transaction coordinator orchestrates a prepare phase (participants vote ready) and a commit/rollback phase. However, 2PC is slow compared to single-service latency and unsuitable for high-load scenarios.
Strangler Fig Pattern
For brownfield (legacy monolith) migrations, run a new refactored application alongside the old one in the same URI space. Gradually redirect traffic: Transform (build new), Coexist (redirect incrementally), Eliminate (remove old functionality).
Bulkhead Pattern
Isolate service instances into groups by load and availability requirements, analogous to ship compartments. Failures in one bulkhead do not cascade, preserving service for other consumers.
Sidecar Pattern
Deploy auxiliary components (logging, monitoring, proxy) in a separate container alongside the main application. The sidecar shares the parent's lifecycle and provides cross-cutting functionality without polluting the main codebase.
Integration Patterns
These patterns address how decomposed services communicate and compose responses.
API Gateway Pattern
A single entry point for all clients. It routes requests to appropriate services, aggregates responses, translates protocols, provides per-client fine-grained APIs, and handles authentication/authorization. Solves problems of multiple round-trips, protocol heterogeneity, and varying response formats.
Aggregator Pattern
Combines data from multiple services before returning to the consumer. Two implementations: a composite microservice that calls and merges data, or the API Gateway itself performing aggregation. Use a composite service when business logic is needed; otherwise the gateway is the de facto standard.
Proxy Pattern
The API Gateway exposes different API modules for different consumers (e.g., Mobile API, Browser API, Public API) while backing onto the same underlying services.
Gateway Routing Pattern
The gateway maintains a routing map (HTTP method + path → service URL) and forwards requests accordingly, functioning like a reverse proxy (e.g., NGINX).
Chained Microservice Pattern
Services call each other synchronously in a linear chain (e.g., Sales → Product → Order). The initial service returns a consolidated response after all downstream calls complete.
Branch Pattern
A hybrid of Aggregator and Chain: a service fans out to multiple parallel chains or single services simultaneously, then merges results. Enables conditional invocation of different chains based on business needs.
Client-Side UI Composition Pattern
The UI is built as a Single Page Application (SPA) composed of independent screen areas, each fetching data from its own backend service. Frameworks like AngularJS or ReactJS facilitate this; each team owns a UI component (e.g., an Angular directive) for its service.
Database Patterns
Data ownership must align with service boundaries to preserve loose coupling.
Database per Service
Each service owns a private database accessible only via its API. Implementation options: private tables per service, schema per service, or database server per service. This ensures independent development, deployment, and scaling.
Shared Database (Anti-pattern for Greenfield)
Multiple services share a single database. Considered an anti-pattern for new systems but a pragmatic stepping stone when decomposing a legacy monolith where denormalization is hard. Should be migrated to database-per-service over time.
Command Query Responsibility Segregation (CQRS)
After adopting database-per-service, cross-service queries become impossible. CQRS splits the application into a Command side (handles creates, updates, deletes) and a Query side (serves reads via materialized views). Often paired with Event Sourcing: every state change emits an event; subscribers update materialized views to keep them current.
Event-Driven Patterns
Replace CRUD state mutation with an append-only event log.
Event Sourcing
Instead of storing current state, persist a sequence of events (e.g., AddedItemToOrder) in an event store. Events are the system of record. Materialized views are rebuilt by replaying events; external systems integrate by subscribing to the event stream.
Saga Pattern
Manages distributed transactions across services with private databases. Each step has a compensating action for rollback. Two coordination styles:
Choreography : Services emit and listen to events without a central coordinator. Suitable when participants span control/visibility domains (like network protocols).
Orchestration : A central orchestrator directs the sequence and invokes compensations. Used when all participants are within a single control domain.
Observability Patterns
Essential for operating distributed systems.
Log Aggregation
Centralized logging service collects structured logs from all instances. Enables search, analysis, and alerting (e.g., PCF Loggregator, AWS CloudWatch).
Performance Metrics
Collect and aggregate metrics per service for monitoring and alerting. Two models: Push (service sends to collector like NewRelic, AppDynamics) and Pull (collector scrapes from service like Prometheus).
Distributed Tracing
Assign a unique trace ID to each external request, propagate it across all services, and include it in every log entry. Enables end-to-end request tracking for debugging.
Health Check
Each service exposes a /health endpoint that verifies host status, downstream connectivity, and custom logic. Allows infrastructure to detect unhealthy instances that are running but unable to process requests.
Cross-Cutting Concern Patterns
External Configuration
Store environment-specific configuration (URLs, credentials) outside the codebase. Load at startup or refresh at runtime without rebuild/redeploy.
Service Discovery
Dynamic IP assignment in containerized environments breaks static consumer URLs. A service registry holds producer metadata. Instances register on startup, deregister on shutdown. Two types: Client-side (e.g., Netflix Eureka) and Server-side (e.g., AWS ALB).
Circuit Breaker Pattern
Calls to remote services go through a proxy that trips after a failure threshold. During the timeout, calls fail fast. After timeout, a few test requests are allowed; success restores normal operation, failure restarts the timeout. Prevents cascading failures and resource exhaustion.
Blue-Green Deployment
Run two identical production environments (Blue and Green). Only one serves live traffic. Deploy new version to the idle environment, verify, then switch traffic. Enables zero-downtime releases and instant rollback. Supported by all major cloud platforms.
Code example
最近面试BAT,整理一份面试资料
《
Java面试BAT通关手册
》
,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
获取方式:点“
在看
”,关注公众号并回复
手册
领取,更多内容陆续奉上。
明天见(。・ω・。)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
