Designing microservices architecture
I need to outline a microservices architecture design covering aspects like boundaries, data ownership, API contracts, service discovery, resilience, observability, CI/CD, and security. I want this to be concise yet comprehensive, providing a general template with an e-commerce example. I’ll include key concepts like DDD, event-driven design, and various tech choices such as Kubernetes for service discovery and observability tools. It's important to discuss trade-offs and ensure I address resilience strategies too!Creating microservices examples
I want to outline example services like Identity, Catalog, Order, Payment, Inventory, Shipping, and Notification, specifying the database types for each. For API contracts, I'll mention OpenAPI and Protobuf, focusing on backward compatibility and consumer-driven contract testing. Service discovery options include internal DNS or a service mesh. I’ll incorporate resilience patterns, observability through logs, metrics, and traces, plus correlation IDs. Governance is also on my list. I’ll structure my answer with bullet points and consider including some text-based diagrams, while noting trade-offs and alternatives.
Below is a reference microservices architecture you can adapt to most product domains (e.g., commerce, SaaS). It covers service boundaries, data ownership, API contracts, discovery, resilience, observability, CI/CD, and security—plus concrete tech choices and trade-offs.
1) Service boundaries (how to slice the system)
Principles
- Bounded contexts (DDD): Each service owns a coherent business capability and its rules.
- High cohesion, low coupling: Minimize cross-service synchronous calls on hot paths.
- Separate “write model” services from read/reporting models where needed (CQRS-style).
Example domain decomposition (illustrative)
- Identity & Access: users, sessions, roles, MFA
- Customer Profile: addresses, preferences
- Catalog: products, pricing rules, availability view (not inventory truth)
- Inventory: stock ledger, reservations
- Order: cart/checkout, order lifecycle
- Payment: payment intents, captures, refunds (often wraps PSPs)
- Shipping: rates, labels, tracking
- Notification: email/SMS/push templates + delivery
- Search: indexing + query (read-optimized)
- Analytics/Events: event lake / warehouse ingestion (read-only consumers)
Trade-off notes
- Fewer services first: Start coarse-grained; split only when team ownership, scaling, or delivery velocity demands it.
- Avoid “entity services” (e.g., a generic “User Service” used by everyone for everything). Prefer capability-centric APIs.
2) Data ownership and consistency
Rules
- Database-per-service (strong default): each service owns its schema and persistence tech.
- No shared tables across services. Cross-service access happens via APIs/events.
- Consistency model
- Intra-service: ACID transactions.
- Inter-service: eventual consistency via events + sagas.
Patterns
- Event-driven integration for state propagation:
- Domain events like
OrderPlaced, PaymentCaptured, StockReserved.
- Outbox pattern (reliable publish):
- Write business data + outbox record in the same DB transaction, then publish to the broker.
- Sagas for multi-step workflows:
- Orchestration (central coordinator) vs choreography (events).
- Idempotency keys for “at least once” delivery and retries.
Tech choices
- Transactional stores: PostgreSQL/MySQL per service (common default).
- High-throughput key-value: Redis (caching), DynamoDB/Cassandra (if needed).
- Search: OpenSearch/Elasticsearch maintained by Search service.
- Event log: Kafka (or Pulsar). If simpler: RabbitMQ (less suited for event sourcing/replay).
- Schema registry: Confluent Schema Registry (Avro/Protobuf/JSON Schema).
Trade-offs
- DB-per-service increases autonomy and safety, but adds:
- More ops overhead (migrations, backups, monitoring).
- Complexity for cross-entity queries → use dedicated read models or analytics pipelines.
3) API contracts (how services talk)
North–south (client → platform)
- API Gateway in front of services:
- AuthN/Z, rate limiting, request shaping, version routing.
- API style:
- REST/JSON for public APIs (broad tooling support).
- GraphQL can fit client aggregation, but be careful: it can reintroduce coupling and N+1 internal calls unless backed by dedicated BFFs.
East–west (service → service)
- gRPC for low-latency internal RPC (Protobuf contracts), or REST if simplicity > perf.
- Prefer async events for propagation of facts/state changes.
Contract practices
- Explicit versioning
- REST: version in path or header; prefer additive changes.
- Protobuf: backward-compatible field evolution.
- Consumer-driven contract tests: Pact (REST) or protobuf-based compatibility checks.
- OpenAPI specs for REST; protobuf IDL for gRPC; generate clients/servers.
Trade-offs
- REST is simpler; gRPC is faster/typed but harder to debug with generic tools.
- Events decouple teams, but require discipline in schema evolution and replay semantics.
4) Service discovery & traffic management
Default on Kubernetes
- Service discovery: Kubernetes Services + DNS (
service.namespace.svc.cluster.local).
- Ingress: NGINX Ingress or Envoy Gateway; or managed gateways in cloud.
- Optional service mesh for mTLS + traffic policies:
- Linkerd (simpler) or Istio (more features/complexity).
Trade-offs
- Mesh reduces app-side networking concerns but adds operational complexity and latency overhead. Start without a mesh unless you need pervasive mTLS, advanced routing, or standardized telemetry.
5) Resilience patterns (keep failures contained)
Required baseline
- Timeouts everywhere (client + server); enforce per-hop budgets.
- Retries with backoff + jitter, only on safe/idempotent operations.
- Circuit breakers (e.g., via resilience libraries or mesh).
- Bulkheads: isolate thread pools/connection pools per dependency.
- Rate limiting at gateway + per-service (token bucket/leaky bucket).
- Load shedding: return 429/503 before meltdown.
- Graceful degradation: cached reads, fallback responses, “best effort” features.
Data & messaging resilience
- Idempotent consumers for events.
- Dead Letter Queues (DLQ) with replay tooling.
- Poison message handling and max retry policies.
Tech choices
- App libraries: Resilience4j (JVM), Polly (.NET), Hystrix alternatives, or built-in platform policies.
- Mesh: Envoy/Istio/Linkerd for retries/timeouts/circuit breaking at L7 (use carefully; avoid retry storms).
6) Observability (know what’s happening)
Signals
- Logs: structured JSON logs with correlation IDs.
- Metrics: RED (Rate/Errors/Duration) and USE (Utilization/Saturation/Errors).
- Traces: distributed tracing for request flows and dependency latency.
Standards & stack
- OpenTelemetry (SDK + auto-instrumentation) as the standard.
- Metrics: Prometheus + Grafana
- Tracing: Tempo or Jaeger
- Logs: Loki (Grafana) or ELK/OpenSearch
- Alerting: Alertmanager + on-call integration (PagerDuty/Opsgenie)
Practices
- Propagate traceparent / correlation headers through gateway, services, and message metadata.
- Define SLOs per critical user journey; page on burn rate, not raw errors.
7) CI/CD (build, test, deploy safely)
Pipeline stages
- Build: compile, unit tests, lint, SAST
- Package: container build (Docker/BuildKit), SBOM generation
- Test
- Integration tests with ephemeral env (Testcontainers)
- Contract tests (Pact)
- Security scans (SCA + container scanning)
- Deploy
- GitOps to Kubernetes (Argo CD or Flux)
- Progressive delivery: canary or blue/green (Argo Rollouts/Flagger)
- Operate
- Automated rollback on SLO/metrics regression
Infra & config
- IaC: Terraform (cloud resources) + Helm/Kustomize (K8s manifests).
- Separate config from code; use feature flags for risky changes (LaunchDarkly/OpenFeature).
Trade-offs
- GitOps improves auditability and consistency, but requires discipline in repo structure and promotion flows.
- Canary reduces blast radius but needs strong metrics and alerting maturity.
8) Security (zero-trust-by-default)
Identity & access
- External auth: OAuth2/OIDC (Keycloak, Auth0, Azure AD, Cognito)
- Token format: JWT access tokens (short-lived), refresh tokens handled carefully.
- Service-to-service auth:
- mTLS (mesh or cert management) + workload identity (SPIFFE/SPIRE optional)
- Fine-grained authorization: OPA/Gatekeeper or OpenFGA (relationship-based)
Network & perimeter
- API Gateway: WAF integration, throttling, bot protection, request validation.
- Kubernetes NetworkPolicies: default-deny + explicit allows.
- Secrets management: Vault or cloud secret manager; rotate regularly.
- Supply chain security:
- Sign images (cosign), verify at deploy time (policy controller)
- Enforce provenance (SLSA), SBOM (Syft), scanning (Trivy/Grype)
Data protection
- TLS everywhere; encrypt at rest (KMS-managed keys).
- PII segregation + field-level encryption where needed.
- Audit logs for sensitive actions (authz decisions, data exports).
Trade-offs
- JWT simplifies stateless auth but complicates immediate revocation → mitigate with short TTL + token introspection for high-risk operations.
- mTLS everywhere is strong but operationally heavy without a mesh or managed identity tooling.
Suggested “default” technology set (pragmatic baseline)
- Runtime: Kubernetes
- Gateway: Kong / Apigee / NGINX (choose based on enterprise needs)
- Internal comms: REST for simplicity + Kafka for events; gRPC where latency/typing matters
- Broker: Kafka + schema registry
- Datastores: PostgreSQL per service; Redis cache
- Observability: OpenTelemetry + Prometheus/Grafana + Tempo/Jaeger + Loki/ELK
- CI/CD: GitHub Actions/GitLab CI + Argo CD + Argo Rollouts
- Security: OIDC provider + Vault/Cloud secrets + NetworkPolicies; optional mesh for mTLS
Key architectural trade-offs to decide early
- Sync vs async: sync is simpler for CRUD, async is better for decoupling and resilience.
- Mesh vs no mesh: mesh standardizes mTLS/telemetry but adds complexity.
- Choreography vs orchestration for sagas: choreography is decentralized; orchestration is clearer for complex workflows.
- Polyglot persistence: powerful but increases ops burden; standardize unless there’s a real need.
If you share your domain (e.g., fintech, marketplace, IoT), scale (RPS/data volume), regulatory constraints, and team topology, I can propose concrete service boundaries, event schemas, and a deployment topology tailored to your situation.