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
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.
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
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 claim | Why 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. |
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.
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 is | Watch |
|---|---|
| Team autonomy | Dependencies between teams, feature branch lifetime, merge requests |
| Continuous delivery | Deployments per period, cycle time, lead time |
| Scalability | Incidents during load peaks, response time, machine size needed |
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Splitting the domain model is where it gets hard. Each challenge has a standard fix:
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.
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.
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.
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.
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.
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.
- Feature toggle: a switch, often in the proxy, between old and new. A plain configuration file is a fine start. Flip it back without a deploy.
- Canary release: send a small group, say one city, to the new code first. Tools can ramp up the share while error rates stay low.
- Parallel run: send the request to both and compare. Trust one, normally the old one; use the other only to check.
- Deploy is not release: install the new version first, release it to users later. Blue-green deployment (chapter 19) is the simplest example.
A side example shows the same ideas with events: FTGO's first extraction, sales reporting, moved in four small steps.
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.
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.
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.
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.
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.
Login breaks in a similar way.
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.
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.
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
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Goal-driven migration | A move with no measurable aim that may not fix the real pain | Discipline to measure, and to stop if nothing improves |
| Strangler application | A big-bang rewrite that delivers nothing until the end | Two systems run side by side for years, joined by glue |
| New features as services | Every new feature makes the monolith bigger | The new service needs the monolith's data |
| Event-fed replica | A service fails whenever the monolith it queries is slow | The monolith must publish or be tailed; stale reads |
| Anti-corruption layer | The legacy data model leaks into the new service | A translation layer to maintain |
| Two-way sync, origin header | Both sides must accept writes for a while | Hard to run and debug; last resort |
| Vertical slice extraction | Existing capabilities stay locked in the monolith | Splitting god classes, references and tables |
| Page- or widget-based UI split | The UI stays one block owned by everyone | Routing, or an assembly layer |
| Proxy, toggle and canary | A cut-over that hits everyone with no quick way back | Two implementations to keep in step |
| Parallel run | No proof the new code gives the same answers | Double load; side effects must not repeat |
| Monolith as saga pivot | Extraction forces undo logic into old code | Constrains extraction order; no isolation |
| Token cookie at login | New services cannot tell who the user is | A small monolith change; token checks everywhere |
Recap
- Migrate only for a named, measurable goal, try easier fixes first, and check in production whether each step moved you closer.
- Never rewrite with a big bang; grow a strangler application around the monolith so that every step delivers value.
- Build new features as services, joined to the monolith by glue: event-fed replicas, an anti-corruption layer, and two-way sync only as a last resort.
- Pick extractions by benefit, ease and tolerance for stale data, cut out whole vertical slices, and do not leave the user interface behind.
- Switch traffic through a proxy with toggles, canaries and parallel runs, so a bad cut-over can be undone in seconds.
- Order extractions so the monolith is the saga's pivot and never compensates, and let the monolith's login issue a token cookie that new services can trust.
Quick check
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.
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.
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.
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.