Migrating a Legacy Monolith to Microservices: A Case Study
Real-world case study of migrating a 500K LOC PHP monolith to a TypeScript/Node.js microservices architecture. Covers strangler fig pattern, data synchronization, and zero-downtime deployment.

- Rol
- Andrés RW
- Año
- Reading time
- 18 min de lectura
- Actualizado
Migrating a Legacy Monolith to Microservices: A Case Study
In 2023, I led the migration of a 12-year-old PHP monolith (500K LOC, 40 developers) to a modern TypeScript/Node.js microservices architecture. This is the honest story of what worked, what didn't, and the patterns that made it possible.
The Starting Point
The Monolith:
- PHP 7.4, Symfony 4, MySQL 5.7
- 500K lines of code, single deployment
- 40 developers across 4 teams
- Deploy every 2 weeks (if lucky)
- 99.5% uptime SLA (barely met)
- Technical debt: estimated 18 months to pay down
The Pain Points:
- Any change required full regression testing
- Database schema changes blocked all teams
- Scaling meant scaling the entire app
- Onboarding: 3 months to productive
- "It works on my machine" was a lifestyle
The Strategy: Strangler Fig Pattern
We didn't do a big bang rewrite. We used the Strangler Fig pattern—gradually replacing pieces of the monolith with new services while keeping the old system running.
┌─────────────────────────────────────────────────────────────┐
│ API Gateway (Kong) │
└─────────────────────────────────────────────────────────────┘
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ Legacy PHP │ │ New Service │ │ New Service │
│ (shrinking) │ │ (growing) │ │ (growing) │
└───────────────┘ └───────────────┘ └───────────────┘
│ │ │
└─────────────────────┼─────────────────────┘
▼
┌───────────────────┐
│ Shared MySQL │
│ (transitional) │
└───────────────────┘
Phase 1: Extract Read Models (Months 1-3)
We started with read-only extractions—zero risk, immediate value.
First Service: Product Catalog
- 15K LOC extracted from monolith
- Read-only GraphQL API over existing MySQL
- Deployed to Kubernetes, behind Kong gateway
- Result: 10x faster product searches, mobile team unblocked
// services/catalog/src/resolvers/product.resolver.ts
@Resolver(() => Product)
export class ProductResolver {
constructor(private readonly catalogService: CatalogService) {}
@Query(() => [Product], { name: "products" })
async products(
@Args("filter", { nullable: true }) filter: ProductFilter,
@Args("pagination", { nullable: true }) pagination: PaginationInput
): Promise<Product[]> {
return this.catalogService.findAll(filter, pagination);
}
@Query(() => Product, { name: "product", nullable: true })
async product(@Args("id", { type: () => ID }) id: string): Promise<Product | null> {
return this.catalogService.findById(id);
}
}
Phase 2: Write Paths with Event Sourcing (Months 4-8)
For write operations, we introduced event-driven architecture with an outbox pattern for reliability.
Order Service - The First Write Service
// services/orders/src/domain/order/order.aggregate.ts
export class Order extends AggregateRoot<OrderId> {
private constructor(
public readonly customerId: CustomerId,
public readonly items: OrderItem[],
public readonly status: OrderStatus,
public readonly version: number
) {
super();
}
static create(customerId: CustomerId, items: OrderItem[]): Order {
const order = new Order(customerId, items, "pending", 0);
order.addDomainEvent(new OrderCreatedEvent(order.id, customerId, items));
return order;
}
confirm(): void {
if (this.status !== "pending") {
throw new DomainError("Only pending orders can be confirmed");
}
this.status = "confirmed";
this.version++;
this.addDomainEvent(new OrderConfirmedEvent(this.id, this.customerId));
}
}
// services/orders/src/application/commands/confirm-order.command.ts
@CommandHandler(ConfirmOrderCommand)
export class ConfirmOrderHandler implements ICommandHandler<ConfirmOrderCommand> {
constructor(
private readonly orderRepo: OrderRepository,
private readonly eventBus: EventBus
) {}
async execute(command: ConfirmOrderCommand): Promise<void> {
const order = await this.orderRepo.findById(command.orderId);
if (!order) throw new NotFoundError("Order");
order.confirm();
await this.orderRepo.save(order);
// Events published via transactional outbox
}
}
Phase 3: Data Synchronization (Months 6-10)
The hardest part: keeping legacy and new systems in sync during transition.
Dual Write with CDC (Change Data Capture)
// infrastructure/cdc/debezium-config.ts
export const debeziumConfig = {
connector: "mysql",
database: {
hostname: "legacy-db",
port: 3306,
user: "cdc_user",
password: process.env.CDC_PASSWORD,
dbname: "legacy_app",
},
table: {
include: [
"orders",
"order_items",
"customers",
"products",
],
},
transform: {
// Transform legacy schema to new service events
"orders": (row) => ({
eventType: "OrderCreated",
payload: {
orderId: row.id,
customerId: row.customer_id,
total: row.total,
status: row.status,
createdAt: row.created_at,
},
}),
},
};
Saga Pattern for Distributed Transactions
// services/orders/src/application/sagas/create-order.saga.ts
export class CreateOrderSaga {
constructor(
private readonly commandBus: CommandBus,
private readonly eventBus: EventBus
) {}
@Saga()
async *handleOrderCreated(event: OrderCreatedEvent): AsyncGenerator<Command> {
// Step 1: Reserve inventory
yield new ReserveInventoryCommand({
orderId: event.orderId,
items: event.items.map((i) => ({
productId: i.productId,
quantity: i.quantity,
})),
});
try {
// Step 2: Process payment
yield new ProcessPaymentCommand({
orderId: event.orderId,
amount: event.total,
customerId: event.customerId,
});
// Step 3: Confirm order
yield new ConfirmOrderCommand({ orderId: event.orderId });
} catch (error) {
// Compensating transactions
yield new ReleaseInventoryCommand({ orderId: event.orderId });
yield new CancelOrderCommand({ orderId: event.orderId, reason: error.message });
throw error;
}
}
}
Phase 4: Database Decomposition (Months 9-14)
Each service got its own database. We used database-per-service with async replication for reporting.
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Orders DB │ │ Customers DB │ │ Catalog DB │
│ (PostgreSQL) │ │ (PostgreSQL) │ │ (PostgreSQL) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
└────────────────────┼────────────────────┘
▼
┌─────────────────┐
│ Analytics DB │
│ (ClickHouse) │
└─────────────────┘
Results After 14 Months
| Metric | Before | After | Change | |--------|--------|-------|--------| | Deploy frequency | 2/week | 50/day | 25x | | Lead time (commit→prod) | 3 weeks | 2 hours | 250x | | MTTR (mean time to recovery) | 4 hours | 15 min | 16x | | Change failure rate | 15% | 0.8% | 19x better | | Onboarding time | 3 months | 2 weeks | 6x faster | | P95 latency (API) | 800ms | 120ms | 6.6x faster | | Infrastructure cost | $45K/mo | $32K/mo | 29% less |
What Went Wrong (Lessons Learned)
1. Underestimated Data Migration Complexity
We spent 3 months on data sync tools. Invest in CDC tooling early.
2. Distributed Tracing Was an Afterthought
Added OpenTelemetry in month 8. Instrument from day one.
3. Too Many Services Too Soon
Started with 12 services, consolidated to 7. Start coarse, split when painful.
4. Testing Strategy Gaps
Integration tests caught 80% of bugs, but contract tests between services were missing initially. Add Pact tests when creating second service.
Key Technical Decisions
| Decision | Rationale | Outcome | |----------|-----------|---------| | TypeScript + Node.js | Team familiarity, hiring pool | ✅ Faster delivery | | PostgreSQL per service | ACID, team autonomy | ✅ Clear ownership | | Kafka for events | Durability, replay, ordering | ✅ Reliable eventing | | Kong API Gateway | Plugin ecosystem, performance | ✅ Rate limiting, auth | | Kubernetes (EKS) | Cloud-agnostic, scaling | ✅ Cost optimization | | OpenTelemetry + Jaeger | Vendor-neutral observability | ✅ Debugging distributed flows |
The Architecture Today
┌─────────────────────────────────────────────────────────────────┐
│ Kong API Gateway │
│ (Auth, Rate Limit, Routing, Logging) │
└─────────────────────────────────────────────────────────────────┘
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ Orders │ │ Customers │ │ Catalog │
│ Service │ │ Service │ │ Service │
│ (TS/Node) │ │ (TS/Node) │ │ (TS/Node) │
└───────┬───────┘ └───────┬───────┘ └───────┬───────┘
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ Orders DB │ │ Customers DB │ │ Catalog DB │
│ (PostgreSQL) │ │ (PostgreSQL) │ │ (PostgreSQL) │
└───────────────┘ └───────────────┘ └───────────────┘
│ │ │
└─────────────────────┼─────────────────────┘
▼
┌─────────────────────┐
│ Apache Kafka │
│ (Event Backbone) │
└─────────────────────┘
│
┌─────────┴─────────┐
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Payment │ │ Inventory │
│ Service │ │ Service │
└─────────────┘ └─────────────┘
Migration Checklist for Your Project
- [ ] Strangler Fig: Identify first read-only extraction
- [ ] API Gateway: Deploy Kong/Traefik in front of monolith
- [ ] Observability: OpenTelemetry + Jaeger + Prometheus from day 1
- [ ] CI/CD: Independent pipelines per service
- [ ] Data Sync: Debezium CDC for dual-write phase
- [ ] Contracts: Pact tests between every service pair
- [ ] Chaos Engineering: Game days before going live
- [ ] Runbooks: Every service has runbook with common incidents
- [ ] Team Topology: Align teams to service boundaries (Team Topologies)
Conclusion
The migration succeeded because we:
- Never stopped shipping—monolith kept running
- Extracted value early—read models first
- Invested in platform—CI/CD, observability, gateway
- Accepted temporary complexity—dual write, CDC, sagas
- Measured everything—deploy frequency, lead time, MTTR
The monolith is now 80% smaller. The remaining 20% (reporting, admin) will stay—it's not worth migrating.
This is part 1 of "Architecture Case Studies". Next: Building a Real-Time Collaboration Engine with WebRTC and CRDTs—how we built Google Docs-like editing for a design tool.
Etiquetas
También te puede interesar
Arquitectura12 min de lectura
Building Scalable Architectures with TypeScript: Patterns That Scale
A deep dive into architectural patterns that help TypeScript applications scale from startup to enterprise. Covers module boundaries, dependency injection, and domain-driven design principles.
Arquitectura15 min de lectura
TypeScript Testing Strategies: From Unit to E2E
A comprehensive guide to testing TypeScript applications. Covers unit testing with Vitest, integration testing with Testcontainers, contract testing with Pact, and E2E with Playwright.
Carrera10 min de lectura
Engineering Culture: Building Developer Experience That Scales
How to build a developer experience (DX) culture that attracts talent, accelerates delivery, and retains engineers. Covers tooling, documentation, onboarding, and psychological safety.