Microservices patterns

From FerroxLabs/wayland · View interactive version

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

How to use this skill

Skill file

Microservices Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Identify the Core Problem Category

Before recommending any pattern, classify the user's problem into one of five categories. The wrong category leads to the wrong pattern family.

Ask the user clarifying questions if the problem category is not immediately clear. Do not proceed to pattern selection until the category is confirmed.

2. Map the User's System Context

Establish the architectural parameters that constrain pattern choices. These directly affect which patterns are viable.

3. Apply the Pattern Decision Framework

For each problem category identified in Step 1, walk through the specific decision tree:

For decomposition:

For communication:

For data consistency:

For resilience:

For cross-cutting concerns:

4. Identify Anti-Patterns to Avoid

Explicitly name and explain anti-patterns that match the user's context. Anti-pattern awareness prevents expensive mistakes.

5. Provide a Concrete Implementation Plan

Translate the selected patterns into a phased implementation sequence.

6. Define Observability Requirements

No microservices pattern recommendation is complete without observability specifications. A pattern that cannot be monitored in production is incomplete.

7. Document Pattern Decisions as ADRs

Every selected pattern must be recorded in an Architecture Decision Record.


Output Format

## Microservices Pattern Recommendation

### Context Summary
- **System:** [service/system name]
- **Problem Category:** [Decomposition / Communication / Data Consistency / Resilience / Cross-Cutting]
- **Team Size:** [N engineers]
- **Scale Target:** [requests/sec or users]
- **Consistency Requirement:** [strong / eventual, acceptable window]
- **Existing Infrastructure:** [message broker, service mesh, API gateway]

---

### Pattern Selection Decision Matrix

| Pattern | Fits Problem? | Complexity | Operational Burden | Recommended? |
|---------|--------------|------------|-------------------|--------------|
| [Pattern 1] | Yes/No | Low/Med/High | Low/Med/High | ✅ / ❌ / ⚠️ |
| [Pattern 2] | Yes/No | Low/Med/High | Low/Med/High | ✅ / ❌ / ⚠️ |
| [Pattern 3] | Yes/No | Low/Med/High | Low/Med/High | ✅ / ❌ / ⚠️ |

**Legend:** ✅ Recommended -- ⚠️ Conditional -- ❌ Not Recommended

---

### Recommended Patterns

#### Primary Pattern: [Pattern Name]
**Problem it solves:** [1-2 sentences]
**Why this over alternatives:** [Specific trade-off reasoning tied to user's context]
**Implementation summary:**
- [Concrete step 1]
- [Concrete step 2]
- [Concrete step 3]

**Configuration parameters:**

// Example configuration or pseudocode


**Failure modes to handle:**
- [Failure scenario 1] → [Mitigation]
- [Failure scenario 2] → [Mitigation]

---

#### Supporting Pattern: [Pattern Name]
**Problem it solves:** [1-2 sentences]
**Integration with primary pattern:** [How they work together]
**Implementation notes:**
- [Concrete note 1]
- [Concrete note 2]

---

### Anti-Patterns to Avoid in This Context
1. **[Anti-pattern name]** -- [Why it is specifically dangerous for this user's setup]
2. **[Anti-pattern name]** -- [Why it is specifically dangerous for this user's setup]

---

### Observability Checklist
- [ ] Correlation ID propagated on all inter-service calls
- [ ] RED metrics (Rate, Error, Duration) instrumented per service
- [ ] Distributed traces exported to [Jaeger/Zipkin/vendor]
- [ ] `/health/live` and `/health/ready` endpoints exposed
- [ ] Alert thresholds set: error rate > 1%, P99 > [N]ms

---

### ADR Stub

**ADR-[NNN] -- [Pattern Name] for [Use Case]**
- **Status:** Proposed
- **Date:** [YYYY-MM-DD]
- **Context:** [What problem exists]
- **Decision:** [What pattern is chosen]
- **Consequences:** [Trade-offs, operational implications]
- **Alternatives rejected:** [Pattern name] -- [Reason]

Rules

  1. NEVER recommend microservices to a team that does not need them. If the user's team is fewer than 5 engineers or their system handles fewer than 1,000 requests/day, recommend a modular monolith first. The operational overhead of microservices -- distributed tracing, separate deployments, network failure handling -- requires mature DevOps capability to manage.
  1. NEVER recommend shared databases across services. If a user's services share a database schema or connection pool, call this out as a critical architectural flaw before discussing any other patterns. Shared databases make service-level independent deployments impossible and invalidate most data isolation benefits.
  1. ALWAYS pair the Saga pattern with compensating transactions. Never describe a saga flow without explicitly defining the rollback/compensation step for every forward action. A saga without compensating transactions is not a pattern -- it is an incomplete implementation waiting to corrupt data.
  1. NEVER recommend 2PC (two-phase commit) across service boundaries. Two-phase commit requires all participating services to be synchronously available and creates distributed locks. In a distributed system with independent failure domains, 2PC reduces overall availability to the product of each participant's availability. At three 99.9% available services, 2PC reduces availability to 99.7%.
  1. ALWAYS specify timeout values and retry limits when recommending resilience patterns. A circuit breaker recommendation without specific threshold values (failure count, time window, half-open timeout) gives the user no actionable guidance. Default values must be included even if noted as "adjust based on SLA."
  1. NEVER recommend the Sidecar or Service Mesh pattern without confirming the user is on Kubernetes or an equivalent container orchestration platform. Sidecar injection, mTLS, and traffic management via Envoy/Linkerd require container orchestration infrastructure. On bare VMs or serverless platforms, these patterns are not applicable.
  1. ALWAYS include observability requirements when describing any pattern. A pattern description that does not include how to observe it in production is incomplete. Every pattern recommendation must specify the minimum metrics, log fields, and trace spans required to operate it safely.
  1. NEVER recommend choreography-based sagas when the saga involves more than 8 steps. Beyond 8 steps, debugging choreography sagas (where state is implicit across events) becomes prohibitively difficult. Above this threshold, recommend orchestration-based sagas with an explicit saga coordinator (e.g., Temporal, AWS Step Functions, Conductor).
  1. ALWAYS warn about the Distributed Monolith anti-pattern when discussing decomposition. Any decomposition strategy recommendation must include explicit guidance on how to verify that the resulting services are actually independently deployable -- by checking for shared databases, shared in-process state, and synchronized deployment pipelines.
  1. NEVER conflate async messaging with eventual consistency guarantees. Publishing an event to Kafka or RabbitMQ does not guarantee the event is processed -- consumers can fail, queues can fill, dead-letter queues can overflow. Always specify the at-least-once or exactly-once delivery guarantee of the chosen broker and how the consuming service handles duplicate messages (idempotency keys, deduplication windows).

Edge Cases

Brownfield Decomposition -- Tightly Coupled Database Schema

When a user is extracting services from a monolith that shares a large relational database with foreign keys crossing business domain boundaries:

High-Throughput Event Sourcing -- Projection Rebuilding Time

When a user implements event sourcing for a high-volume service (millions of events per aggregate type):

Circuit Breaker in a Serverless Environment

When a user wants circuit breakers but is running on AWS Lambda, Google Cloud Functions, or Azure Functions:

Multi-Region Deployment and the Saga Pattern

When a user is running sagas across multiple geographic regions:

Versioning Breaking Changes in Event-Driven Systems

When a user needs to evolve the schema of domain events that multiple consumers depend on:

Service Mesh Adoption in a Mixed-Technology Environment

When a user is adopting Istio or Linkerd in a fleet where not all services are containerized:

Idempotency in At-Least-Once Messaging Systems

When a user is processing messages from Kafka, SQS, or RabbitMQ (all of which guarantee at-least-once delivery):


Example

Input:

"We have a monolithic Node.js e-commerce application. Order processing, inventory management, and payment are all in one codebase. We're a team of 10 engineers. We're experiencing deployment bottlenecks -- any change to payment code requires a full regression test and redeploy of the entire app. We deploy to AWS and already use SQS and PostgreSQL. We want to break this apart but we are worried about keeping orders, inventory, and payments consistent when things go wrong."


Output:

Microservices Pattern Recommendation

Context Summary


Pattern Selection Decision Matrix

| Pattern | Fits Problem? | Complexity | Operational Burden | Recommended? |

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

| Strangler Fig (decomposition) | Yes | Medium | Low | ✅ |

| Choreography-based Saga | Yes | Medium | Medium | ✅ |

| Orchestration-based Saga | Yes | Medium-High | Medium | ⚠️ Evaluate if steps grow |

| Two-Phase Commit | No -- reduces availability | High | High | ❌ |

| Big-Bang Rewrite | No -- high risk | Very High | Very High | ❌ |

| Database-per-Service | Yes (phase 2) | High | Medium | ✅ Phase 2 only |

| Circuit Breaker (Resilience pattern) | Yes | Low | Low | ✅ |

| BFF (API Gateway variant) | No -- internal concern | Medium | Medium | ❌ Not needed yet |

Legend: ✅ Recommended -- ⚠️ Conditional -- ❌ Not Recommended


Recommended Patterns

Primary Pattern: Strangler Fig for Phased Decomposition

Problem it solves: Enables extracting Payment, Inventory, and Order services from the monolith incrementally without a risky big-bang rewrite. New services go live alongside the monolith, which continues to handle un-migrated flows.

Why this over alternatives: A big-bang rewrite with a team of 10 on a production e-commerce system is high-risk and typically takes 2-3x longer than estimated. The Strangler Fig allows you to ship value continuously during the migration and roll back individual service extractions if problems arise.

Implementation summary:

Configuration parameters (routing proxy):

// Express-based routing proxy configuration
const routingRules = [
  { prefix: '/payments', target: process.env.PAYMENT_SERVICE_URL },
  { prefix: '/inventory', target: process.env.INVENTORY_SERVICE_URL },
  { prefix: '/orders', target: process.env.ORDER_SERVICE_URL },
  { prefix: '/', target: process.env.MONOLITH_URL }  // catch-all fallback
];

// Each rule evaluated in order -- first match wins
// Monolith remains the default until all routes are migrated

Failure modes to handle:


Primary Pattern: Choreography-based Saga for Order -- Inventory -- Payment Consistency

Problem it solves: Maintains data consistency across Order, Inventory, and Payment services when processing an order -- without distributed transactions or shared database locks.

Why this over alternatives: Your team already has SQS, which is an ideal choreography bus for this use case. The order processing saga has 5 or fewer steps (within the 8-step choreography threshold), making choreography debuggable. Two-phase commit is rejected because it reduces system availability to the product of each service's availability: three 99.9% services = 99.7% overall under 2PC.

Saga flow design:

1. Order Service: Create order record, status = PENDING
   → Publish: OrderCreated {orderId, items[], customerId, totalAmount}

2. Inventory Service: Receives OrderCreated
   → Reserve stock for each line item
   → On success: Publish InventoryReserved {orderId, reservationId}
   → On failure (out of stock): Publish InventoryReservationFailed {orderId, reason}

3. Payment Service: Receives InventoryReserved
   → Charge customer payment method
   → On success: Publish PaymentCaptured {orderId, paymentId, amount}
   → On failure: Publish PaymentFailed {orderId, reason}

4. Order Service: Receives PaymentCaptured
   → Update order status = CONFIRMED
   → Publish OrderConfirmed {orderId}

5. [Notification Service, Fulfillment Service react to OrderConfirmed independently]

COMPENSATING TRANSACTIONS (mandatory):
- If PaymentFailed → Inventory Service subscribes, releases reservation
  Publish InventoryReleased {orderId, reservationId}
- If InventoryReservationFailed → Order Service subscribes, updates status = FAILED
- Order Service always has a terminal state: CONFIRMED or FAILED -- never stuck in PENDING

SQS Queue Configuration:

Queues required:
- order-events (OrderCreated, OrderConfirmed)
- inventory-events (InventoryReserved, InventoryReservationFailed, InventoryReleased)
- payment-events (PaymentCaptured, PaymentFailed)

Each queue:
- Visibility timeout: 30 seconds (must exceed max consumer processing time)
- Dead-letter queue: order-events-dlq, inventory-events-dlq, payment-events-dlq
- DLQ maxReceiveCount: 3 (move to DLQ after 3 failed processing attempts)
- Message retention: 4 days (default SQS; increase to 14 days for audit)

Message format (all events):
{
  "eventType": "OrderCreated",
  "eventVersion": "1",
  "eventId": "01ARZ3NDEKTSV4RRFFQ69G5FAV",  // ULID for ordering + uniqueness
  "correlationId": "...",  // propagated from original HTTP request
  "occurredAt": "2024-03-15T14:22:00.000Z",
  "payload": { ... }
}

Idempotency implementation (Node.js consumer):

async function processInventoryReserved(message) {
  const { eventId } = message;
  
  // Atomic idempotency check + business action in one transaction
  await db.transaction(async (trx) => {
    // Will throw unique constraint violation if already processed
    await trx('processed_events').insert({
      event_id: eventId,
      processed_at: new Date(),
      consumer: 'payment-service'
    });
    
    // Business logic only executes if insert succeeded
    await chargePaymentMethod(message.payload);
  });
}

Failure modes to handle:


Supporting Pattern: Circuit Breaker for Payment Provider Calls

Problem it solves: Prevents the Payment service from hanging indefinitely when the upstream payment gateway is slow or failing, which would cause SQS message consumers to block and eventually exhaust the processing pool.

Integration with primary pattern: The Payment service consumer processes InventoryReserved messages and calls the payment gateway. Without a circuit breaker, a payment gateway outage causes all Inventory Reserved messages to time out, the SQS visibility timeout expires repeatedly, and messages eventually land in the DLQ -- requiring manual intervention.

Implementation notes (using opossum circuit breaker for Node.js):

const CircuitBreaker = require('opossum');

const paymentGatewayOptions = {
  timeout: 5000,           // 5s timeout -- reject if gateway doesn't respond
  errorThresholdPercentage: 50,  // Open if 50% of calls fail in rolling window
  rollingCountTimeout: 10000,    // 10-second rolling window
  resetTimeout: 30000      // Try half-open probe after 30 seconds
};

const breaker = new CircuitBreaker(callPaymentGateway, paymentGatewayOptions);

breaker.fallback(() => {
  // When circuit is open, publish PaymentFailed immediately
  // rather than waiting for timeout on every message
  return { success: false, reason: 'PAYMENT_GATEWAY_UNAVAILABLE' };
});

breaker.on('open', () => {
  metrics.increment('circuit_breaker.payment_gateway.open');
  logger.error('Payment gateway circuit breaker opened');
});

Anti-Patterns to Avoid in This Context

  1. Distributed Monolith -- If the extracted Payment service can only be deployed when the Order service is also deployed (e.g., because they share a database migration script or a shared library with domain objects), you have created a distributed monolith. Verify independence by having a team member deploy the Payment service to staging without touching Order or Inventory. If it fails, the boundary is not clean.
  1. Saga Without Compensating Transactions -- Do not go live with the inventory reservation or payment capture saga steps until the compensating transactions (releaseInventoryReservation, triggered by PaymentFailed) are implemented, tested under SQS message failure injection, and confirmed to reach a terminal order state. An order stuck in PENDING indefinitely will cause customer service escalations and revenue leakage.
  1. Shared Domain Model Library -- Do not create an NPM package called @ecommerce/models that exports Order, Payment, and Inventory TypeScript interfaces and share it across all three services. When the Order model needs a new field, you will be forced to coordinate releases across all three services. Each service owns its own internal model. Cross-service data is represented by event payload schemas, not shared classes.

Observability Checklist


ADR Stub

ADR-001 -- Choreography-based Saga for Order Processing Consistency

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.