Top Microservice Design Patterns: Database per Service, Event Sourcing, CQRS, Saga

This article reviews essential microservice design patterns—including Database per Service, Event Sourcing, CQRS, Saga, Backend‑for‑Frontend, API Gateway, Strangler, Circuit Breaker, Externalized Configuration, and Consumer‑Driven Contract Testing—explaining their advantages, drawbacks, when to apply them, and common technology implementations.

21CTO
21CTO
21CTO
Top Microservice Design Patterns: Database per Service, Event Sourcing, CQRS, Saga

Microservice Architecture Design Patterns

Software design patterns provide reusable solutions to common problems, allowing teams to share vocabulary and avoid reinventing the wheel.

Database per Microservice

When migrating a monolith to microservices, the most critical decision is the database strategy. Keeping a single central database creates strong coupling and can cause migration failure at scale. A better approach is to give each microservice its own logical data store—services may share a physical database but must use separate schemas, tables, or collections to maintain domain‑driven boundaries.

Database per Microservice diagram
Database per Microservice diagram

Advantages

Data is fully owned by the service.

Coupling between development teams is reduced.

Disadvantages

Data sharing between services becomes more challenging.

Maintaining ACID transactions across services is difficult.

Designing how to split the monolithic database is complex.

When to use

Large enterprise applications.

Teams need full control of services to scale development speed.

When not to use

Small‑scale applications.

All microservices are developed by a single team.

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

Event Sourcing

In microservices that use dedicated databases, services must exchange data asynchronously. For highly scalable, fault‑tolerant systems, atomic operations that update a database and publish a message are needed, but traditional two‑phase commit does not scale. Event sourcing stores every state‑changing event instead of the current entity state, allowing services to reconstruct state by replaying events.

Event sourcing diagram
Event sourcing diagram

Advantages

Provides atomic operations for highly scalable systems.

Automatically records entity change history with time‑travel capability.

Enables loosely coupled, event‑driven microservices.

Disadvantages

Reading entities from the event store is more complex and often requires additional storage (CQRS).

System complexity increases, typically requiring domain‑driven design.

Handling duplicate or lost events and evolving event schemas adds challenges.

When to use

High‑throughput transactional systems using relational or NoSQL databases.

Event‑driven, highly scalable microservice architectures.

Typical messaging‑driven use cases such as e‑commerce or reservation systems.

When not to use

Low‑scalability transactional systems based on SQL.

Simpler microservices where synchronous API calls suffice.

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

Command Query Responsibility Segregation (CQRS)

If event sourcing is used, reading data from the event store becomes difficult. CQRS separates the write side (commands) from the read side (queries). In its simple form, separate models are used for reads and writes; in the advanced form, distinct data stores are employed, often combined with event sourcing.

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

Write stores handle high‑throughput, scalable writes (e.g., EventStoreDB, Kafka, DynamoDB). Read stores are optimized for queries (e.g., Elasticsearch, Solr, Cloud Spanner, Aurora, Neo4j).

Advantages

Faster reads in event‑driven microservices.

Higher data availability.

Independent scaling of read and write paths.

Disadvantages

Read stores are eventually consistent.

Overall system complexity increases.

When to use

Event‑sourced, highly scalable microservices.

Complex domain models requiring multiple data sources for queries.

Systems with a clear read/write load imbalance.

When not to use

When storing a large number of events is unnecessary; snapshots may suffice.

When read and write loads are similar.

Saga

With dedicated databases, distributed transactions become a challenge because two‑phase commit does not scale for relational or most NoSQL databases. The Saga pattern implements distributed transactions by chaining local transactions that each publish an event; compensating transactions roll back if a step fails.

Saga pattern diagram
Saga pattern diagram

Advantages

Provides consistency for highly scalable, loosely coupled, event‑driven microservices.

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

Disadvantages

Requires handling of transient failures and idempotency.

Debugging is harder and complexity grows with the number of services.

When to use

High‑scalability, loosely coupled microservices that already use event sourcing.

Systems built on distributed NoSQL databases.

When not to use

Low‑scalability transactional systems based on relational databases.

When services have circular dependencies.

Technology examples : Axon, Eventuate, Narayana.

Backend‑for‑Frontend (BFF)

Modern applications often have separate web and mobile clients with different UI requirements. A BFF provides a dedicated backend for each UI, reducing coupling, improving security, and minimizing chatty communication with downstream services.

BFF diagram
BFF diagram

Advantages

Separates concerns, allowing UI‑specific optimizations.

Provides higher security.

Reduces frequent communication between UI and downstream services.

Disadvantages

Potential code duplication across BFFs.

Increased maintenance for many BFFs.

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

When to use

Multiple UIs with distinct API needs.

Security requirements that benefit from an extra layer.

Micro‑frontend architectures.

When not to use

Multiple UIs that share the same API.

Core microservices are not deployed in a DMZ.

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

API Gateway

In microservice architectures, clients often need to call many fine‑grained services. An API gateway acts as a façade, routing requests, handling cross‑cutting concerns (SSL termination, authentication, rate limiting, logging), and optionally aggregating responses.

API gateway diagram
API gateway diagram

Advantages

Provides loose coupling between front‑end and back‑end services.

Reduces the number of client‑to‑service calls.

Enables centralized security, logging, monitoring, throttling, and load balancing.

Disadvantages

Can become a single point of failure.

Additional network hop adds latency.

May become a 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 cross‑cutting concerns.

When not to use

Small projects or startups where security and central management 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

To migrate a running monolith to microservices, the Strangler pattern incrementally replaces functionality with new microservices while routing traffic through a façade (often an API gateway). Once all functionality is migrated, the monolith is retired.

Strangler pattern diagram
Strangler pattern diagram

Advantages

Safe migration from monolith to microservices.

Allows parallel development of new features and migration of existing ones.

Provides better control over migration pace.

Disadvantages

Sharing data stores between legacy and new services is challenging.

Introducing a façade adds latency.

End‑to‑end testing becomes more complex.

When to use

Incrementally migrate a large backend monolith to microservices.

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‑based backend frameworks.

Circuit Breaker

Microservices that call each other synchronously can suffer from cascading failures. A circuit breaker monitors recent failures and trips to short‑circuit calls, returning errors quickly and protecting the system.

Circuit breaker states diagram
Circuit breaker states diagram

States

Closed : Requests flow normally; failures are counted.

Open : Requests fail fast; after a timeout the breaker becomes half‑open.

Half‑open : A limited number of requests are allowed; success closes the breaker, failure re‑opens it.

Advantages

Improves fault tolerance and resilience.

Prevents cascading failures.

Disadvantages

Requires sophisticated exception handling and monitoring.

Needs 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.

Services that do not call other services.

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

Externalized Configuration

Embedding configuration (e.g., DB credentials, service URLs) in code is a security risk and forces rebuilds for any change. Externalizing configuration separates build from runtime, keeping production secrets out of the codebase and allowing on‑the‑fly updates.

Advantages

Reduces security exposure by keeping production config out of source control.

Changes to configuration do not require rebuilding the application.

Disadvantages

Requires a framework that supports externalized configuration.

When to use

Any important production application.

When not to use

Proof‑of‑concept or throw‑away projects.

Technology examples : Most modern enterprise frameworks provide this capability.

Consumer‑Driven Contract Testing

When many teams develop microservices, integration testing can be fragile. Consumer‑driven contract tests let consumer teams define expected request/response contracts; provider services run these contracts as part of their automated test suite, ensuring API changes are detected early.

Advantages

Detects unexpected provider changes automatically.

Improves robustness in large, multi‑team applications.

Enhances team autonomy.

Disadvantages

Additional effort to create and maintain contracts.

If contracts diverge from real behavior, production failures may occur.

When to use

Large enterprise applications with many independently developed services.

When not to use

Small applications where all services are owned by a single team.

Stable services that are not under active development.

Technology examples : Pact, Postman, Spring Cloud Contract.

Summary

Microservice architecture can scale large enterprise software, but it is not a universal silver bullet. Teams should follow proven design patterns—Database per Service, Event Sourcing, CQRS, Saga, Backend‑for‑Frontend, API Gateway, Circuit Breaker, Strangler, Consumer‑Driven Contract Testing, and Externalized Configuration—to address common challenges and reap long‑term benefits.

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-gatewayCQRSEvent Sourcingsaga
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

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.