Volume 6 · Chapter 8 — Enterprise Application Architecture and Design Patterns

Microservice Design Patterns

Goutham Mayaluri 7 min read .NETC#

8.1 Introduction

Microservices structure a system as independently deployable services, each owning a business capability and its data. The architecture buys team autonomy and independent scaling at the price of distributed-systems complexity. Success depends less on any single technology and more on applying a coherent set of patterns for decomposition, data, communication, and resilience. This chapter surveys the patterns that recur in production .NET microservice estates.

8.2 Decomposition and Service Boundaries

Boundaries follow business capabilities and bounded contexts, not technical layers. A good service is cohesive (one clear responsibility), loosely coupled (communicates through contracts), and owns its data. The wrong cut - splitting by database table or entity - produces chatty, tightly coupled services that must be deployed together, the worst of both worlds (“distributed monolith”).

8.3 Database per Service

Each service owns its datastore; no other service reads its tables directly. This is what makes independent deployment and scaling real. The consequence is that you cannot use a database transaction across services, which drives the need for sagas and eventual consistency.

flowchart TB
  subgraph S1["Payments Service"]
      P["API"] --> PD[("Payments DB")]
  end
  subgraph S2["Customers Service"]
      C["API"] --> CD[("Customers DB")]
  end
  P -- "events only, never direct DB access" --> C

8.4 The Saga Pattern for Distributed Transactions

A saga replaces a distributed ACID transaction with a sequence of local transactions, each publishing an event that triggers the next step. If a step fails, the saga runscompensatingactions to undo the prior steps. Sagas come in two styles: choreography (services react to each other’s events) and orchestration (a central coordinator drives the steps).

sequenceDiagram
  autonumber
  participant O as Order Service
  participant Pay as Payment Service
  participant Inv as Inventory Service
  participant Ship as Shipping Service
  O->>Pay: reserve funds
  Pay-->>O: funds reserved
  O->>Inv: reserve stock
  Inv-->>O: stock reserved
  O->>Ship: schedule shipment
  Ship--xO: FAILED (no courier)
  Note over O,Ship: Compensate in reverse
  O->>Inv: release stock
  O->>Pay: refund funds

// Orchestration-style saga step with an explicit compensation.
public async Task Handle(OrderPlaced e, CancellationToken ct)
{
    try
    {
        await _payments.ReserveAsync(e.OrderId, e.Total, ct);
        await _inventory.ReserveAsync(e.OrderId, e.Items, ct);
        await _shipping.ScheduleAsync(e.OrderId, ct);
        await _orders.MarkConfirmedAsync(e.OrderId, ct);
    }
    catch (StepFailedException)
    {
        await _inventory.ReleaseAsync(e.OrderId, ct);   // compensate
        await _payments.RefundAsync(e.OrderId, ct);     // compensate
        await _orders.MarkFailedAsync(e.OrderId, ct);
    }
}

8.5 API Gateway and Backend for Frontend

An API Gateway gives clients a single entry point and centralises routing, authentication, rate limiting, and TLS termination. A Backend-for-Frontend (BFF) goes further, providing a tailored API per client type (mobile, web) so each frontend gets exactly the shape it needs without a chatty, general-purpose API. In .NET, YARP is the common reverse-proxy building block.

flowchart TB
  M["Mobile App"] --> MB["Mobile BFF"]
  W["Web App"] --> WB["Web BFF"]
  MB --> GW["API Gateway"]
  WB --> GW
  GW --> A["Accounts"]
  GW --> P["Payments"]
  GW --> L["Loans"]

8.6 API Composition and CQRS Across Services

When a view needs data from several services (a customer dashboard spanning accounts, payments, and loans), the API Composition pattern queries each service and stitches the results. For heavy read workloads, a materialised view built from services’ events (a CQRS read model) avoids fan-out queries at request time.

8.7 Service Discovery and Configuration

Service instances come and go, so clients resolve locations through discovery (DNS in Kubernetes, or a registry) rather than hard-coded addresses. Configuration and secrets are externalised to a central store (Azure App Configuration, Key Vault) so services stay stateless and portable.

8.8 The Sidecar Pattern and Service Mesh

The sidecar pattern deploys supporting capabilities - mTLS, retries, telemetry, traffic shaping - alongside each service as a separate process, keeping that plumbing out of application code. A service mesh (Istio, Linkerd) is sidecars at fleet scale, giving uniform, policy-driven cross-service communication.

Senior Interview Question

How do you decide microservice boundaries?

By business capability and bounded context, not by data table or technical layer. A boundary is right when the service is cohesive around one responsibility, can own its data, can be deployed and scaled independently, and changes for one business reason. Signals that a boundary is wrong include two services that always deploy together, chatty synchronous call chains between them, or a shared database - all symptoms of a distributed monolith. When unsure, keep the boundary inside a modular monolith and split only when a concrete pressure (scaling, team autonomy) appears.

Senior Interview Question

How do you maintain data consistency across services without distributed transactions?

You give up cross-service ACID and adopt eventual consistency via sagas. Each service commits a local transaction and emits an event; downstream services react, and failures trigger compensating actions that semantically undo prior steps. To make events reliable you use a transactional outbox so the state change and the event are recorded atomically, and you make consumers idempotent because delivery is at-least-once. Where a user needs immediacy, you design the UX around the pending state rather than blocking on global consistency.

Senior Interview Question

Choreography or orchestration for sagas - how do you choose?

Choreography (services react to each other’s events) is decentralised, avoids a single coordinator, and suits simple flows with few steps, but the overall process becomes implicit and hard to follow as it grows. Orchestration (a central coordinator issues commands and tracks state) makes the workflow explicit, easier to monitor and change, and better for complex, long-running processes, at the cost of a coordinator that must itself be resilient. I default to choreography for two or three steps and switch to orchestration once the flow has branching, timeouts, or many participants.

Senior Interview Question

What is a "distributed monolith" and how do you avoid it?

It is the failure mode where you have paid the full operational cost of microservices but kept the coupling of a monolith: services that share a database, must be released together, or call each other synchronously in long chains. You avoid it by enforcing database-per-service, integrating asynchronously through events, keeping contracts stable and versioned, and cutting boundaries along business capabilities so services can truly change and deploy independently. If two services cannot be deployed separately, they are one service wearing two costumes.

Principal Engineer Question

What are the biggest challenges with microservices, and how do you mitigate them?

The dominant challenges are distributed data consistency, cross-service failure handling, observability, and operational complexity. I mitigate consistency with sagas, outbox, and idempotent consumers; failure with timeouts, retries with jitter, circuit breakers, and bulkheads (Polly); observability with correlation IDs, distributed tracing (OpenTelemetry), and centralised structured logs and metrics; and operations with strong platform automation - CI/CD per service, infrastructure as code, and a service mesh for uniform communication. Above all I resist premature decomposition, because the cheapest distributed problem is the one you did not create.

Principal Engineer Question

How do you handle a schema/contract change in a service that many others consume?

I treat the contract as a published API with backward compatibility as a non-negotiable. Changes are additive - new optional fields, new event types - never breaking renames or removals. For unavoidable breaking changes I version the contract (v1 and v2 side by side), run both during a migration window, and use consumer-driven contract tests (Pact) so I know exactly who depends on what before I deprecate v1. Events carry a schema version and consumers use tolerant readers. This lets producers and consumers deploy independently, which is the entire point of the architecture.

8.9 Banking Enterprise Scenario

A bank runs Payments, Accounts, Customers, and Loans as independent services, each with its own database, fronted by a YARP gateway and per-client BFFs. A funds transfer spans Payments and Accounts, so it is modelled as an orchestrated saga with compensations: if the credit leg fails, the debit is refunded. Every service publishes events through a transactional outbox, and consumers are idempotent. Cross-cutting concerns - mTLS, retries, tracing - live in a service-mesh sidecar, and a customer dashboard composes data from all four services through the gateway. When peak load hits Payments, only that service scales out.

Chapter Revision Notes

  • Cut services by business capability; each owns its data.
  • Replace distributed transactions with sagas and compensations.
  • Use an API gateway/BFF for a clean, tailored client edge.
  • Make events reliable (outbox) and consumers idempotent.
  • Avoid the distributed monolith; version contracts, test them with Pact.
  • Push cross-cutting concerns into sidecars / a service mesh.