Microservices
Microservices organize a system as independently deployable services aligned to cohesive business capabilities. Each service owns its contracts, data changes, runtime configuration, telemetry, release process, and operational support, allowing teams to change or scale one capability without coordinating a full-application deployment.
Overview
The architecture trades in-process simplicity for deployment autonomy and distributed-systems costs. A useful service owns a coherent business capability, data, contracts, deployment, telemetry, and operational support. Network calls, partial failure, eventual consistency, schema evolution, security, and team ownership matter more than the number of processes. The decision should begin with measurable delivery, scaling, compliance, or reliability needs; when those forces are absent, a well-structured modular monolith usually preserves boundaries with lower latency, cost, and operational risk.
What you will learn
- Decide when microservices create enough independent-delivery value to justify distributed complexity.
- Find service boundaries from business capabilities, change patterns, data ownership, and team ownership.
- Choose synchronous HTTP or gRPC and asynchronous messaging deliberately.
- Implement transactional outbox delivery and idempotent consumers without distributed transactions.
- Design version-tolerant APIs, events, sagas, and database-per-service boundaries.
- Apply identity, least privilege, zero-trust networking, and secret isolation between services.
- Observe end-to-end requests with correlated logs, metrics, traces, and business outcomes.
- Release, scale, recover, and retire services independently with compatibility windows.
Prerequisites
- ASP.NET Core APIs, dependency injection, configuration, and health checks.
- Basic domain modeling, database transactions, and message-broker concepts.
- Containers and continuous delivery fundamentals.
- A .NET 10 SDK to run the dedicated order-flow sample.
When to use Microservices
Good fit
- Use microservices when bounded capabilities need genuinely independent release cadence, scaling, availability, or ownership.
- Use them when stable team boundaries can own code, data, deployment, telemetry, and support end to end.
- Use asynchronous integration when temporal decoupling and durable buffering are more valuable than immediate consistency.
- Extract a service only after its contract and operational boundary are clearer than the module it replaces.
Choose another approach when
- Avoid distribution when one team and one deployment can meet the product and reliability goals.
- Do not split by technical layer, CRUD entity, table, or arbitrary service-size target.
- Do not share writable schemas or coordinate every request through long synchronous call chains.
- Do not adopt microservices without automated delivery, observability, incident ownership, and platform support.
Key concepts
Capabilities and change patterns shape cohesive services more reliably than technical layers or tables.
Each service controls its persistence model and shares behavior through contracts, not database joins.
Events, queues, outbox delivery, idempotent consumers, and sagas coordinate without global transactions.
Independent deployment requires health, telemetry, release safety, capacity, and clear ownership per service.
Timeouts, bounded retries, circuit breaking, backpressure, fallbacks, and isolation make network failure an explicit design input.
Additive APIs and events, consumer-driven verification, deprecation telemetry, and compatibility windows prevent coordinated releases.
Sagas use local transactions and compensating actions to coordinate multi-service outcomes without pretending atomicity.
Golden paths, service catalogs, identity, deployment automation, observability, and on-call ownership keep the fleet governable.
Architecture
Clients enter through an edge; independently deployed services own their data and exchange durable messages through a broker.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
Build the critical path deliberately, then verify its observable behavior.
- 01
- 02
- 03
- 04
- 05
- 06
- 07
Code example
A consumer records message identity in the same transaction as its business change so redelivery is safe.
public async Task HandleAsync(OrderPlaced message, CancellationToken ct)
{
if (await db.ProcessedMessages.AnyAsync(x => x.Id == message.Id, ct))
return;
inventory.Reserve(message.OrderId, message.Lines);
db.ProcessedMessages.Add(new ProcessedMessage(message.Id, clock.UtcNow));
await db.SaveChangesAsync(ct);
}
public sealed record OrderPlaced(Guid Id, Guid OrderId,
IReadOnlyList<OrderLine> Lines);Testing strategy
Test each service in isolation and prove the failure semantics between services rather than relying only on an end-to-end happy path.
- Unit-test domain rules, idempotency decisions, compensation, and retry classification deterministically.
- Run component tests against real service databases and brokers with isolated state.
- Verify HTTP, gRPC, and event schemas for backward compatibility and consumer expectations.
- Inject timeout, duplicate, reorder, poison-message, dependency-loss, and partial-deployment scenarios.
- Load-test fan-out, queue growth, hot partitions, connection pools, and downstream saturation.
- Run critical journeys across production-like topology while keeping failures diagnosable by service and correlation ID.
Security considerations
Treat every service, network hop, contract, datastore, build artifact, and operator action as a separate trust boundary.
- Authenticate workloads with short-lived identities and authorize every operation; never trust network location alone.
- Give each service least-privilege access only to its data, topics, queues, secrets, and control-plane operations.
- Validate and bound external and inter-service input, including message size, schema, tenant, and replay window.
- Use TLS, controlled ingress and egress, private endpoints where justified, and gateway policies without moving all authorization to the edge.
- Sign and scan artifacts, produce provenance and SBOM data, patch base images, and protect deployment credentials with federation.
- Redact sensitive values from logs and traces, isolate tenant data, audit administrative actions, and rehearse credential rotation.
Performance and scalability
Optimize complete user journeys and resource saturation; a fast service can still participate in a slow, fragile call graph.
- Set end-to-end latency budgets, then allocate explicit timeout budgets to each hop.
- Avoid chatty APIs and deep synchronous fan-out; batch, cache, or publish events where semantics allow.
- Use bounded concurrency, backpressure, bulkheads, connection reuse, and retry budgets to prevent amplification.
- Partition by stable keys, measure hot keys and queue lag, and scale consumers without violating ordering guarantees.
- Track p50, p95, p99, errors, saturation, queue age, retries, and business throughput by version and dependency.
- Capacity-test failure modes because retries, failover, and replay often create the largest production load.
Deployment and operations
Independent deployment works only when contracts, data changes, traffic control, rollback, and ownership support mixed versions safely.
- Build immutable signed artifacts once and promote them through automated environments.
- Deploy additive database and contract changes before code that depends on them; remove compatibility later.
- Use readiness, graceful shutdown, disruption budgets, canaries, and automated rollback signals.
- Provision identities, queues, stores, dashboards, alerts, and policies with infrastructure as code.
- Separate service scaling and release controls while preserving an end-to-end release view for user journeys.
- Retire services by migrating consumers, draining messages, archiving owned data, revoking identities, and removing routes and telemetry.
Common problems and fixes
One user request times out across several services
Likely cause: Timeout budgets are missing, a dependency is saturated, or retries amplify the original delay.
Fix: Follow the distributed trace, compare hop deadlines and saturation, stop retry storms, and degrade or isolate the failing dependency.
A business update exists but its event is missing
Likely cause: The service performed an unsafe database-and-broker dual write.
Fix: Write the business change and outbox row in one local transaction, then publish asynchronously with monitored retries.
Inventory or billing is applied twice
Likely cause: The consumer assumed exactly-once delivery and did not persist a message receipt atomically.
Fix: Use a stable message ID and store the receipt with the business effect; replay the duplicate-path test.
A deployment breaks only some callers
Likely cause: Contracts changed incompatibly while old and new producers or consumers coexist.
Fix: Restore the compatible contract, use additive evolution, inventory consumers, and remove fields only after deprecation telemetry is clear.
A queue grows continuously
Likely cause: Consumers are unhealthy, underprovisioned, poison-looping, or blocked by a downstream service.
Fix: Inspect queue age, delivery count, dead letters, consumer health, partition skew, and dependency latency before scaling blindly.
Nobody owns a failing cross-service journey
Likely cause: Service ownership exists, but end-to-end SLOs and incident coordination do not.
Fix: Assign journey ownership, retain service-level owners, link runbooks, and use shared correlation and incident roles.
Best practices
- Start with boundaries and ownership; do not split solely to follow an architecture trend.
- Assume messages may be delayed, duplicated, or reordered.
- Use correlation identifiers and distributed tracing across synchronous and asynchronous hops.
- Deploy compatibility changes before removing old contract behavior.
- Prefer a modular monolith until independent deployment has measurable value.
- Keep synchronous call graphs shallow and make deadlines propagate.
- Own business data through contracts rather than cross-service database access.
- Automate the platform path so secure, observable defaults are easier than one-off infrastructure.
Production checklist
- Each service boundary maps to a cohesive capability, owned data, accountable team, and independent change reason.
- Synchronous and asynchronous contracts are versioned, bounded, authenticated, documented, and compatibility-tested.
- Transactional outbox, idempotent consumers, retry budgets, dead-letter handling, replay, and compensation are proven.
- Workload identity, least privilege, secret rotation, ingress and egress controls, and supply-chain checks are enforced.
- Health, structured logs, metrics, traces, business outcomes, SLOs, dashboards, alerts, and runbooks identify owner and version.
- Database migrations, mixed-version releases, canaries, rollback, graceful shutdown, and disaster recovery are rehearsed.
- Load, chaos, dependency-loss, duplicate, reorder, poison-message, and regional-failure tests cover critical journeys.
- Service catalog metadata, costs, lifecycle, deprecation, and retirement steps keep the fleet supportable.
Common interview questions
Why is a database per service recommended?
It preserves autonomy and prevents other services from coupling to internal schemas. The storage can be physically shared, but ownership and access boundaries must remain clear.
What problem does the transactional outbox solve?
It atomically records a business change and an outgoing message in one local transaction, then publishes the message asynchronously to avoid dual-write inconsistency.
When is a modular monolith a better choice?
When the domain or team boundaries are still evolving and independent deployment benefits do not justify distributed operations, latency, and consistency costs.
Why does exactly-once delivery not remove idempotency work?
Broker guarantees have scope and failure boundaries. A consumer can complete its side effect and fail before acknowledging, so application-level identity and atomic receipts are still needed.
How do sagas differ from distributed transactions?
A saga commits local transactions and coordinates later steps or compensations. It exposes intermediate states instead of holding one atomic lock across services.
What makes a microservice independently deployable?
Owned data and deployment are necessary, but contracts must also tolerate mixed versions, migrations must be compatible, and the team must operate the service without coordinated fleet releases.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Microservices Order Flow
A .NET 10 order API demonstrating service-owned state, transactional-outbox intent, idempotent inventory consumption, bounded contracts, health, and Service Bus infrastructure.
- Run
dotnet run --project src/MicroservicesOrderFlow- Test
dotnet test MicroservicesOrderFlow.slnx