Skip to content
10 Essential Microservices Design Patterns: Pros, Cons & When to Use Each

10 Essential Microservices Design Patterns: Pros, Cons & When to Use Each

This article details ten core microservices design patterns — including Database per Service, Event Sourcing, CQRS, Saga, BFF, API Gateway, Strangler, Circuit Breaker, Externalized Configuration, and Consumer-Driven Contract Testing — with pros, cons, use cases, and technology examples for each.

Architect's Guide
Architect's Guide
Architect's Guide

Microservices Architecture Overview

Microservices architecture vertically decomposes a large complex system into smaller, independently deployable sub‑processes that communicate via lightweight synchronous (REST, gRPC) or asynchronous (messaging) network calls. Unlike modular monoliths or SOA, services are split by business capability, have external boundaries, and communicate over the network without smart channels.

Key Characteristics

Application split into independent sub‑processes with internal modules

Vertical decomposition by business domain

Services communicate via network calls (RPC or messaging)

Each service is an independently deployable process

Lightweight communication, no intelligent middleware

Advantages

Better development scale

Faster development velocity

Supports iterative and incremental modernization

Leverages cloud, containers, DevOps, serverless

Enables horizontal and fine‑grained scaling

Reduces cognitive load per developer

Disadvantages

Higher number of moving parts (services, databases, containers, frameworks)

Complexity shifts from code to infrastructure

Significant increase in RPC calls and network traffic

Security management becomes more challenging

Overall system design is harder

Introduces distributed‑system complexity

When to Use Microservices

Large‑scale web applications

Cross‑team enterprise collaboration

Long‑term benefits outweigh short‑term costs

Team has architects or senior engineers skilled in microservice design

Ten Core Design Patterns

1. Database per Microservice

Each microservice owns its data store (logical isolation — separate tables, collections, or schemas; physical sharing is allowed). This avoids tight coupling at the database layer, which would undermine independent deployment and team autonomy.

Database per Microservice diagram
Database per Microservice diagram

Pros:

Data fully owned by the service

Reduced coupling between development teams

Cons:

Cross‑service data sharing becomes harder

Application‑wide ACID transactions are difficult

Splitting a monolithic database is a complex task

When to use: Large enterprise apps; teams need full control for scale and speed.

When not to use: Small applications; single team owns all services.

Technology examples: All SQL and NoSQL databases support logical separation (separate tables, collections, schemas).

2. Event Sourcing

Instead of storing current entity state, every state‑changing event is persisted as an immutable sequence. Services reconstruct state by replaying events. This provides atomicity in high‑scale distributed scenarios where two‑phase commit (2PC) does not scale (relational) or is unsupported (NoSQL).

Event Sourcing diagram
Event Sourcing diagram

Pros:

Atomic operations for highly scalable systems

Automatic audit trail with temporal queries

Loose coupling, event‑driven microservices

Cons:

Reading entity state requires replaying events; often needs CQRS

Increases overall complexity; typically requires Domain‑Driven Design

Must handle duplicate (idempotency) or lost events

Event schema evolution is challenging

When to use: High‑scale transactional systems with relational or NoSQL databases; resilient, scalable microservices; event‑driven domains (e‑commerce, booking).

When not to use: Low‑scale transactional systems on SQL; simple microservices with synchronous APIs.

Technology examples: Event stores: EventStoreDB, Apache Kafka, Confluent Cloud, AWS Kinesis, Azure Event Hub, GCP Pub/Sub, Azure Cosmos DB, MongoDB, Cassandra, Amazon DynamoDB. Frameworks: Lagom, Akka, Spring, akkatecture, Axon, Eventuate.

3. Command Query Responsibility Segregation (CQRS)

Separates write (command) and read (query) models. Simple CQRS uses different entity/ORM models for reads and writes. Advanced CQRS uses separate data stores: write store is the system of record (OLTP, ACID), read store is optimized for queries (denormalized, search‑oriented). Data is asynchronously replicated from write to read store, resulting in eventual consistency.

Simple CQRS diagram
Simple CQRS diagram
Advanced CQRS diagram
Advanced CQRS diagram

Pros:

Faster reads in event‑driven microservices

High data availability

Read and write systems scale independently

Cons:

Read store is eventually consistent (weak consistency)

Increased complexity; poorly implemented CQRS can harm the project

When to use: Event Sourcing in scalable microservices; complex domain models querying multiple stores; systems with disparate read/write loads.

When not to use: When event snapshots suffice; read/write loads are similar.

Technology examples: Write stores: EventStoreDB, Kafka, Confluent Cloud, Kinesis, Azure Event Hub, GCP Pub/Sub, Cosmos DB, MongoDB, Cassandra, DynamoDB. Read stores: Elasticsearch, Solr, Cloud Spanner, Amazon Aurora, Cosmos DB, Neo4j. Frameworks: Lagom, Akka, Spring, akkatecture, Axon, Eventuate.

4. Saga

A sequence of local transactions, each executed within a single microservice and publishing an event/message. The first transaction is triggered externally; each subsequent transaction is triggered by the previous event. If a step fails, compensating transactions roll back prior changes. Two coordination styles:

Choreography: decentralized, services listen to each other's events

Orchestration: centralized coordinator directs participants

Saga pattern diagram
Saga pattern diagram

Pros:

Consistent transactions for scalable, loosely coupled, event‑driven microservices

Works with NoSQL databases that lack 2PC support

Cons:

Must handle transient faults and ensure idempotency

Debugging is hard; complexity grows with service count

When to use: Scalable, loosely coupled microservices using Event Sourcing; systems with distributed NoSQL databases.

When not to use: Low‑scale transactional systems on relational databases; services with cyclic dependencies.

Technology examples: Axon, Eventuate, Narayana.

5. Backend for Frontend (BFF)

Creates a dedicated backend per user interface (Web, Mobile, Smart TV, Desktop) to tailor APIs to each client's screen size, performance, bandwidth, and security needs. BFF also shields downstream microservices, reducing chatty client‑to‑service communication and adding a security layer for services in a DMZ.

BFF pattern diagram
BFF pattern diagram

Pros:

Separates concerns per UI, enabling client‑specific optimization

Improves security

Reduces frequent UI‑to‑microservice calls

Cons:

Code duplication across BFFs

Many BFFs needed for multiple UIs

Must avoid business logic in BFF; only client‑specific logic allowed

When to use: Multiple UIs with different API needs; security requires extra layer between UI and downstream services; micro‑frontend architectures.

When not to use: Multiple UIs sharing the same API; core microservices not in DMZ.

Technology examples: Any backend framework (Node.js, Spring, Django, Laravel, Flask, Play, etc.).

6. API Gateway

Acts as a facade between clients and backend microservices. Routes requests, fans out to multiple services, aggregates responses, and handles cross‑cutting concerns: SSL termination, authentication, authorization, rate limiting, logging, monitoring, load balancing.

API Gateway diagram
API Gateway diagram

Pros:

Decouples frontend from backend services

Reduces client‑to‑microservice call count

Centralized security (SSL, auth, authz)

Centralized cross‑cutting concerns (logging, monitoring, throttling, load balancing)

Cons:

Potential single point of failure

Added network hop increases latency

Can become a bottleneck if not scaled

Additional development and maintenance overhead

When to use: Complex microservice architectures (almost mandatory); large enterprises needing centralized security and cross‑cutting concerns.

When not to use: Personal projects or small companies where security and centralization are low priority; very few microservices.

Technology examples: Amazon API Gateway, Azure API Management, Apigee, Kong, WSO2 API Manager.

7. Strangler Fig

Incrementally migrates a legacy monolith to microservices by gradually replacing specific functions with new services. New features are built only as microservices. An API Gateway (facade) routes requests to either the monolith or the new services. Once all functions are migrated, the monolith is retired.

Strangler Fig pattern diagram
Strangler Fig pattern diagram

Pros:

Safe migration of live monolith to microservices

Parallel migration of existing features and new development

Controlled migration pace

Cons:

Data sharing between monolith and new services is challenging

Facade (API Gateway) adds latency

End‑to‑end testing becomes difficult

When to use: Incremental migration of large backend monoliths.

When not to use: Small monoliths where big‑bang rewrite is feasible; unable to intercept client requests to the legacy app.

Technology examples: API Gateway plus backend frameworks.

8. Circuit Breaker

Prevents cascading failures when a downstream service is unavailable. A proxy tracks recent failures; if failures exceed a threshold, the circuit opens and calls fail fast. After a timeout, it enters half‑open state allowing a few test requests; success closes the circuit, failure reopens it. Three states:

Closed: normal operation, requests routed, failures counted

Open: requests fail fast, return exception; after timeout enters half‑open

Half‑Open: limited test requests allowed; success closes circuit, failure reopens

Circuit Breaker state diagram
Circuit Breaker state diagram

Pros:

Improves fault tolerance and resilience

Stops cascading failures across services

Cons:

Requires sophisticated exception handling

Needs logging and monitoring

Should support manual reset

When to use: Tightly coupled microservices with synchronous communication; services depending on multiple other services.

When not to use: Loosely coupled, event‑driven architectures; services with no downstream dependencies.

Technology examples: API Gateway, Service Mesh, libraries (Hystrix, Resilience4j, Polly).

9. Externalized Configuration

All configuration parameters (database URLs, service endpoints, credentials, certificates) are kept outside the codebase and injected at runtime via environment variables or config servers. This separates build from deployment, minimizes security risk (production secrets not in source control), and allows changes without rebuilding.

Pros:

Production config not in codebase, reducing security exposure

Configuration changes without rebuild

Cons:

Requires a framework that supports externalized configuration

When to use: Any production‑grade application.

When not to use: Proof‑of‑concept or prototype development.

Technology examples: Nearly all modern enterprise frameworks support externalized configuration.

10. Consumer‑Driven Contract Testing

Consumer teams write test suites (contracts) specifying expected requests and responses for each provider service. Provider runs these contracts in its CI pipeline. Detects breaking API/message changes early, improves robustness in large multi‑team environments, and enhances team autonomy.

Pros:

Fast automated detection of provider API/message changes

Fewer surprises, more robust large‑scale systems

Improves team autonomy

Cons:

Extra effort to develop and integrate contracts (different test tools)

Contracts may drift from real provider behavior, risking production failures

When to use: Large enterprise apps with multiple teams owning different services.

When not to use: Small apps with single‑team ownership; stable provider APIs not under active development.

Technology examples: Pact, Postman, Spring Cloud Contract.

Summary

Microservices architecture enables development scale and long‑term benefits but is not a silver bullet. The foundational pattern is Database per Microservice, which demands supporting patterns like Event Sourcing, CQRS, and Saga. For multi‑client applications (Web, Mobile, Desktop, Smart Devices), BFF and API Gateway manage communication volume and unified security. Circuit Breaker handles fault tolerance in synchronous call chains. Strangler Fig enables safe legacy migration. Consumer‑Driven Contract Testing is essential for integration testing in multi‑team settings. Externalized Configuration is mandatory for any modern production system. This list is not exhaustive but provides a strong introduction to microservice design patterns.

Code example

·················END·················
资料链接
清华学姐自学的Linux笔记,天花板级别!
新版鸟哥Linux私房菜资料
阿里大佬总结的《图解Java》火了,完整版PDF开放下载!
Alibaba官方上线!SpringBoot+SpringCloud全彩指南
国内最强的SpringBoot+Vue全栈项目天花板,不接受反驳!
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

design patternsmicroservicesAPI GatewaycqrsCircuit Breakerevent-sourcingSagadatabase-per-service
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.