Claude Code for Microservices Architecture: Patterns and Automation
Claude Code accelerates microservices development by generating service scaffolds, Docker Compose configurations, OpenAPI specs, and inter-service communication boilerplate from natural-language descriptions. Rather than manually wiring together service registries, health checks, and message queues, you describe the architecture and Claude Code produces the files. This guide covers the full lifecycle: decomposition, implementation, testing, and operational patterns.
Service Decomposition with Claude Code
Start with a monolith description and ask Claude Code to suggest a decomposition:
claude "Given this monolith (show codebase), suggest a microservices decomposition.
For each service identify:
1. Bounded context (what domain data it owns)
2. API surface (which endpoints move there)
3. Dependencies on other services
4. Estimated size (LOC)
Output as a structured table and a system diagram in ASCII art"
A typical decomposition for an e-commerce monolith yields:
| Service | Owns | Talks To | Size |
|---|---|---|---|
user-service |
Users, auth tokens | None | ~2K LOC |
product-service |
Catalog, inventory | None | ~3K LOC |
order-service |
Orders, cart | user, product, payment | ~4K LOC |
payment-service |
Transactions | order | ~2K LOC |
notification-service |
Emails, SMS | Subscribes to order events | ~1K LOC |
Decomposition principle: Services own their data. order-service holds the order table; it never reads the product table directly — it queries product-service via HTTP or a cached snapshot.
Scaffolding Services
claude "Scaffold user-service as a FastAPI Python app:
- POST /users — create user (email, hashed password)
- GET /users/{id} — get user by ID
- POST /auth/token — return JWT
- GET /health — liveness check
- Use SQLAlchemy async + PostgreSQL
- Include Dockerfile and docker-compose.yml for local dev"
Claude Code generates the complete service structure:
user-service/
app/
main.py
models.py
schemas.py
database.py
routers/
users.py
auth.py
tests/
test_users.py
Dockerfile
docker-compose.yml
requirements.txt
.env.example
Docker Compose for Local Multi-Service Development
claude "Generate a docker-compose.yml that runs all 5 services with:
- PostgreSQL instances (one per service, separate databases)
- Redis for session caching
- Kafka for event streaming
- Traefik as API gateway on port 80
- Service health checks
- Shared network"
Resulting docker-compose.yml skeleton:
version: '3.9'
networks:
microservices:
driver: bridge
services:
traefik:
image: traefik:v3.0
command:
- "--api.insecure=true"
- "--providers.docker=true"
- "--entrypoints.web.address=:80"
ports:
- "80:80"
- "8080:8080" # Traefik dashboard
volumes:
- "/var/run/docker.sock:/var/run/docker.sock"
networks: [microservices]
user-service:
build: ./user-service
environment:
DATABASE_URL: postgresql+asyncpg://user:pass@user-db:5432/users
JWT_SECRET: ${JWT_SECRET}
labels:
- "traefik.http.routers.user.rule=PathPrefix(`/api/users`) || PathPrefix(`/api/auth`)"
depends_on:
user-db:
condition: service_healthy
networks: [microservices]
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 10s
retries: 3
user-db:
image: postgres:16-alpine
environment:
POSTGRES_DB: users
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
networks: [microservices]
healthcheck:
test: ["CMD", "pg_isready", "-U", "user"]
interval: 5s
retries: 5
kafka:
image: confluentinc/cp-kafka:7.6.0
environment:
KAFKA_KRAFT_MODE: "true"
KAFKA_PROCESS_ROLES: broker,controller
KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,CONTROLLER://0.0.0.0:9093
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
CLUSTER_ID: "microservices-local-001"
networks: [microservices]
Inter-Service Communication Patterns
Synchronous (HTTP)
claude "In order-service, implement a product client that:
- Calls product-service GET /products/{id}
- Uses httpx async with a 5-second timeout
- Retries on 503 with exponential backoff (max 3 attempts)
- Caches results in Redis for 60 seconds
- Raises ServiceUnavailableError if product-service is down"
Asynchronous (Event-Driven)
Events decouple services — order-service publishes order.created; notification-service subscribes:
# order-service/events.py (producer)
import json
from aiokafka import AIOKafkaProducer
async def publish_order_created(producer: AIOKafkaProducer, order: dict) -> None:
event = {
"event_type": "order.created",
"order_id": order["id"],
"user_id": order["user_id"],
"total": order["total"],
"timestamp": order["created_at"].isoformat(),
}
await producer.send_and_wait(
topic="orders",
value=json.dumps(event).encode(),
key=str(order["id"]).encode(),
)
# notification-service/consumer.py (consumer)
from aiokafka import AIOKafkaConsumer
import json
async def consume_orders(email_service):
consumer = AIOKafkaConsumer(
"orders",
bootstrap_servers="kafka:9092",
group_id="notification-service",
auto_offset_reset="earliest",
)
await consumer.start()
async for msg in consumer:
event = json.loads(msg.value)
if event["event_type"] == "order.created":
await email_service.send_order_confirmation(
user_id=event["user_id"],
order_id=event["order_id"],
)
Mid-Article Offer
Scaling microservices requires disciplined prompting patterns. The Power Prompts 300 ($29) includes architecture review prompts, Docker debugging patterns, and service communication templates that work directly in Claude Code sessions.
CLAUDE.md for Microservices Repos
A monorepo CLAUDE.md keeps Claude Code oriented across all services (see Claude Code Complete Guide for the full CLAUDE.md reference):
# E-Commerce Microservices
## Architecture
- user-service — FastAPI, PostgreSQL, port 8001
- product-service — FastAPI, PostgreSQL, port 8002
- order-service — FastAPI, PostgreSQL + Kafka producer, port 8003
- payment-service — FastAPI, Stripe integration, port 8004
- notification-service — Python worker, Kafka consumer, no HTTP API
## Rules
- Services NEVER share a database
- Cross-service data access via HTTP client (sync) or Kafka events (async)
- All services expose GET /health returning {"status": "ok"}
- Use httpx[asyncio] for HTTP clients, never requests (blocking)
- OpenAPI spec auto-generated, stored in docs/openapi/{service}.json
## Test commands
- Single service: cd {service} && pytest
- Integration: docker compose -f docker-compose.test.yml up --abort-on-container-exit
Testing Microservices
claude "Write integration tests for order-service that:
- Mock product-service and user-service with respx
- Mock Kafka producer
- Test the happy path: create order, verify event published
- Test product-service unavailable: verify graceful error
- Use pytest-asyncio and a test PostgreSQL via testcontainers"
Benchmark: Teams using Claude Code to generate integration tests for microservices reduce test setup time by approximately 60% — test boilerplate (fixtures, mocks, container setup) takes 30–60 minutes manually but under 5 minutes with Claude Code.
Kubernetes Manifest Generation
For production deployments, see the dedicated Kubernetes YAML Automation guide. A quick example:
claude "Generate Kubernetes Deployment and Service manifests for user-service:
- 3 replicas, rolling update (maxSurge=1)
- Resource limits: 256Mi memory, 0.25 CPU
- Readiness probe: GET /health every 5s
- ConfigMap for non-secret env vars
- Reference a Secret named user-service-secrets for DATABASE_URL and JWT_SECRET"
Observability Setup
claude "Add OpenTelemetry tracing to all FastAPI services:
- Auto-instrument FastAPI, SQLAlchemy, httpx, and Kafka
- Export to Jaeger running at jaeger:4317
- Add a trace-id header to all outgoing HTTP requests
- Include the service name as a span attribute"
Distributed tracing is essential for microservices — a single user request touches 3–5 services, and without trace correlation, debugging latency issues is nearly impossible.
Related Guides
- Claude Code Complete Guide — CLAUDE.md patterns, hooks, parallel subagents, and worktree isolation for large refactors
- Claude Agent SDK Guide — Agentic loop patterns for service orchestration
- GitHub Actions CI/CD with Claude Code — Automated pipelines for multi-service deployments
- Docker Container Setup with Claude Code — Docker fundamentals and Claude Code integration
Frequently Asked Questions
Can Claude Code understand a large monolith and suggest decomposition?
Yes — share the directory structure and key files using @ references in Claude Code. Claude Code reads the codebase and produces a bounded-context analysis. For very large codebases (50K+ LOC), use the 200K context window with /compact if needed.
What's the best event broker for microservices with Claude Code support?
Kafka is the most widely documented option and Claude Code produces accurate Kafka configuration. RabbitMQ and Redis Streams are also well-supported. For simpler setups, Claude Code can use PostgreSQL with a polling pattern (no separate broker needed).
How does Claude Code handle database migrations across services?
Each service has its own migration folder (Alembic for Python, Flyway for Java). Claude Code generates migration files when you change models. For zero-downtime migrations, ask Claude Code for the expand-contract pattern specific to your ORM.
Should I use REST or gRPC for inter-service communication?
For most teams, REST with OpenAPI is simpler and Claude Code generates better REST clients than gRPC stubs. Use gRPC when you need streaming RPCs or binary efficiency at high throughput (10K+ req/s per link). Ask Claude Code to generate either based on your requirements.
How do I prevent cascading failures?
Ask Claude Code to implement the circuit breaker pattern using tenacity (Python) or opossum (Node.js). A circuit breaker stops retrying after N consecutive failures, preventing a slow upstream from blocking all threads in the calling service.
What is the right service count for a small team?
As a rule: one service per engineer is a reasonable upper bound. A 3-person team running 15 microservices creates more operational overhead than value. Claude Code can help you evaluate whether a modular monolith (separate modules, one deployment) is more appropriate for your team size.
Go Deeper
Power Prompts 300 — $29 — 300 tested prompts for backend architecture, Docker Compose debugging, Kubernetes manifest generation, and API design — all tuned for Claude Code sessions.
30-day money-back guarantee. Instant download.