Microservice Architecture Design Patterns

This article introduces key microservice architecture design patterns—including Database per Service, Event Sourcing, CQRS, Saga, BFF, API Gateway, Strangler, Circuit Breaker, Externalized Configuration, and Consumer‑Driven Contract Testing—explaining their advantages, drawbacks, appropriate usage scenarios, and example technologies to guide scalable, resilient system design.

Architecture Digest
Architecture Digest
Architecture Digest
Microservice Architecture Design Patterns

Microservice Architecture Design Patterns

Software design patterns provide reusable solutions to common problems in system design. In the context of microservice architectures, a collection of patterns helps teams build scalable, maintainable, and resilient applications.

Database per Microservice (独享数据库)

Each microservice owns its own logical data store, avoiding strong coupling at the database layer. Physical databases may be shared, but data structures are isolated.

Advantages

Data is fully owned by the service.

Reduced coupling between development teams.

Disadvantages

Data sharing between services becomes more challenging.

Maintaining ACID transactions across services is difficult.

Designing the split of a monolithic database requires careful planning.

When to Use

Large enterprise applications.

When teams need full control to scale development speed.

When Not to Use

Small‑scale applications.

Single‑team ownership of all services.

Technology Examples

Any SQL or NoSQL database that supports logical separation (separate tables, collections, schemas, or databases).

Event Sourcing (事件源)

Instead of persisting only the current state, every state‑changing event is stored immutably, allowing services to reconstruct state by replaying events.

Advantages

Provides atomic operations for highly scalable systems.

Automatically records a complete change history.

Enables loosely coupled, event‑driven microservices.

Disadvantages

Reading the current state requires replaying events (often via CQRS).

Increases overall system complexity and typically needs DDD.

Handling duplicate or missing events adds operational burden.

Changing event schemas is challenging.

When to Use

High‑throughput, transactional systems using relational or NoSQL databases.

Event‑driven architectures such as e‑commerce or booking systems.

When Not to Use

Low‑scale transactional systems on traditional SQL databases.

Simple microservices that can synchronously exchange data via 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.

Command Query Responsibility Segregation – CQRS (命令和查询职责分离)

CQRS separates write (command) and read (query) models, often combined with Event Sourcing. Simple form uses separate ORM models; advanced form employs distinct data stores for reads and writes.

Advantages

Faster reads in event‑driven microservices.

Higher data availability.

Independent scaling of read and write sides.

Disadvantages

Read store may be eventually consistent.

Overall system complexity increases.

When to Use

High‑scale microservices using Event Sourcing.

Complex domain models requiring multiple data stores for reads.

Systems with significantly different read/write load patterns.

When Not to Use

When snapshotting the event store is sufficient.

When read and write loads are similar.

Technology Examples

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

Saga (事务补偿模式)

Saga coordinates a series of local transactions across microservices, each publishing an event upon completion. If a transaction fails, compensating transactions roll back prior changes.

Advantages

Provides consistency for highly scalable, loosely coupled systems.

Works with non‑relational databases that lack 2PC support.

Disadvantages

Requires handling of transient failures and idempotency.

Debugging becomes harder as the number of services grows.

When to Use

High‑scale, loosely coupled microservices using Event Sourcing.

Systems built on distributed NoSQL databases.

When Not to Use

Low‑scale transactional systems on relational databases.

Simple microservices with synchronous API calls.

Technology Examples

Axon, Eventuate, Narayana.

Backend‑for‑Frontend (BFF) (面向前端的后端)

BFF provides a dedicated backend for each UI (Web, Mobile, etc.), allowing UI‑specific optimizations, security isolation, and reduced chatter between UI and downstream services.

Advantages

Separates concerns per UI, enabling tailored optimizations.

Improves security.

Reduces frequent communication with downstream services.

Disadvantages

Potential code duplication across BFFs.

Many BFFs may be needed for various client types.

Requires careful design to keep business logic out of the BFF.

When to Use

Multiple UIs with differing API requirements.

Security‑sensitive scenarios needing an extra layer.

Micro‑frontend architectures.

When Not to Use

Multiple UIs that share the same API.

Core services not deployed in a DMZ.

Technology Examples

Any backend framework (Node.js, Spring, Django, Laravel, Flask, Play, …).

API Gateway (API 网关)

An API Gateway sits between clients and microservices, acting as a façade, routing requests, aggregating responses, and handling cross‑cutting concerns such as SSL termination, authentication, rate limiting, and logging.

Advantages

Decouples front‑end from back‑end services.

Reduces the number of client‑to‑service calls.

Provides centralized security and cross‑cutting concerns.

Enables unified logging, monitoring, and throttling.

Disadvantages

Can become a single point of failure.

Introduces additional network latency.

May become a performance bottleneck if not scaled.

Increases maintenance and development cost.

When to Use

Complex microservice landscapes where a façade is essential.

Large enterprises needing centralized security and management.

When Not to Use

Small projects or startups where security and centralization are not priorities.

When the number of microservices is very low.

Technology Examples

Amazon API Gateway, Azure API Management, Apigee, Kong, WSO2 API Manager.

Strangler (分层迁移模式)

The Strangler pattern incrementally replaces parts of a monolithic application with new microservices, routing traffic via a façade (often an API Gateway) until the legacy system can be retired.

Advantages

Safe migration from monolith to microservices.

Allows parallel development of new features.

Provides better control over migration pace.

Disadvantages

Sharing data stores between legacy and new services is challenging.

Adding a façade adds latency.

End‑to‑end testing becomes more complex.

When to Use

Incrementally migrating a large backend monolith.

When Not to Use

Small monoliths where a full rewrite is simpler.

When you cannot intercept client traffic to the legacy system.

Technology Examples

API gateway frameworks and backend application frameworks.

Circuit Breaker (断路器)

Circuit Breaker protects a microservice from cascading failures by monitoring error rates and short‑circuiting calls when a threshold is exceeded, transitioning through Closed, Open, and Half‑Open states.

Advantages

Improves fault tolerance and resilience.

Prevents cascading failures.

Disadvantages

Requires sophisticated exception handling.

Needs proper logging, monitoring, and manual reset mechanisms.

When to Use

Synchronous, tightly‑coupled microservice communication.

When a service depends on multiple downstream services.

When Not to Use

Event‑driven, loosely coupled architectures.

When a service has no external dependencies.

Technology Examples

API gateways, service meshes, libraries such as Hystrix, Resilience4j, Polly.

Externalized Configuration (外部化配置)

Externalizing configuration separates build artifacts from environment‑specific settings, reducing security risks and eliminating the need to rebuild applications for configuration changes.

Advantages

Configuration is not stored in code repositories, reducing security exposure.

Changes can be applied without rebuilding the application.

Disadvantages

Requires a framework that supports externalized configuration.

When to Use

Any production‑grade application.

When Not to Use

Proof‑of‑concept or throw‑away prototypes.

Technology Examples

Virtually all modern enterprise frameworks provide support.

Consumer‑Driven Contract Testing (消费端驱动的契约测试)

Consumer‑driven contracts let consumer teams define expected request/response pairs, which providers then verify in their automated test suites, ensuring API compatibility across teams.

Advantages

Detects breaking changes quickly.

Improves robustness in large enterprise applications.

Enhances team autonomy.

Disadvantages

Additional effort to develop and integrate contracts.

Potential mismatch between contracts and real services can cause production failures.

When to Use

Large enterprise applications with multiple independently developed services.

When Not to Use

Small, single‑team applications.

When provider services are stable and rarely change.

Technology Examples

Pact, Postman, Spring Cloud Contract.

Conclusion

Microservice architecture offers scalability and long‑term benefits but is not a universal silver bullet. Teams should adopt proven design patterns—Database per Service, Event Sourcing, CQRS, Saga, BFF, API Gateway, Circuit Breaker, Strangler, Consumer‑Driven Contract Testing, and Externalized Configuration—to build robust, maintainable systems.

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 PatternsDistributed SystemsBackend ArchitectureScalability
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
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.