Microservices avec Claude Code
Découvrez microservices avec Claude Code. Conseils pratiques et exemples de code inclus.
Where Claude Code Shines in Microservices Development
Microservices architecture requires careful consideration of inter-service communication, data consistency, and shared library management. Claude Code can make consistent changes across multiple services while maintaining a bird’s-eye view of the entire project.
Service Decomposition Design
> I want to split an e-commerce site into microservices.
> Using domain-driven design bounded contexts as a reference,
> propose a service decomposition plan. Design the APIs for each service.
Claude Code proposes a service structure like the following:
- user-service: User management and authentication
- product-service: Product catalog management
- order-service: Order processing
- payment-service: Payment processing
- notification-service: Notification delivery
Inter-Service Communication
Synchronous Communication via REST API
// order-service/src/clients/product-client.ts
import axios from 'axios';
const PRODUCT_SERVICE_URL = process.env.PRODUCT_SERVICE_URL || 'http://product-service:3001';
export class ProductClient {
async getProduct(productId: string) {
const { data } = await axios.get(
`${PRODUCT_SERVICE_URL}/api/products/${productId}`,
{ timeout: 5000 }
);
return data;
}
async checkStock(productId: string, quantity: number): Promise<boolean> {
const { data } = await axios.post(
`${PRODUCT_SERVICE_URL}/api/products/${productId}/check-stock`,
{ quantity },
{ timeout: 5000 }
);
return data.available;
}
}
Asynchronous Communication via Event-Driven Architecture
// order-service/src/events/publisher.ts
import { SNSClient, PublishCommand } from '@aws-sdk/client-sns';
const sns = new SNSClient({ region: 'us-east-1' });
export async function publishOrderCreated(order: Order) {
await sns.send(new PublishCommand({
TopicArn: process.env.ORDER_EVENTS_TOPIC_ARN,
Message: JSON.stringify({
type: 'ORDER_CREATED',
data: {
orderId: order.id,
userId: order.userId,
items: order.items,
totalAmount: order.totalAmount,
},
timestamp: new Date().toISOString(),
}),
MessageAttributes: {
eventType: { DataType: 'String', StringValue: 'ORDER_CREATED' },
},
}));
}
// notification-service/src/handlers/order-handler.ts
import { SQSEvent } from 'aws-lambda';
export async function handleOrderEvent(event: SQSEvent) {
for (const record of event.Records) {
const message = JSON.parse(record.body);
const orderEvent = JSON.parse(message.Message);
if (orderEvent.type === 'ORDER_CREATED') {
await sendOrderConfirmationEmail(orderEvent.data);
}
}
}
Docker Compose Configuration
> Set up docker-compose so all services can be started together.
> Include hot reload support, shared network, and health checks.
version: '3.8'
services:
user-service:
build: ./services/user-service
ports: ['3001:3000']
environment:
- DATABASE_URL=postgresql://postgres:pass@user-db:5432/users
depends_on:
user-db:
condition: service_healthy
volumes:
- ./services/user-service/src:/app/src
healthcheck:
test: ['CMD', 'curl', '-f', 'http://localhost:3000/health']
interval: 10s
retries: 3
product-service:
build: ./services/product-service
ports: ['3002:3000']
environment:
- DATABASE_URL=postgresql://postgres:pass@product-db:5432/products
depends_on:
product-db:
condition: service_healthy
volumes:
- ./services/product-service/src:/app/src
order-service:
build: ./services/order-service
ports: ['3003:3000']
environment:
- DATABASE_URL=postgresql://postgres:pass@order-db:5432/orders
- PRODUCT_SERVICE_URL=http://product-service:3000
- USER_SERVICE_URL=http://user-service:3000
depends_on:
order-db:
condition: service_healthy
user-db:
image: postgres:16-alpine
environment:
POSTGRES_DB: users
POSTGRES_PASSWORD: pass
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U postgres']
interval: 5s
retries: 5
product-db:
image: postgres:16-alpine
environment:
POSTGRES_DB: products
POSTGRES_PASSWORD: pass
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U postgres']
interval: 5s
retries: 5
order-db:
image: postgres:16-alpine
environment:
POSTGRES_DB: orders
POSTGRES_PASSWORD: pass
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U postgres']
interval: 5s
retries: 5
Shared Library Management
> Create shared type definitions and utilities in packages/shared.
> Use npm workspaces for management.
// packages/shared/src/types/events.ts
export interface DomainEvent<T = unknown> {
type: string;
data: T;
timestamp: string;
correlationId: string;
}
export interface OrderCreatedEvent extends DomainEvent<{
orderId: string;
userId: string;
items: Array<{ productId: string; quantity: number }>;
totalAmount: number;
}> {
type: 'ORDER_CREATED';
}
Tips for Improving Development Efficiency
For microservices development, documenting your service structure and API conventions in CLAUDE.md is effective. For details, see the Complete CLAUDE.md Guide. Also leverage Refactoring Automation to maintain code quality. Setting up hooks per service development flow is also useful.
Summary
With Claude Code, you can efficiently build everything from microservices design to implementation, Docker configuration, and CI/CD. It’s especially powerful for cross-service tasks like sharing type definitions and maintaining event schema consistency.
For more details, see the official Anthropic documentation.
Related Posts
Maîtriser les Hooks de Claude Code : Formatage automatique, tests automatiques et plus encore
Apprenez à configurer le formatage et les tests automatiques avec les hooks de Claude Code. Inclut des exemples de configuration pratiques et des cas d'utilisation concrets.
Configuration des serveurs MCP dans Claude Code et cas d'utilisation pratiques
Un guide complet sur les capacités des serveurs MCP de Claude Code. Apprenez à connecter des outils externes, configurer des serveurs et découvrez des exemples d'intégration concrets.
Le guide complet pour rédiger un CLAUDE.md : Bonnes pratiques de configuration de projet
Un guide approfondi pour rédiger des fichiers CLAUDE.md efficaces. Apprenez à communiquer votre stack technologique, vos conventions et la structure de votre projet pour maximiser la qualité des réponses de Claude Code.