7.1 Core Principles
Microservices architecture structures an application as a collection of small, autonomous services, each owning its own data and deployable independently. The principles that separate a good microservices architecture from a “distributed monolith” are:
- Single Responsibility / Business Capability Alignment — each service owns one business capability end-to-end.
- Autonomy — a team can design, build, test, and deploy its service without coordinating a release with another team.
- Decentralized Data Management — database-per-service; no service reaches into another’s schema.
- Design for Failure — every remote call can fail; timeouts, retries, circuit breakers, and bulkheads are not optional.
- Smart Endpoints, Dumb Pipes — business logic lives in the services, not in an all-knowing ESB.
- Infrastructure Automation — CI/CD, container orchestration, and observability are prerequisites, not nice-to-haves.
- Evolutionary Design — services should be small enough to rewrite in a sprint if needed.
The 12-Factor App (foundational discipline for any service)
| Factor | Description | Key Practice |
|---|---|---|
| 1. Codebase | One repo, many deploys | Monorepo or multi-repo per service |
| 2. Dependencies | Explicit declaration | Maven/Gradle/NuGet/pip, no implicit deps |
| 3. Config | Stored in environment | No hardcoded URLs; config server/secret store |
| 4. Backing services | Treat as attached resources | DB, cache, queue = pluggable via connection string |
| 5. Build, release, run | Strict separation | Docker image = immutable artifact |
| 6. Processes | Stateless, share-nothing | Session in Redis, not in-process memory |
| 7. Port binding | Self-contained HTTP | Embedded Kestrel/Uvicorn, not app-server deployment |
| 8. Concurrency | Scale out via process model | Horizontal pods, not a bigger box |
| 9. Disposability | Fast start, graceful shutdown | Handle SIGTERM, drain in-flight requests |
| 10. Dev/prod parity | Keep environments similar | Docker Compose locally, same images in K8s |
| 11. Logs | Treat as event streams | stdout → collector → central log store |
| 12. Admin processes | One-off tasks | K8s Jobs, not manual SSH scripts |
7.2 Decomposition Strategies
Strategy 1 — Decompose by Business Capability (preferred default)
E-Commerce Platform
├── User Service → Identity, auth, profiles
├── Product Catalog Service → Products, categories, search
├── Inventory Service → Stock, reservations
├── Order Service → Order lifecycle management
├── Payment Service → Payment processing, reconciliation
├── Notification Service → Email, SMS, push
└── Analytics Service → Reporting, BI, dashboards
A business capability is something the organization does regardless of technology (e.g., “manage inventory”). It changes far less often than an org chart, which makes it a stable seam for a service boundary.
Strategy 2 — Decompose by Subdomain (DDD Bounded Contexts)
Domain-Driven Design gives a more rigorous decomposition technique than “business capability” alone: identify bounded contexts — explicit boundaries within which a specific domain model, and specifically its ubiquitous language, is valid.
flowchart LR
subgraph OrderContext["Order Bounded Context"]
OrderModel["• Order (Root)\n• OrderLine\n• OrderStatus"]
end
subgraph PaymentContext["Payment Bounded Context"]
PaymentModel["• Payment (Root)\n• Invoice\n• PaymentMethod"]
end
subgraph ShippingContext["Shipping Bounded Context"]
ShippingModel["• Shipment (Root)\n• TrackingInfo\n• DeliveryRoute"]
end
OrderContext -->|Domain Event:\nOrderSubmitted| PaymentContext
PaymentContext -->|Domain Event:\nPaymentCaptured| ShippingContext
Key DDD building blocks that map directly onto microservice boundaries:
| Concept | Description | Example |
|---|---|---|
| Bounded Context | Boundary within which a model/language is unambiguous | OrderContext, InventoryContext, BillingContext |
| Aggregate | Cluster of entities/value objects treated as one consistency unit | Order (root) + OrderLines + ShippingAddress |
| Aggregate Root | Only entry point into the aggregate | Order class — nothing mutates OrderLine directly |
| Value Object | Immutable, no identity, defined by attributes | Money, Address, DateRange |
| Domain Event | Something meaningful that happened | OrderPlaced, PaymentProcessed |
| Entity | Has a distinct identity that persists over time | Customer, Product, Order |
| Anti-Corruption Layer (ACL) | Translation layer that prevents a legacy/foreign model from leaking in | Adapter between legacy mainframe and Order Context |
| Shared Kernel | Small, deliberately shared model between two closely related contexts | Common Money type shared by Billing and Order |
| Context Map | Diagram of how bounded contexts relate (Partnership, Customer-Supplier, Conformist, ACL) | Governance artifact for the whole system |
Rule of thumb: one microservice should never span more than one bounded context, but one bounded context can be implemented by more than one microservice if scaling needs differ (e.g., separate read/write services under CQRS).
# Aggregate root enforcing invariants — Python example
from dataclasses import dataclass, field
from decimal import Decimal
from enum import Enum, auto
class OrderStatus(Enum):
DRAFT = auto()
SUBMITTED = auto()
CANCELLED = auto()
@dataclass(frozen=True)
class Money:
amount: Decimal
currency: str = "USD"
def add(self, other: "Money") -> "Money":
if self.currency != other.currency:
raise ValueError("Cannot add different currencies")
return Money(self.amount + other.amount, self.currency)
@dataclass
class OrderLine:
product_id: str
unit_price: Money
quantity: int
@property
def subtotal(self) -> Money:
return Money(self.unit_price.amount * self.quantity, self.unit_price.currency)
class DomainException(Exception):
pass
class Order:
"""Aggregate root — all mutation goes through here, guaranteeing invariants."""
def __init__(self, order_id: str, customer_id: str):
self.id = order_id
self.customer_id = customer_id
self.status = OrderStatus.DRAFT
self._lines: list[OrderLine] = []
self._domain_events: list[object] = []
@property
def total(self) -> Money:
total = Money(Decimal("0"))
for line in self._lines:
total = total.add(line.subtotal)
return total
def add_line(self, product_id: str, unit_price: Money, quantity: int) -> None:
if self.status != OrderStatus.DRAFT:
raise DomainException("Cannot modify a submitted order")
self._lines.append(OrderLine(product_id, unit_price, quantity))
self._domain_events.append(("OrderLineAdded", self.id, product_id, quantity))
def submit(self) -> None:
if not self._lines:
raise DomainException("Cannot submit an empty order")
self.status = OrderStatus.SUBMITTED
self._domain_events.append(("OrderSubmitted", self.id, str(self.total.amount)))
def pull_events(self) -> list[object]:
events, self._domain_events = self._domain_events, []
return events
Strategy 3 — Strangler Fig Pattern (Migration Strategy)
flowchart TD
Client["Client Traffic"]
GW["API Gateway / Reverse Proxy\n(Traffic Splitter)"]
subgraph MonolithTier["Legacy Monolith Core"]
Monolith["Monolithic Application\n(Gradually Deprecated)"]
end
subgraph ModernTier["Extracted Microservices"]
Svc1["User Service\n(Extracted Domain)"]
Svc2["Product Service\n(Extracted Domain)"]
Svc3["Order Service\n(Extracted Domain)"]
end
Client --> GW
GW -->|Legacy Routes / Unmigrated Capabilities| Monolith
GW -->|/api/v1/users| Svc1
GW -->|/api/v1/products| Svc2
GW -->|/api/v1/orders| Svc3
Iterative Migration Phases:
- Perimeter Interception: Deploy an API Gateway / Reverse Proxy in front of the monolithic core.
- Incremental Extraction: Carve out high-value, decoupled capabilities into isolated microservices.
- Traffic Shifting: Route canary traffic (e.g., 5% → 25% → 100%) to verify feature parity before cutting over entirely.
- Decommissioning: Once all bounded contexts are extracted, safely retire the empty monolithic shell.
7.3 Service Communication Patterns
flowchart LR
subgraph SyncComm["Synchronous Communication (REST / gRPC)"]
C1["Client"] -->|Blocking HTTP/2| S1["Service A"]
S1 -->|Blocking RPC| S2["Service B"]
end
subgraph AsyncComm["Asynchronous Communication (Event-Driven)"]
S3["Service A"] -->|Publish Event| Bus[("Message Broker\n(Kafka / RabbitMQ)")]
Bus -->|Consume Event| S4["Service B"]
Bus -->|Consume Event| S5["Service C"]
Bus -->|Consume Event| S6["Service D"]
end
Synchronous vs. Asynchronous Trade-Off Matrix:
- Synchronous (REST / gRPC):
- Pros: Simple mental model, immediate client response, familiar HTTP error semantics.
- Cons: Temporal coupling, cascading failure vulnerabilities, compounding latency chains across dependencies.
- Asynchronous (Event-Driven / Messaging):
- Pros: Loose coupling, resilient against traffic spikes, message replayability and non-blocking scale.
- Cons: Eventual consistency lag, requires distributed tracing (W3C TraceContext), complex saga error orchestration.
Architectural Decision Rule: Use synchronous calls when the client requires an immediate answer to proceed (e.g., synchronous fraud decision or login auth token). Use asynchronous messaging for all decoupled side effects (e.g., order confirmations, invoice generation, metrics pipeline, search indexing).
7.4 Anti-Patterns
| Anti-Pattern | Problem | Root Cause | Fix |
|---|---|---|---|
| Distributed Monolith | Services are deployed as micro-units but must all release together because they’re contractually and temporally coupled | Shared database, synchronous call chains, lock-step versioning | Decouple via events, contract testing, independent DB per service |
| Chatty Communication | Service A calls B calls C calls D synchronously to answer one request; latency and failure probability compound | Decomposition boundary cut through a single use case | Aggregate data at the boundary (BFF/API composition), or push data via events (event-carried state transfer) |
| Shared Database | Multiple services read/write the same tables directly | “Easiest” way to keep data in sync in the short term | Database per service; synchronize via events / CDC, expose data only via API |
| No API Gateway | Every client talks directly to every internal service | No governance layer was designed in early on | Add a gateway for authn/z, rate limiting, routing, versioning |
| Premature Decomposition (“microservices envy”) | Team splits into 30 services before the domain is understood, causing constant boundary rework and huge cross-service change sets | Cargo-culting a pattern without validating team/domain maturity | Start with a modular monolith; extract services once real seams and scaling needs emerge |
| Nanoservices | Services so small the network/ops overhead exceeds the benefit (e.g., one service per CRUD entity) | Decomposing by table instead of by capability | Merge related entities that always change together back into one service |
| Entangled Lifecycle | A “shared library” of business logic is imported by every service, so a bug fix requires a synchronized redeploy of all of them | Business logic reuse solved via shared code instead of shared service/API | Extract as its own service if it’s truly cross-cutting business logic; keep shared libraries to technical concerns (logging, auth middleware) only |
7.5 When NOT to Use Microservices
Microservices are a tool for organizational and technical scaling, not a default architecture. Reasons to stay with a (modular) monolith:
- Small team (< 8–10 engineers) — Conway’s Law means your architecture will mirror your team structure; a small team fragmenting into 20 services creates more coordination overhead than it removes.
- Domain not yet understood — early-stage products pivot; premature service boundaries have to be re-drawn constantly, which is far more expensive across services than within one codebase.
- No dedicated DevOps/platform capability — microservices multiply the number of things to deploy, monitor, secure, and patch. Without automation (CI/CD, container orchestration, centralized logging/tracing) the operational burden dwarfs the benefit.
- Low/steady traffic, no differential scaling needs — if nothing needs to scale independently, you’re paying network/latency/complexity tax for nothing.
- Strong consistency dominates the domain — if almost every operation needs a cross-entity ACID transaction (e.g., a general ledger core), splitting entities into separate services with their own databases fights the domain instead of serving it.
- Time-to-market is critical — the extra plumbing (service discovery, distributed tracing, contract testing, message infra) delays the first release.
Recommended progression: start with a modular monolith — one deployable unit, but internally partitioned into modules with enforced boundaries (own schema/DbContext per module, communication only through interfaces, no cross-module foreign keys). Extract a module into its own service only when there’s a concrete forcing function: independent scaling, independent deploy cadence, a different tech stack requirement (e.g., a Python ML service), or a team boundary that needs decoupling.
src/
├── Modules/
│ ├── Orders/ (internal boundary, owns its DbContext/schema)
│ ├── Payments/ (talks to Orders only via interfaces, not direct DB access)
│ ├── Inventory/
│ └── Notifications/
├── SharedKernel/ (common abstractions only — Money, DateRange, etc.)
└── API/ (thin orchestration layer)
7.6 Interview Q&A
Q1: Your team is debating between a monolith and microservices for a new product. What do you recommend?
Start with a modular monolith. New products need fast iteration, and microservices add deployment and debugging overhead you can’t afford before you know your domain boundaries. Structure the monolith into modules with enforced boundaries and its own persistence per module, so it can be decomposed later at low cost. Migrate a module out to its own service when the team grows past ~8–10 engineers (Conway’s Law), when a component needs independent scaling (e.g., notifications spike independently of orders), when release cadence diverges (orders team ships daily, payments ships monthly and needs a stricter change process), or when a different technology stack is required (a Python ML service alongside a C#/.NET core).
Q2: How do you ensure data consistency in a microservices architecture?
I accept that strong consistency across services is often neither possible nor necessary, and adopt “be consistent where it matters, be eventually consistent everywhere else.” For critical business operations like payments or inventory reservations, I use the Saga pattern with compensating transactions — each step is local and atomic, and if a downstream step fails, compensating actions undo the prior steps. I pair this with the Outbox pattern so the local DB write and the event publication are atomic. For read-side consistency, I embrace eventual consistency: events propagate to read models within milliseconds, which is fine for most user-facing queries. Where absolute consistency really matters (e.g., a balance display), I route directly to the source-of-truth service instead of a cached read model.
Q3: A senior developer argues DDD is over-engineering for your product. How do you respond?
I agree DDD isn’t appropriate everywhere. Use full DDD (aggregates, value objects, domain events, bounded contexts) for the core domain — the part that gives the product its competitive edge, where business rules are complex and change often; the ubiquitous language and encapsulated invariants pay for themselves there. Use simple CRUD + repository pattern for supporting domains (user management, notifications, settings). Use off-the-shelf solutions for generic domains (auth, email). I would not force DDD onto the whole codebase, but for the core domain the upfront modeling investment saves far more in maintenance cost over the product’s life than it costs upfront.
Q4: How do you decompose a legacy monolith into microservices without a risky rewrite?
I use the Strangler Fig pattern. Phase 1: put an API Gateway or reverse proxy in front of the monolith so all traffic routes through it. Phase 2: extract the highest-value, most independently-changing capability first (often the one causing the most deployment pain) as a new service, and have the gateway route just that capability’s traffic to it while the monolith remains the source of truth for everything else. Repeat capability by capability. Every phase keeps an instant rollback path — flip the gateway route back to the monolith. Never attempt a big-bang cutover; the incremental approach means a bad extraction affects one capability, not the whole system.
Q5: What’s the difference between a distributed monolith and microservices, and how do you detect you have one?
A distributed monolith looks like microservices operationally (separate deployables, separate repos) but behaves like a monolith at release time: services must be deployed together because of tight synchronous coupling, a shared database, or lock-step contract versioning. Detection signals: you cannot deploy service A without also deploying service B in the same release window; an outage in one service cascades through synchronous call chains into unrelated services; multiple services write to the same tables. The fix is the same discipline that defines real microservices: database-per-service, asynchronous integration wherever consistency doesn’t need to be immediate, and consumer-driven contract testing so a service can evolve without breaking its callers.