Microservices Patterns
- Decompose a bank or e-commerce domain into services by business capability and subdomain
- Apply database-per-service and query across services without shared tables
- Place API gateway, BFF, service discovery and service mesh correctly in a design
- Choose sync vs async communication per interaction and explain temporal coupling
- Recognize a distributed monolith and the shared-data anti-patterns that cause it
- Use contract testing and Team Topologies to keep services independently deployable
TL;DR
- Decompose by business capability or DDD subdomain, not by technical layer. A service should change for one business reason and be owned by one team.
- Database per service is non-negotiable for independence. Cross-service queries use API composition or a read model built from events — never a shared table.
- API gateway handles cross-cutting edge concerns (TLS, authn, rate limiting, routing); BFF shapes APIs per client (mobile vs web vs partner). Neither should hold business rules.
- Service mesh moves retries, mTLS, traffic shifting and telemetry into sidecars or node proxies — useful at scale, overhead for small fleets.
- Prefer async events between services for anything that does not need an immediate answer; synchronous chains multiply latency and failure probability.
- A distributed monolith (lock-step deploys, shared DB, chatty sync calls) gives you the costs of microservices with none of the benefits.
- Conway's law is real: design team boundaries and service boundaries together (inverse Conway maneuver).
Why it matters
Most microservice failures are not caused by Kubernetes or Kafka; they are caused by wrong boundaries and shared data. A checkout that synchronously calls cart → pricing → promotion → inventory → payment → fraud → loyalty has seven ways to fail on 11.11, and its p99 latency is roughly the sum of seven tails. A bank that splits "accounts" and "transactions" into separate services sharing one Oracle schema cannot deploy either without a joint regression test. Interviewers probe exactly these failure modes: "How would you split this?", "What if the inventory service is down?", "How do you query orders with customer names?"
Core concepts
Decomposition
Two complementary strategies (see Chris Richardson's Microservices Patterns):
- By business capability — what the business does: accept payments, manage catalog, fulfil orders, assess credit. Capabilities are stable over years even when processes change.
- By subdomain — DDD's core, supporting and generic subdomains, with each bounded context a candidate service (see Domain-Driven Design).
Heuristics for the right granularity (Software Architecture: The Hard Parts calls these "disintegrators" and "integrators"):
| Split further when… (disintegrators) | Keep together when… (integrators) |
|---|---|
| Parts change at very different rates | They need a single ACID transaction |
| Parts have very different scaling needs (search vs admin) | They form one tightly coupled workflow |
| Fault isolation matters (recommendations must not take down checkout) | They share a lot of code or a data model |
| Security or compliance scope differs (PCI card vault) | Data relationships are dense and queried together |
| Different teams own them | One team owns both and deploys them together anyway |
Litmus tests: can the service be described in one sentence without "and"? Can one team own it end-to-end? Does a typical feature change touch one service?
Database per service
Each service's data is private; other services access it only through the service's API or the events it publishes. Levels of isolation, from cheapest to strongest: private tables in a shared server → schema per service → database server per service. Pick per risk: the card vault gets its own server and network segment; small supporting services can share a server with separate schemas and credentials.
Querying across services:
- API composition — a BFF or composer calls several services and joins in memory. Simple, but latency and availability depend on all callees.
- CQRS read model — a dedicated service consumes events (OrderPlaced, CustomerRenamed) and maintains a denormalized view for queries such as "orders with customer name and shipment status". Eventually consistent, fast and decoupled. See Event-Driven Architecture.
- Transactions across services use sagas with compensations, not 2PC — see Distributed Transactions — and reliable publishing uses the outbox pattern.
Shared data anti-patterns
- Shared database integration — two services read/write the same tables. Any schema change requires coordinated deploys; locking and performance problems cross service boundaries.
- "Common" domain library — a
shared-modelspackage withOrder,Customerused everywhere. Every change ripples to every service. Share infrastructure code (logging, tracing), not domain models. - Reporting directly from service databases — the BI team queries production schemas. Services lose the freedom to change their schema. Publish events or CDC streams into a warehouse instead.
- Entity service — a "CustomerService" that is just CRUD over a table, called by everyone for everything. It becomes a synchronous bottleneck and a hidden shared database.
Distributed monolith smell
You probably have one if several of these are true:
- Releases require deploying multiple services in a specific order.
- Services share a database schema or a domain-model library.
- A single user request triggers a deep synchronous call chain (more than three or four hops).
- One service's outage takes down unrelated features.
- End-to-end tests on a shared environment are the only way to gain confidence.
- Teams cannot name which team owns a given table.
API gateway and BFF
- API gateway (Kong, Envoy-based gateways, AWS API Gateway, Apigee…): single entry point; TLS termination, authentication (validate JWT/OAuth tokens), coarse authorization, rate limiting and quotas, request routing, WAF integration, request/response logging. See Proxies, Load Balancers & API Gateways.
- Backend for Frontend (BFF): one backend per client experience, owned by the client team. The mobile BFF returns a compact payload tuned for a slow network; the web BFF returns richer data; the partner API exposes a stable, versioned contract. The pattern is associated with Sam Newman and was popularized by teams at SoundCloud.
- Keep business rules out of both. A gateway that computes fees or a BFF that decides stock availability becomes a hidden monolith.
Service discovery
Instances come and go; callers need current addresses.
| Approach | How | Examples |
|---|---|---|
| Server-side discovery | Caller hits a stable virtual address; platform load balances | Kubernetes Service (ClusterIP + DNS), cloud load balancers |
| Client-side discovery | Caller queries a registry and picks an instance itself | Consul, Eureka, gRPC client-side load balancing |
| Mesh-based | Sidecar or node proxy resolves and balances | Istio, Linkerd |
On Kubernetes, server-side discovery via order-service.payments.svc.cluster.local is the default and usually enough. Note that HTTP/2 and gRPC keep long-lived connections, so a plain ClusterIP Service balances connections, not requests — use client-side balancing (headless Service) or a mesh for even request distribution.
Sidecar and service mesh
- Sidecar pattern: deploy a helper process alongside the app in the same pod to provide a capability without changing app code (proxying, log shipping, secret fetching).
- Service mesh: a fleet of proxies (data plane) plus a control plane that provides mTLS between services, traffic policies (retries, timeouts, circuit breaking), traffic shifting for canaries, and uniform telemetry. Istio and Linkerd are the common choices; Istio also offers a sidecar-less "ambient" mode.
- When it pays off: dozens or hundreds of services, polyglot stacks, a zero-trust mandate (common in banks: "all east–west traffic must be mutually authenticated and encrypted").
- When it does not: a handful of Go services that already share a well-built client library. A mesh adds latency per hop (small but non-zero), memory per pod and a complex control plane to operate.
- Careful with retries in two places: if both the app and the mesh retry three times, one failure becomes up to nine (or more) attempts. Decide where retries live; see Resilience Patterns.
Inter-service communication: sync vs async
| Aspect | Synchronous (REST, gRPC) | Asynchronous (events, queued commands) |
|---|---|---|
| Coupling | Temporal: both must be up now | Decoupled in time; broker must be up |
| Latency | Adds to user request | Off the critical path |
| Failure | Propagates upstream; needs timeouts, retries, circuit breakers | Retries and DLQs inside the consumer |
| Consistency | Immediate answer | Eventual; needs idempotent consumers |
| Debugging | Easy with tracing | Harder: correlation IDs, event lineage |
| Use for | Queries needing an immediate answer; authorization decisions | Notifications, projections, downstream workflows, fan-out |
Rules of thumb:
- The user-facing critical path should have few synchronous hops, each with a timeout budget and a fallback.
- Commands vs events: a command ("ReserveStock") has one intended handler and expects an outcome; an event ("OrderPlaced") states a fact and may have many consumers. Do not disguise commands as events.
- Every async consumer must be idempotent — brokers deliver at least once. See Idempotency & Exactly-Once.
- Bank note: card authorization and balance checks are inherently synchronous (the terminal waits); posting to downstream systems, notifications, loyalty and analytics should be async.
Contract testing
End-to-end tests across 30 services are slow and flaky. Consumer-driven contract tests (Pact is the best-known tool; Spring Cloud Contract in the JVM world) let each consumer publish the requests it makes and the responses it relies on; the provider's CI verifies it still satisfies every consumer contract before deploying.
- Catches breaking changes (renamed field, changed enum) before production.
- Works for HTTP and for messages (event payload contracts).
- For events, combine with a schema registry enforcing backward compatibility (see event schema & registry).
- A "can I deploy?" check in the pipeline (Pact Broker offers one) makes contract status a deployment gate.
Conway's law and Team Topologies
Melvin Conway (1968): "Organizations which design systems are constrained to produce designs which are copies of the communication structures of these organizations." If three teams share one service, you will get a three-part internal structure with messy seams; if one team owns five services, they will drift toward a single deployable.
Inverse Conway maneuver: shape teams to match the architecture you want.
Team Topologies (Skelton & Pais, 2019) gives a vocabulary:
| Team type | Purpose | Example |
|---|---|---|
| Stream-aligned | Owns a flow of business change end-to-end | Checkout team, Transfers team |
| Platform | Provides internal services as self-service products | Kubernetes platform, event-streaming platform |
| Enabling | Helps other teams adopt skills, then steps back | Observability coaches, DDD coaching |
| Complicated-subsystem | Owns a part needing deep specialist knowledge | Fraud models, pricing engine, HSM integration |
Interaction modes: collaboration (working closely for a limited time), X-as-a-Service (consume via a clear API), facilitating (coaching). A healthy microservice organization has mostly stream-aligned teams consuming platforms as a service.
Trade-offs
| Pattern | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Database per service | True independence, local schema freedom | Cross-service queries and transactions get hard | Always, for services meant to be independent |
| API composition | Simple, real-time data | Latency = slowest callee; availability multiplies | Few callees, low traffic, must be fresh |
| CQRS read model | Fast queries, decoupled | Eventual consistency, extra infrastructure | High-read cross-service views (order history, statements) |
| Single API gateway | One place for edge concerns | Can become a bottleneck / change queue | Most systems |
| BFF per client | Tailored payloads, client team autonomy | Duplication across BFFs | Distinct clients with different needs (mobile vs web vs partner) |
| Service mesh | mTLS, policies, telemetry without code changes | Ops complexity, per-hop overhead | Large or polyglot fleets, zero-trust mandates |
| Shared client library | No extra infrastructure, fast | Language-specific, version drift | Small, single-language fleets |
| Sync calls | Simple, immediate | Temporal coupling, cascading failure | Queries, authorization decisions |
| Async events | Resilience, fan-out | Eventual consistency, debugging | Workflows, notifications, projections |
In practice
A BFF composing an order page: the order is critical, shipment tracking is optional and degrades gracefully. Shared deadline, parallel calls, partial results.
package bff
import (
"context"
"time"
"golang.org/x/sync/errgroup"
)
type Order struct {
ID string
Status string
Total int64 // minor units, e.g. VND or cents
}
type Shipment struct {
Carrier string
ETA time.Time
}
type OrderPage struct {
Order Order
Shipment *Shipment
ShippingUnavailable bool
}
type OrderClient interface {
Get(ctx context.Context, id string) (Order, error)
}
type ShippingClient interface {
Track(ctx context.Context, orderID string) (Shipment, error)
}
type Handler struct {
orders OrderClient
shipping ShippingClient
}
func (h *Handler) OrderPage(ctx context.Context, orderID string) (OrderPage, error) {
ctx, cancel := context.WithTimeout(ctx, 800*time.Millisecond)
defer cancel()
var page OrderPage
g, gctx := errgroup.WithContext(ctx)
g.Go(func() error {
o, err := h.orders.Get(gctx, orderID)
if err != nil {
return err // critical: fail the page
}
page.Order = o
return nil
})
g.Go(func() error {
s, err := h.shipping.Track(gctx, orderID)
if err != nil {
page.ShippingUnavailable = true // optional: degrade, do not fail
return nil
}
page.Shipment = &s
return nil
})
if err := g.Wait(); err != nil {
return OrderPage{}, err
}
return page, nil
}
Operational checklist per service (a good "definition of done" for a paved road):
- Health endpoints (liveness, readiness), structured logs with correlation ID, RED metrics, tracing.
- Timeouts on every outbound call; retries only on idempotent operations, with jittered backoff.
- Outbox for events; idempotent consumers with a dedup table.
- Contract tests in CI; schema compatibility check for events.
- Owner team, on-call rotation and runbook link in the service catalog (e.g. Backstage).
Common pitfalls
- Nano-services. One service per entity or per endpoint. Symptom: a single feature needs changes in six repos and a coordinated release.
- Shared database "for now". Symptom: two years later, nobody can change the
orderstable without a cross-team meeting. - Synchronous everything. Symptom: p99 checkout latency equals the sum of all tails; an outage in loyalty points blocks payments.
- Retry storms. App retries plus mesh retries plus client retries. Symptom: a brief slowdown in the payment service turns into a full outage under amplified load.
- Gateway with business logic. Symptom: fee rules in Lua plugins that only one person understands.
- No ownership. Symptom: an orphaned service with an expired certificate takes down login on a Sunday.
- Ignoring the org chart. Symptom: services drift back into a monolith or fracture along team lines rather than domain lines.
Interview angle
- Expect "Design the services for an e-commerce checkout" or "How would you split a core banking monolith?" Start from capabilities/bounded contexts and data ownership, then communication style, then infrastructure.
- Show you know why database-per-service exists and how you query across (composition vs read model).
- When you draw a sync call, say its timeout, retry policy and fallback. When you draw an event, say who consumes it, what happens on duplicates, and how ordering is handled.
- Discuss the organization: number of teams, ownership, platform team. Mentioning Conway's law with a concrete example is a strong signal.
- Follow-ups: "Inventory is down — what does checkout do?", "How do you change an event schema used by five teams?", "When would you not use a service mesh?"
- Red flags: shared database between services, a service per table, no mention of idempotency, claiming microservices make things "simpler".
Self-check
1. Why is decomposition by technical layer (e.g. a "validation service" and a "persistence service") a poor choice?
Every business change crosses every layer, so every feature touches every service and requires coordinated deploys. It maximizes coupling between services and minimizes cohesion within them. Business-capability decomposition keeps related changes inside one service owned by one team.
2. Your order history page needs order data, customer names and shipment status from three services. Compare two ways to build it.
API composition: a BFF calls all three services in parallel and joins results; always fresh but latency is bounded by the slowest service and availability is the product of three. CQRS read model: a projection service consumes OrderPlaced, CustomerRenamed and ShipmentUpdated events into a denormalized table; reads are fast and independent of the source services, but data is eventually consistent and you operate another store. For a high-traffic history page, the read model usually wins.
3. List four symptoms of a distributed monolith.
- Releases require multiple services deployed together in order.
- Services share a database schema or a domain-model library.
- Deep synchronous call chains for single user requests.
- One service's outage breaks unrelated features.
- Confidence only comes from end-to-end tests in a shared environment.
4. What belongs in an API gateway, what belongs in a BFF, and what belongs in neither?
Gateway: TLS termination, authentication, coarse authorization, rate limiting, routing, logging, WAF. BFF: client-specific aggregation and payload shaping, owned by the client team. Neither: business rules such as fee calculation, stock decisions or payment state transitions — those belong in domain services.
5. A bank mandates mTLS for all east–west traffic across 120 services in Go, Java and .NET. Mesh or library? Why?
A service mesh. Implementing and rotating mTLS consistently in three language stacks via libraries is error-prone, and the mesh provides certificate issuance and rotation, policy enforcement and uniform telemetry without code changes. Accept the operational cost of the control plane and per-hop overhead, and assign a platform team to own it.
6. What does consumer-driven contract testing give you that end-to-end tests do not?
Fast, isolated verification in the provider's own CI that it still satisfies every consumer's actual usage, so breaking changes are caught before deploy without a shared integration environment. It scales with the number of services, pinpoints which consumer breaks, and can gate deployments ("can I deploy?").
7. Explain the inverse Conway maneuver with an e-commerce example.
Instead of letting the existing org chart dictate the architecture, you restructure teams to match the target architecture. Example: one "backend team" owns the whole monolith; to get independent cart, pricing and fulfilment services, you form three stream-aligned teams each owning one bounded context end-to-end, plus a platform team. The communication structure then naturally produces the intended service boundaries.
Exercise
Design the service landscape for a marketplace e-commerce platform (sellers, catalog, search, cart, checkout, payment, shipping, reviews, notifications):
- Draw services, their databases and the main sync and async interactions in Mermaid (≤ 15 nodes).
- For each synchronous call on the checkout path, write timeout, retry policy and fallback.
- List every event, its producer and consumers, and how consumers stay idempotent.
- Propose the team structure (Team Topologies types) and map each service to one owner.
- Identify one place you deliberately accept API composition and one where you build a read model.
Done when: no two services share a database, checkout has at most three synchronous downstream calls, and every service has exactly one owning team.
Further reading
- Microservices Patterns — Chris Richardson (Manning, 2018) and microservices.io.
- Building Microservices (2nd ed.) — Sam Newman (O'Reilly, 2021).
- Monolith to Microservices — Sam Newman (O'Reilly, 2019).
- Software Architecture: The Hard Parts — Ford, Richards, Sadalage, Dehghani (O'Reilly, 2021).
- Team Topologies — Matthew Skelton & Manuel Pais (IT Revolution, 2019).
- Melvin Conway, "How Do Committees Invent?" (Datamation, 1968).
- Pact documentation (docs.pact.io) — consumer-driven contract testing.
Related
- Architecture Styles — whether to use microservices at all.
- Domain-Driven Design — finding service boundaries.
- Event-Driven Architecture, CQRS & Event Sourcing — the async side in depth.
- Distributed Transactions: 2PC, TCC, Saga — consistency across services.
- Resilience Patterns — timeouts, retries, circuit breakers, bulkheads.
- Proxies, Load Balancers & API Gateways — the gateway layer in detail.
- RPC & gRPC — synchronous communication mechanics.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).