# Microservice Patterns

## Overview

Microservice patterns address the challenges of building, deploying, and operating distributed systems composed of independently deployable services. They solve problems around routing, discovery, migration, cross-cutting concerns, and client-specific API needs.

## Pattern Comparison

| Pattern | Purpose | Scope | Key Benefit |
|---|---|---|---|
| **API Gateway** | Single entry point routing to backend services | Infrastructure / Edge | Centralised routing, auth, rate limiting |
| **Service Discovery** | Dynamic registration and lookup of services | Infrastructure | No hardcoded service addresses |
| **Strangler Fig** | Incremental migration from monolith to microservices | Migration | Zero-downtime, gradual replacement |
| **Sidecar** | Helper process for cross-cutting concerns | Deployment | Separation of business and infra logic |
| **Backend for Frontend** | Client-specific API aggregation | API Layer | Optimised APIs per client type |

## When to Use Which

- **Need a single entry point for external clients?** Use **API Gateway** to route, authenticate, and rate-limit at the edge.
- **Services come and go dynamically (scaling, deployments)?** Use **Service Discovery** so callers find services without hardcoded URLs.
- **Migrating a monolith gradually?** Use **Strangler Fig** to route traffic between old and new systems incrementally.
- **Multiple services need the same infra concerns (logging, TLS, metrics)?** Use **Sidecar** to handle them uniformly without modifying each service.
- **Mobile and web clients need different API shapes?** Use **Backend for Frontend** to create optimised aggregation layers per client.

## Relationships Between Patterns

- **API Gateway** often incorporates **Service Discovery** to find backend services dynamically.
- **Strangler Fig** is commonly implemented inside an **API Gateway** (routing rules shift traffic).
- **Sidecar** runs alongside each service instance; the **API Gateway** is a cluster-wide singleton.
- **Backend for Frontend** sits behind the **API Gateway** or is itself a specialised gateway per client.
- **Service Discovery** is a foundational pattern used by nearly all others.

## Design Guidelines

1. **Start simple** — not every system needs all five patterns on day one.
2. **Prefer convention over configuration** — use naming conventions for discovery and routing.
3. **Design for failure** — every network call can fail; add timeouts, retries, and circuit breakers.
4. **Observe everything** — distributed tracing, metrics, and structured logging are essential.
5. **Own your data** — each microservice owns its data store; no shared databases.
