Microservices design

From FerroxLabs/wayland · View interactive version

Microservices design is an AI agent skill from the GitHub repository FerroxLabs/wayland. Guides expert-level microservices design implementation: architecture and microservices decision frameworks, production-ready patterns, and concrete templates for microservices design workflows. Use when the user asks about microservices design, microservices design configuration, or architecture be

How to use this skill

Skill file

Microservices Design

When to Use

Use this skill when:

Do NOT use this skill when:


Process

Step 1 -- Assess Decomposition Readiness and Organizational Fit

Before designing any service boundary, establish whether the system is ready for microservices:

Step 2 -- Define Service Boundaries Using Domain-Driven Design

Service boundaries are the most consequential decision in microservices design. Wrong boundaries cause chatty services, distributed monoliths, and broken data consistency.

Step 3 -- Design the Communication Architecture

Communication patterns determine latency characteristics, coupling, and resilience.

Step 4 -- Design the Data Architecture

Data ownership is the hardest part of microservices. Each service must own its data -- no sharing database schemas.

Step 5 -- Design for Resilience

Distributed systems fail in partial and unexpected ways. Resilience must be designed in, not added later.

Step 6 -- Design the Observability Stack

You cannot debug a microservices system without structured observability. Logs alone are insufficient.

Step 7 -- Design the Deployment and Service Contract Strategy

Microservices derive their value from independent deployability. This requires careful contract management.

Step 8 -- Review and Validate the Design

Before committing to implementation, validate the design against known failure modes.


Output Format

Use this template when presenting a microservices design recommendation:

## Microservices Design Specification: [System/Feature Name]

### Context Summary
- Business domain: [e.g., e-commerce order fulfillment]
- Team structure: [e.g., 3 teams, 8 engineers each]
- Current state: [e.g., Rails monolith, ~500k req/day]
- Decomposition driver: [e.g., scaling hot spot on inventory; independent release cadence for payments]

---

### Service Boundary Map

| Service Name       | Bounded Context      | Owns Aggregate(s)         | Database         | Team Owner    |
|--------------------|---------------------|---------------------------|-----------------|---------------|
| orders-service     | Order Management    | Order, OrderLineItem       | PostgreSQL       | Fulfillment   |
| inventory-service  | Inventory           | SKU, StockLedger           | PostgreSQL       | Catalog       |
| payments-service   | Payments            | Payment, Refund            | PostgreSQL       | Payments      |
| notifications-svc  | Notifications       | Notification, Template     | PostgreSQL       | Platform      |
| user-service       | Identity            | User, Profile, Session     | PostgreSQL+Redis | Platform      |

---

### Communication Architecture

| Interaction                          | Pattern          | Protocol       | Justification                              |
|--------------------------------------|-----------------|----------------|--------------------------------------------|
| Client → API                         | Sync request    | REST/HTTPS     | User-facing, needs immediate response      |
| orders → inventory (reservation)     | Sync call       | gRPC           | Must confirm availability before order     |
| orders → payments (charge)           | Orchestrated saga| Kafka events  | Distributed transaction, compensation needed|
| payments → notifications             | Async event     | Kafka          | Fire-and-forget, eventual consistency OK   |
| inventory read model                 | CQRS projection  | Kafka CDC      | High read:write ratio, separate query model|

---

### Data Architecture Decisions

| Service            | Write Store      | Read Store       | Event Pattern     | Migration Tool |
|--------------------|-----------------|-----------------|-------------------|----------------|
| orders-service     | PostgreSQL       | N/A              | Outbox → Kafka    | Flyway          |
| inventory-service  | PostgreSQL       | Redis (cache)    | Outbox → Kafka    | Flyway          |
| payments-service   | PostgreSQL       | N/A              | Outbox → Kafka    | Flyway          |

---

### Saga Design: Order Placement

**Type:** Orchestration-based (OrderOrchestrator service)

| Step | Command Sent           | Success Event               | Failure Compensation              |
|------|------------------------|-----------------------------|------------------------------------|
| 1    | ReserveInventory       | InventoryReserved           | -- (first step, no prior to undo) |
| 2    | AuthorizePayment       | PaymentAuthorized           | ReleaseInventoryReservation        |
| 3    | ConfirmOrder           | OrderConfirmed              | RefundPayment, ReleaseInventory    |
| 4    | SendConfirmationEmail  | NotificationSent            | -- (non-critical, log failure)    |

---

### Resilience Configuration

| Service             | Timeout (outbound) | Circuit Breaker Threshold | Retry Policy              | Fallback                        |
|---------------------|--------------------|--------------------------|---------------------------|---------------------------------|
| orders-service      | 2s (inventory)     | 50% errors / 10s window  | 3x, exp backoff + jitter  | Return HTTP 503, surface to user|
| orders-service      | 3s (payments)      | 30% errors / 10s window  | 2x (non-idempotent, caution)| Queue for async retry          |
| inventory-service   | 1s (Redis cache)   | 80% errors / 5s window   | 1x, no jitter             | Fall through to PostgreSQL      |

---

### Observability Setup

- Tracing: OpenTelemetry SDK → Jaeger (internal) / Datadog APM (production)
- Metrics: Prometheus exposition format, scraped every 15s, stored in Thanos
- Logs: JSON structured, shipped via Fluentd to Loki
- Correlation: W3C `traceparent` header propagated across all HTTP and Kafka calls
- Alerting SLOs:
  - orders-service: p99 latency < 300ms | error rate < 0.1% | measured over 30-day window
  - payments-service: p99 latency < 500ms | error rate < 0.01% | measured over 30-day window

---

### Deployment Strategy

- Deployment pattern: Canary releases (5% → 25% → 100%, 10 min soak at each stage)
- Contract testing: Pact broker, consumer contracts run in provider CI pipelines
- Schema registry: Confluent Schema Registry, BACKWARD compatibility enforced
- Health endpoints: /health/live and /health/ready on all services, port 8081
- Service catalog: Backstage, updated via CI pipeline on merge to main

---

### Architecture Decision Records

| ADR # | Decision                                      | Status   |
|-------|-----------------------------------------------|----------|
| ADR-001 | Use orchestration-based saga for order flow | Accepted |
| ADR-002 | gRPC for inventory reservation (sync)        | Accepted |
| ADR-003 | PostgreSQL per service, no shared schemas    | Accepted |
| ADR-004 | Outbox pattern for guaranteed event delivery | Accepted |
| ADR-005 | Service mesh (Istio) deferred until 10+ svc  | Proposed |

Rules

  1. Never share a database between two services. Two services reading the same table or schema is a distributed monolith, not microservices. If it cannot be avoided in the short term (legacy migration), document it explicitly as technical debt with a removal date.
  1. Never use distributed two-phase commit (2PC). 2PC creates tight availability coupling -- if the coordinator is unavailable, all participants are blocked. Use Sagas (choreography or orchestration) for all cross-service transactions. The additional complexity is mandatory, not optional.
  1. Never design service boundaries along technical layers. A "validation service" or "persistence service" is not a microservice -- it is a distributed library. All service boundaries must follow business domain boundaries (bounded contexts).
  1. Always assign a single team as the owner of each service. No service may have joint ownership. Joint ownership means no clear accountability for SLAs, on-call response, or API contract stability. If two teams both need a capability, one owns the service and the other is a customer.
  1. Never create synchronous call chains longer than 3 hops for user-facing requests. A user request that causes Service A to call B, which calls C, which calls D creates compounded latency (latencies multiply) and catastrophic failure amplification. Redesign long chains with async messaging, request fan-out aggregation, or boundary revision.
  1. Always implement idempotency on all message consumers and all POST/PUT/PATCH endpoints. At-least-once delivery is the default guarantee in every message broker. Assume every message will be delivered 2+ times and design accordingly. Use idempotency keys stored with the business state.
  1. Never expose a service's internal data model as its API contract. The API contract is a public interface that must be versioned and stable. The internal database schema is a private implementation detail. Coupling them means every schema refactor breaks consumers.
  1. Always set explicit timeouts on every outbound network call. No timeout means a slow dependency can exhaust all threads/connections, taking down the caller. The default in most HTTP clients is "no timeout" or "system TCP timeout" (minutes). Set it explicitly: 500ms--3s for internal calls, 5--10s for external APIs.
  1. Apply the Strangler Fig pattern when migrating from a monolith. Never attempt a "big bang" rewrite of a monolith into microservices. Route new traffic to the new service while the old monolith handles existing traffic. Migrate one bounded context at a time. Maintain a facade (API gateway or proxy) that routes to either the monolith or the new service based on the operation.
  1. Do not adopt microservices to solve a people or process problem. Microservices solve deployment coupling and scaling isolation. They do not fix poor code quality, unclear product ownership, or organizational dysfunction. If the real problem is slow deployments due to manual processes, fix the CI/CD pipeline first. If the real problem is unclear ownership, fix the org chart first.

Edge Cases

Migrating a Shared Database (The "Shared Schema" Monolith)

The most common microservices migration scenario involves a single relational database with dozens of tables and cross-cutting foreign key relationships. Do not attempt to split the database before splitting the code. The sequence is: (1) separate the application codepaths first -- introduce service interfaces in the monolith code that isolate data access by bounded context; (2) deploy the new service with its own database and dual-write: write to both the old shared table and the new service's table while reads still hit the old table; (3) once the new service's data is verified consistent, move reads to the new service; (4) remove the dual-write and drop the old table. This process takes weeks to months per service. Rushing it is the primary cause of microservices migration disasters.

Event Schema Evolution and Backward Compatibility

When a service publishes events consumed by 5+ downstream services, changing an event schema risks breaking all consumers simultaneously. Always use a schema registry with compatibility checks. The BACKWARD compatibility rule means: a consumer using the old schema can read messages produced with the new schema. This allows consumers to upgrade at their own pace. Never remove a required field without a deprecation period of at least 2 full deployment cycles. Never rename a field -- add the new field alongside the old one, migrate consumers, then remove the old field. When a breaking change is unavoidable, publish a new event topic (e.g., orders.v2.placed) and route consumers in parallel during migration.

The Chatty Service Antipattern

If profiling shows that fulfilling a single API request requires 20+ inter-service calls, the service decomposition is likely too fine-grained. This manifests as p99 latency >1s on operations that should be fast, and cascading failures where a single slow dependency causes widespread degradation. Resolution options in priority order: (1) redesign the boundary -- merge the chatty services into one if they represent a single cohesive domain; (2) introduce an aggregator service or Backend for Frontend (BFF) that makes parallel calls and assembles the response; (3) introduce a read-optimized projection (CQRS read model) that pre-computes the assembled response asynchronously. Never solve chatty services by simply increasing timeouts -- that treats the symptom, not the cause.

Service Discovery in Multi-Region or Hybrid Cloud Deployments

Standard Kubernetes DNS-based service discovery (ClusterIP services) does not work across clusters or clouds. When a microservices system spans multiple regions for availability or latency reasons, implement either: (1) a service mesh with multi-cluster federation (Istio multi-cluster, Linkerd multi-cluster) that handles cross-cluster mTLS and service discovery; or (2) an API gateway per region with explicit cross-region routing rules. Never rely on hardcoded IP addresses or external DNS for internal service-to-service calls -- it creates brittle dependencies that break during failover scenarios. Each region must be able to operate independently (active-active preferred, active-passive acceptable) without real-time dependency on a remote region for critical paths.

The "Too Many Sagas" Complexity Problem

When a system has 15+ orchestrated sagas, the cognitive overhead of understanding the overall system workflow becomes extreme. Symptoms: engineers cannot explain what happens to data in a failure scenario; compensation logic has never been tested in production; on-call incidents take hours to diagnose because the state machine is unclear. Mitigations: (1) consolidate simple linear workflows into choreography-based sagas (no central orchestrator, simpler mental model); (2) invest in saga state visualization -- a dashboard showing all in-flight saga instances and their current step is invaluable for operations; (3) test compensation logic explicitly in CI using contract tests; (4) consider whether some of the sagas can be eliminated by redesigning service boundaries to keep the transaction within a single service.

High-Security and Compliance Requirements (PCI-DSS, HIPAA, SOC 2)

Microservices that handle sensitive data (payment card data, health records, PII) require additional design constraints. Isolate regulated workloads into their own network segment (VPC, namespace) with explicit ingress/egress rules -- a microservices architecture makes this isolation tractable because the boundary is clear. Enforce mTLS on all communication to/from regulated services (service mesh is the practical path). Implement field-level encryption for sensitive fields at rest and in transit -- the encryption key must not be accessible to services that do not have a business need to read the plaintext. Audit every access to sensitive data: structured log entries with actor, timestamp, operation, and resource ID. Implement network egress filtering to prevent data exfiltration. Conduct threat modeling per service for regulated workloads -- the STRIDE model is appropriate.

Versioning When Multiple API Consumers Have Different Upgrade Timelines

Enterprise environments often have mobile clients (iOS/Android) that cannot force-upgrade users, third-party integrations on contractual SLAs, and internal services on independent release cycles. All of them consume the same API. Strategy: (1) maintain at minimum N and N-1 API versions simultaneously; (2) use a sunset header (Sunset: Sat, 01 Jan 2026 00:00:00 GMT) on deprecated endpoints to signal end-of-life to consumers; (3) implement usage analytics on each API version endpoint to identify which clients are still using deprecated versions before removing them; (4) never remove an API version that still has >0 calls per day without explicit coordinated migration confirmation from all consumers.


Example

Input: "We're building a food delivery platform. We have a team of 24 engineers split into 4 teams. We currently have a Node.js monolith that handles everything: user accounts, restaurant menus, order placement, payment processing, and delivery driver tracking. We're hitting scaling issues on the order placement and driver tracking parts specifically, and the payments team wants to deploy independently. What microservices architecture would you recommend?"


Output:

Microservices Design Specification: Food Delivery Platform

Context Summary

1. Scaling isolation: order placement and driver tracking are hot spots requiring independent scaling

2. Independent release cadence: payments team needs to ship without coordinating with other teams

3. Compliance isolation: payment data (PCI-DSS scope) benefits from boundary isolation


Service Boundary Map

Apply event storming to identify domain events: OrderPlaced, OrderAccepted (by restaurant), DriverAssigned, DriverLocationUpdated, OrderPickedUp, OrderDelivered, PaymentCaptured, PaymentRefunded, MenuItemUpdated, UserRegistered.

These events cluster into four bounded contexts that map directly to the four teams:

| Service Name | Bounded Context | Owns Aggregates | Database | Team Owner |

|----------------------|---------------------|--------------------------------------|-----------------------------|----------------|

| user-service | Identity | User, Address, Session | PostgreSQL + Redis (sessions)| Platform Team |

| catalog-service | Restaurant Catalog | Restaurant, Menu, MenuItem, Hours | PostgreSQL + Redis (read cache)| Catalog Team |

| orders-service | Order Management | Order, OrderLineItem, OrderStatus | PostgreSQL | Orders Team |

| payments-service | Payments | Payment, Refund, PaymentMethod | PostgreSQL (PCI segment) | Payments Team |

| delivery-service | Delivery Logistics | DeliveryJob, DriverLocation, Route | PostgreSQL + Redis (live loc)| Delivery Team |

| notifications-svc | Notifications | Notification, Template | PostgreSQL | Platform Team |

Notes on boundary decisions:


Communication Architecture

| Interaction | Pattern | Protocol | Justification |

|------------------------------------------|---------------------|------------------|----------------------------------------------------|

| Mobile/web client → API | Sync request | REST/HTTPS | User-facing; immediate response required |

| orders → catalog (price validation) | Sync call | gRPC | Must validate price and availability at order time |

| orders → payments (charge) | Orchestrated saga | Kafka events | Distributed transaction; compensation logic needed |

| orders → delivery (dispatch) | Async event | Kafka | Fire-and-forget; delivery picks up when ready |

| payments → orders (payment result) | Async event | Kafka | Saga response; eventual update acceptable |

| delivery → orders (status updates) | Async event | Kafka | Status sync; eventual consistency OK (< 2s lag) |

| any service → notifications | Async event | Kafka | Non-critical path; all notification triggers async |

| driver app → delivery (location) | WebSocket | WSS | 1--5 second location update frequency; persistent connection |

API Gateway: Single ingress via Kong. Handles JWT validation, rate limiting (100 req/min per authenticated user, 10 req/min unauthenticated), and routing. No business logic in the gateway.


Saga Design: Order Placement (Orchestration-Based)

Orchestrator: orders-service contains the saga orchestrator as an internal component (not a separate service -- the team is 6 engineers). The orchestrator state is persisted in the order_saga_state table in the orders PostgreSQL database.

| Step | Command Published | Kafka Topic | Success Event | Compensation Command |

|------|---------------------------|----------------------------|----------------------------|------------------------------------|

| 1 | ValidateCart | catalog.commands | CartValidated | -- (first step) |

| 2 | ReservePaymentMethod | payments.commands | PaymentMethodReserved | -- (authorization, not charge) |

| 3 | CapturePayment | payments.commands | PaymentCaptured | RefundPayment |

| 4 | DispatchDelivery | delivery.commands | DeliveryDispatched | CancelDelivery + RefundPayment |

| 5 | SendOrderConfirmation | notifications.commands | NotificationSent | -- (non-critical; log failure) |

Failure behavior:


Data Architecture Decisions

Outbox Pattern Implementation (applies to all services):

Each service has an outbox table:

CREATE TABLE outbox (
  id          UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  topic       VARCHAR(255) NOT NULL,
  payload     JSONB NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  published   BOOLEAN NOT NULL DEFAULT FALSE
);

State change and outbox insert happen in the same database transaction. A Debezium CDC connector reads the outbox table via PostgreSQL logical replication and publishes to Kafka. This guarantees exactly-once event publishing.

CQRS for delivery-service:

Driver location updates arrive at 10--50 updates/second per driver. Querying the current location of all active drivers in a geographic area for order dispatch cannot hit PostgreSQL at this rate. Design:

Schema for payments-service (PCI isolation):


Resilience Configuration

| Service | Dependency | Timeout | Circuit Breaker | Retry Policy | Fallback |

|------------------|---------------------|---------|------------------------------|--------------------------|-------------------------------------|

| orders-service | catalog (gRPC) | 1.5s | 40% errors / 10s window | 2x, 100ms + jitter | Reject order with "service unavailable" |

| orders-service | payments (Kafka) | N/A | N/A (async) | Kafka producer retry: 5x | Dead-letter topic: payments.dlq |

| delivery-service | Redis (geo queries) | 200ms | 70% errors / 5s window | 1x immediate | Fall through to PostgreSQL query |

| catalog-service | Redis (read cache) | 100ms | 80% errors / 5s window | None | Fall through to PostgreSQL |

Bulkhead configuration for orders-service:


Observability Setup

| Service | SLI | SLO Target |

|------------------|------------------------------|-----------------|

| orders-service | p99 order placement latency | < 800ms |

| orders-service | Error rate (5xx) | < 0.5% |

| payments-service | p99 payment capture latency | < 1200ms |

| payments-service | Error rate (5xx) | < 0.05% |

| delivery-service | p99 location update latency | < 300ms |

| catalog-service | p99 menu read latency | < 150ms |


Migration Plan from Monolith (Strangler Fig)

The monolith is not replaced in a single cutover. The sequence:

  1. Week 1--4 -- Payments Service: Extract the payments bounded context first because the team has the strongest deployment independence motivation. Stand up payments-service with its own database. Use a database sync job to dual-write payments data to the new service during transition. Route /api/v1/payments/* traffic through Kong to the new service. Decommission payment code in monolith once data sync is verified consistent for 2 weeks.
  1. Week 5--10 -- Catalog Service: Lowest risk extraction. Restaurant menu data is largely read-heavy. Stand up catalog-service. Migrate read traffic first (catalog reads are stateless). Then migrate write traffic. This service's extraction also produces the gRPC contract that orders-service will later consume.
  1. Week 11--18 -- Delivery Service: Stand up delivery-service with Redis geospatial layer. This is the second scaling hot spot. Route WebSocket connections from driver apps to the new service. Maintain a REST adapter in the monolith that proxies delivery status queries to the new service.
  1. Week 19--28 -- Orders Service + Saga: Most complex extraction. The orders flow currently has inline calls to payments and delivery. Replace these with the Kafka saga. This is the highest-risk migration step -- run shadow mode (execute both old and new order paths in parallel, compare results) for 2 weeks before cutting over.
  1. Week 29--32 -- User Service: Extract identity/session management last. Implement JWT issuance in the new service; the monolith becomes a JWT consumer rather than a session issuer.

Architecture Decision Records

| ADR # | Decision | Status | Rationale Summary |

|---------|---------------------------------------------------------------------------|----------|----------------------------------------------------------------------|

| ADR-001 | Orchestration-based saga for order placement | Accepted | 5-step transaction with non-trivial rollback logic; central visibility needed |

| ADR-002 | gRPC for orders → catalog price validation | Accepted | Synchronous, latency-sensitive; binary protocol reduces p99 |

| ADR-003 | Redis GEOADD for driver location read model | Accepted | Native geospatial queries, 50--50k driver scale, sub-10ms reads |

| ADR-004 | Outbox pattern via Debezium CDC for all event publishing | Accepted | Guarantees no lost events under database transaction rollback |

| ADR-005 | Payments service in isolated Kubernetes namespace (PCI scope reduction) | Accepted | Network isolation reduces PCI audit scope; required by security team|

| ADR-006 | Service mesh (Istio) deferred until 6+ services in production | Proposed | Current 6 services can use application-level circuit breakers; revisit at 10 services |

| ADR-007 | Strangler Fig migration rather than big-bang rewrite | Accepted | Monolith handles $X revenue; zero-downtime migration mandatory |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.