Chapter 23 of 27 · Part 10: Refactoring to microservices

Refactoring a monolith: the strangler application

FTGO cannot stop the business for a year to rewrite its monolith. This chapter shows how to move to services step by step while the monolith keeps running: set a goal, grow new services around the old code, glue the two together, and switch traffic safely.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 22 we scaled FTGO's services with replicas, partitions, caches and autoscaling. All of that assumed a fresh start. That left one problem open: FTGO has a large monolith in production today, and it cannot be switched off.

This chapter

How do you move a running monolith to services without a big-bang rewrite? By the end you can decide whether to migrate, choose what to move first, glue new services to old code, switch traffic with a way back, and keep transactions and logins working.

Is the monolith really the problem? Set a goal first

Problem

FTGO's monolith ships every few weeks, and the plan for the year says only "move to microservices". Twelve months later there are five new services, releases are still slow, and nobody can say whether anything improved, because nobody said what "better" meant.

Microservices are a means, not the goal. Istio merged its control plane back into one process, and Segment moved back to a monolith after a small team drowned in per-service deployments. Slow delivery, buggy releases and poor scaling are real pain, but check first whether the monolith causes them or the process around it does. Good automated tests may be enough. Many common reasons for the move are weaker than they sound:

Common claimWhy it may not justify the move
"We can scale horizontally"A monolith can run many copies too. The real limit is usually the database.
"Teams will be autonomous"A modular monolith can give autonomy as well. Part of it is a change of mindset.
"Features will ship faster"For a small team, services can slow things down. Find the root cause of slow delivery first.
"Continuous delivery"Possible with a monolith, though harder as the team and the code grow.
Strong reasons: the database can only scale vertically and has become too costly; the team has outgrown the application; or the technology stack is deprecated, or you need several stacks.
Solution · Set a goal, then chip away

Name the outcome you want, such as more load or faster shipping, and the metrics that show it. Try easier fixes first. If services are still the answer, move one or two pieces, run them in production, and check whether you got closer.

Start with a goal, then chip away Name the goal, try easier fixes, move in small steps and reflect. Pick the first service by benefit and ease. 1 Name the goal not "microservices" 2 Try easier ways e.g. more copies 3 Chip away small steps, learn 4 Reflect in production, adjust What to split first Benefit a load bottleneck? code that changes often? Ease how tangled is it with the rest? First picks: real impact, low-hanging fruit Snap CI merged its young services back into one app, learned the domain, then split again a year later.

An easier fix can win. More copies of the monolith behind a load balancer may beat a long decomposition, and if one part is the bottleneck, moving out just that 10 percent may be enough. The monolith is rarely the enemy; it often stays, only smaller. Measure progress against your reason, and ask the engineers how it feels: their feedback is the most valuable signal.

If your reason isWatch
Team autonomyDependencies between teams, feature branch lifetime, merge requests
Continuous deliveryDeployments per period, cycle time, lead time
ScalabilityIncidents during load peaks, response time, machine size needed
Cost

Metrics take discipline: the team must be willing to stop, or merge services back, if the numbers do not move. And a goal says nothing about how to get there while restaurants keep ordering.

Do not rewrite: strangle the monolith

FTGO sets its goal: ship the delivery features weekly instead of monthly. The next question is how to get there.

Problem

An architect proposes a clean rewrite: freeze the monolith, build all services from scratch, switch over in one weekend. Meanwhile the business keeps changing, the rewrite chases a moving target, and nothing reaches customers until the end.

Two ways to migrate Big bang rewrite Years of duplicate work Business keeps changing No value until the end Strangler application Grow services around it Value early and often Monolith shrinks over time The only thing a big-bang rewrite guarantees is a big bang.
Solution · Strangler application

Build new services around the monolith and move functionality into them piece by piece, until the monolith is small or gone. The name comes from the strangler fig, a vine that grows around a tree. Every step ships and delivers value on its own. Change the monolith as little as possible, and build infrastructure only as you need it.

There are three ways to shrink the monolith, and the rest of this chapter uses all of them: build new features as services, split the user interface from the back end, and extract existing business capabilities.

Ways to shrink the monolith Three strategies New features built as services Split UI front end vs back end Extract business capabilities Law of Holes: when you are in a hole, stop digging. Build new features outside the monolith.
Cost

For months or years FTGO runs two systems side by side, and each new service still needs data and behavior that live in the monolith.

Stop digging: build new features as services

The cheapest first step does not touch existing code at all: stop making the monolith bigger.

Problem

Customers complain that late orders arrive with no warning. Product wants a Delayed Delivery feature that spots late orders and tells the customer and support. Built inside the monolith, it is one more module on the same slow release train.

Solution · New features as services (Law of Holes)

Implement the feature as a new service. The API gateway routes the new paths to it and everything else to the monolith. The service gets the data it needs from the monolith through integration glue.

Delayed Delivery Service keeps replicas of orders and restaurants (with opening hours), built from the monolith's events. A timer finds orders that will miss their promised time and notifies the customer and the CRM system. Contact details are needed rarely, so it fetches them by REST.

New feature: Delayed Delivery Service Monolith publishes events Replicas orders, restaurants Timer check find late orders Notify customer + CRM Contact info is fetched by REST when needed. Order and restaurant data are replicated from events.
Cost

The new service is only as independent as its link to the monolith, which was never built to share its data.

Glue new services to the monolith

Every new service needs that link. The code that provides it is called integration glue.

Problem

The quickest way for Delayed Delivery Service to learn a restaurant's hours is a REST call to the monolith per order. At the Friday dinner peak the monolith slows down, and Delayed Delivery stops too. Scaling it up only adds load to the monolith.

Glue has two jobs. Queries read the other side's data; commands and updates change it or react to its changes.

Integration glue between service and monolith Queries Query API (REST) simple, but synchronous Replica (CQRS view) fast, more complex Commands and updates Messages or events transactional messaging Saga for multi-step updates
Solution · Replica fed by events

Treat the remote call as a temporary bridge. For data the service reads often, keep a local view, built from events the monolith publishes (the CQRS view from chapter 11). The service then keeps working when the monolith is slow.

A new service that needs monolith data A remote call couples the service to the monolith. A local view built from restaurant events does not. Remote call (temporary) OrderCreated event Delayed Delivery needs restaurant hours Monolith API cascading failure risk Local view (sustainable) Restaurant events from the monolith Delayed Delivery local restaurant view Own database or Kafka KTable

For that, the monolith must join the event flow. Subscribing is usually easy: add an event handler, or a small helper app if the monolith has no broker client. Publishing is harder, because the code that changes an order may be scattered across the monolith. If adding publish calls is too risky, tail the monolith's database instead (log tailing from chapter 6): no code change, but you get table-level changes rather than business events.

The monolith's data model is also old and odd: columns with cryptic names, one Order class that means five things. If the new service reads it directly, those quirks leak into its fresh domain model.

Solution · Anti-corruption layer

Put a translation layer between the new service and the monolith. It calls the legacy API, receives the legacy data model, and hands the service clean domain objects.

Anti-corruption layer Monolith Anti-corruption New service call legacy API legacy data model translated objects clean domain model It translates between the two models, so the monolith's quirks never leak into the new service.

The other direction works the same way. The monolith often joins moved data with other domains in one SQL query, and joining over HTTP means merging large result sets in memory. Instead, feed the monolith's tables from the service's events as a read-only copy; the service stays the source of truth.

Sometimes both sides must accept writes for a while, for example when stored procedures that cannot be switched off still change the data. Then each side publishes its changes and consumes the other's, and an origin header stops the loop.

Two-way synchronization without loops Each system publishes its changes; each consumer ignores events whose origin is itself. Monolith edits a record Monolith queue origin = monolith New service applies change New service edits a record Service queue origin = service Monolith applies change The monolith ignores the service-origin event it re-published. Collisions: the later version or timestamp wins.
Last resort: two-way sync is very hard to run for long. Incidents are harder to trace, and new features are limited by the monolith's design. Keep it at the bottom of the toolbox, and retire the monolith's queue as soon as no messages flow through it.
Cost

Glue is real work, much of it thrown away when the monolith goes, and replicas are eventually consistent. And so far we only added things next to the monolith; the code that changes most is still inside it.

Extract existing capabilities one slice at a time

New features stop the monolith from growing. To shrink it, existing capabilities must move out.

Problem

Delivery scheduling changes every sprint and its courier planning eats CPU at the dinner peak, so the Delivery team wants it out. But the code calls Order objects directly, writes delivery columns in the ORDERS table, and Order is the god class from chapter 2.

First decide what to extract. Weigh the benefit (a busy part of the roadmap, a module with performance or reliability trouble, or one that unblocks other extractions), how hard it is to untangle, and how stale its data may be: a module that tolerates delay can run on replicas from day one.

Choosing the first module to move Sales reporting has one dependency and tolerates delay, so it is a better first move than order management. Order management depends on 4 modules Delivery 1 dependency, strict Sales reporting 1 dependency, lenient Move first: easy, valuable, tolerant of a short stale window. Weigh difficulty, benefit and how weak a consistency level the module can accept.

FTGO moves sales reporting first, to learn on something forgiving (the next section shows how), and Delivery second, because that is where the goal is.

Do not split too early in a domain you do not know. The Snap CI team guessed wrong boundaries and paid for constant cross-service changes. An existing monolith helps: you can study it before you cut. And the real costs of microservices only show in production.
Solution · Extract a vertical slice

Cut one business capability out of every layer at once: its API endpoints, its domain logic, its data access and the tables it owns. Replace in-memory references across the cut with ids and messages.

Extracting a vertical slice Inbound adapters the API endpoints Domain logic the business rules Outbound adapters database access Database tables the data it owns Cut all four layers of one capability out of the monolith together.

Splitting the domain model is where it gets hard. Each challenge has a standard fix:

Splitting the domain model and database Challenge Fix Object references across the cut refer by id: Order.restaurantId God classes like Order split: Order + Delivery Shared tables split the database Wide changes in monolith replicate data, keep old columns

For Delivery, the team first defines a DeliveryService interface inside the monolith and refactors every caller to use it. A feature toggle then picks the old in-process code or a proxy that talks to the new service by messages.

Extracting Delivery Service from the monolith Interface DeliveryService Refactor callers use the interface Feature toggle old code or proxy Delivery svc via messages Once the new path works, delete the old code. Next candidates: Order History, Order, Consumer, Kitchen.

The messages are notifications. The monolith sends ScheduleDelivery and CourierLocationUpdated; Delivery Service computes courier plans and publishes CourierPlanUpdated, which the monolith copies into a local replica so its old screens keep working.

Two more choices come with every extraction. First, code or data first? Most teams move the code first, because it pays off sooner; chapter 24 weighs the choice. Either way, sketch how both will move before you start: a half-finished split that leaves a shared database stores up trouble. Second, the user interface easily lags behind, because you need the services before you can see how to split the screens. Do not let it lag too far.

Splitting the user interface Page-based decomposition routes pages to services. Widget-based decomposition assembles widgets into a container page. Page-based Widget-based Router and common navigation /orders/ pages /delivery/ pages Container page Order status Courier map Simple web. A team can ship pages end to end. Needs an assembly layer. Widgets can talk by events. Widgets suit a mixed page. Pages suit a website.

For a website, page-based decomposition is a simple default: no special browser code, and a link is the hand-off between teams. Widget-based decomposition is the micro-frontend style from chapter 13, where a team owns a widget and the service behind it.

Cost

Every extraction ends in a cut-over: the moment real orders start flowing to new code. That moment is where a migration can hurt customers.

Switch traffic safely, and keep a way back

The new Delivery Service passes its tests. Now it must take over from code that has run FTGO's deliveries for years.

Problem

The team flips all delivery traffic to the new service on a Monday evening. A bug in courier assignment leaves orders without couriers for 40 minutes, in every city at once, and rolling back needs a new deploy of the monolith.

Solution · Proxy with toggle, canary and parallel run

Put a proxy (often the API gateway) in front of the monolith and decide per request whether old or new code answers. The monolith needs no change. Switch gradually and keep the old path ready.

Safe ways to switch traffic A proxy with a toggle, a canary release and a parallel run. Toggle in proxy switch back any time Proxy + toggle Monolith New svc Canary release ramp up on good metrics Proxy few users to new Monolith New svc Parallel run one answer is trusted Proxy calls both Monolith New svc Compare results Never repeat side effects: do not send two order emails or charge a card twice.

A side example shows the same ideas with events: FTGO's first extraction, sales reporting, moved in four small steps.

Four steps to move the reporting module Build the new service beside the monolith, connect it by a queue, backfill old data, then redirect and remove the module. 1 Build beside monolith untouched 2 Add a queue monolith publishes 3 Backfill republish old data 4 Redirect remove old module Step 3 doubles as validation: the reports must match the ones in the monolith. Keep both implementations in step until the old one is removed.

A durable broker makes mistakes cheap: after a bug, reset the offset and regenerate; for new fields, read from the beginning. Once Order Service is extracted, Reporting Service reads its events unchanged.

The queue can also become the trigger for the work, not just a side effect. Monolith and new service read the same messages and each handles a subset chosen by content: one country, then more, then the old module goes. If the monolith cannot read a queue, convert requests to messages outside it.

Events as the source for both systems A queue triggers both the monolith and the new service; each processes a subset, such as one country at a time. Upstream Message queue single source of truth Monolith all other countries New service country = CA Roll out by message content: move one country, then more, then remove the monolith module.

For synchronous requests the proxy does the same job, routing by content such as GET reports?country=CA. Before shifting traffic, a comparison job checks that both databases agree, and the rollback stays simple: route back, rewind the queue and reprocess.

Cost

Two implementations must be kept in step, and a parallel run must never repeat side effects. And once part of a business operation runs in a new service, one database transaction can no longer cover it.

Keep transactions and logins working across the cut

Inside the monolith, placing an order was one ACID transaction. After extraction it is not.

Problem

The team plans to extract Kitchen Service before Order Service. Then creating an order starts in the monolith and continues in Kitchen Service. If Kitchen rejects the ticket, the monolith must undo the order it already created, so someone has to add pending states and compensation logic to old code that nobody wants to touch.

Solution · Make the monolith the saga's pivot

Order extractions so that the monolith's part of a saga (chapter 9) never needs undoing. Extract the service that starts the flow first: it owns the compensations, and the monolith's local transaction becomes the pivot, the step after which the saga always completes.

For FTGO that means Order Service first. Its saga then creates the order in an APPROVAL_PENDING state and asks the monolith to verify the consumer, create the ticket and authorize the card in one local transaction. Consumer, Kitchen and Accounting can be extracted later, one at a time, and each takes its step out of the monolith.

Extraction order that keeps the monolith simple 1. Order svc owns compensation 2. Consumer svc verify consumer 3. Kitchen svc pending ticket 4. Accounting authorize card If Kitchen went first, the monolith would need APPROVAL_PENDING states and undo logic.
Saga with the monolith as the pivot Order svc Monolith Order APPROVAL_PENDING verify consumer, ticket, card pivot: never undone success Order APPROVED All compensation lives in the new, testable service.

Login breaks in a similar way.

Problem

Customers log in through the monolith, which keeps their session in its own memory behind a JSESSIONID cookie. The new Order History Service receives GET /orders and has no idea who the user is.

Solution · Login sets a token cookie

Make one small change to the monolith: its login handler also sets a USERINFO cookie that holds a JWT (the access token from chapter 16). The API gateway turns the cookie into an Authorization header, and each service validates the token and reads the user from it.

Sharing login between monolith and services Browser API gateway Monolith Order History POST /login route login JSESSIONID + USERINFO GET /orders + cookie Authorization: JWT validate, read user One small change: the monolith's login handler also sets a USERINFO cookie holding a JWT.
Cost

Sagas bring compensations and no isolation between steps, with all the countermeasures from chapter 9. And underneath it all, the extracted code still reads and writes the monolith's tangled schema: Delivery Service owns its logic, but not yet its data.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Goal-driven migrationA move with no measurable aim that may not fix the real painDiscipline to measure, and to stop if nothing improves
Strangler applicationA big-bang rewrite that delivers nothing until the endTwo systems run side by side for years, joined by glue
New features as servicesEvery new feature makes the monolith biggerThe new service needs the monolith's data
Event-fed replicaA service fails whenever the monolith it queries is slowThe monolith must publish or be tailed; stale reads
Anti-corruption layerThe legacy data model leaks into the new serviceA translation layer to maintain
Two-way sync, origin headerBoth sides must accept writes for a whileHard to run and debug; last resort
Vertical slice extractionExisting capabilities stay locked in the monolithSplitting god classes, references and tables
Page- or widget-based UI splitThe UI stays one block owned by everyoneRouting, or an assembly layer
Proxy, toggle and canaryA cut-over that hits everyone with no quick way backTwo implementations to keep in step
Parallel runNo proof the new code gives the same answersDouble load; side effects must not repeat
Monolith as saga pivotExtraction forces undo logic into old codeConstrains extraction order; no isolation
Token cookie at loginNew services cannot tell who the user isA small monolith change; token checks everywhere

Recap

Quick check

Why extract Order Service before Kitchen Service?
Show answer

Then the monolith's step is the saga's pivot and never needs undoing, so all the compensation logic lives in the new, testable Order Service instead of being added to the monolith.

Your first idea for the migration is to move order management, which touches four other modules. Why might sales reporting be a better first move?
Show answer

It has fewer dependencies, still delivers value, and tolerates stale data, so the team meets distributed-system problems at a small scale and gets feedback early.

FTGO's new Delayed Delivery Service calls the monolith's REST API for restaurant hours on every order. At the Friday dinner peak the monolith slows down. What breaks, and which pattern fixes it?
Show answer

Delayed Delivery Service fails with the monolith, and scaling it up only adds load. Replace the call with a local replica of restaurant data, fed by the monolith's events or by tailing its database.

Still open

FTGO's code is moving out of the monolith, but its data is not. Delivery Service and Order Service still lean on one tangled schema full of shared tables, foreign keys and joins.

Next: 24 Decomposing the database →