Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Real-World Projects

Project: Strangling a Monolith

Extract an orders service from a monolith with a routing facade, backfill and change replay, shadow comparison, a staged cutover and a rollback plan you can run.

Almost nobody builds microservices on an empty field. Most teams have a monolith that works, earns money and hurts to change, and the real task is to move one capability out of it without a single minute of downtime. This project walks through that move step by step, using the strangler fig pattern you already know and the data rules from Database per Service and Data Ownership.

The scenario: a shop monolith owns an orders table. We will extract an orders service with its own store. Along the way you will build a routing facade, copy the existing data, keep both copies in step, compare them in shadow mode, cut over reads and then writes, and prove that you can go back at any point.

There is no real monolith, database or network on this site. Everything here is a single-process Node model: the monolith and the new service are objects holding Maps, and the "change feed" is an array. The sequence of steps and the ways they go wrong are real; the sockets, replication lag and database engines are not.

Five steps, each reversible

Facade first Route everything through one door.
Copy and sync Backfill, then replay changes.
Shadow Compare old and new answers.
Cut over Reads first, then writes.

Retire the old code only when the new path has run quietly for a while.

1 / 2

The plan

flowchart LR
    S1["1. Facade in front"] --> S2["2. Backfill + change replay"]
    S2 --> S3["3. Shadow compare"]
    S3 --> S4["4. Reads to new"]
    S4 --> S5["5. Writes to new + reverse sync"]
    S5 --> S6["6. Retire old code"]

Every arrow is a configuration change with a way back, except the last one.

  1. Facade in front. Clients keep calling the same URLs. A thin layer (NGINX, a gateway, or a small proxy) forwards everything to the monolith. Nothing changes yet, but now you hold the steering wheel.
  2. Backfill and change replay. The new service gets its own database. You copy the existing rows, then keep the copy current from the monolith's change feed.
  3. Shadow compare. The monolith still answers clients, but you also ask the new service and log any difference.
  4. Reads to new. When mismatches are near zero, route reads to the new service. Writes still go to the monolith and flow across.
  5. Writes to new, with reverse sync. The new service becomes the system of record. You copy its changes back into the old tables so a rollback does not lose new orders.
  6. Retire. After a quiet period, stop the sync, delete the old table and code.

Step 2: backfill without losing writes

The classic trap is copying a table while writes keep arriving. If you copy first and note the position afterwards, you can miss changes. The safe order is:

  1. Note the position of the change feed (here, a sequence number).
  2. Copy a snapshot of the data.
  3. Replay every change after the noted position. Replays are upserts, so applying a change twice is harmless (The Transactional Outbox and Idempotent Consumers explains why idempotency matters).
Node.js Backfill, replay and compare

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first comparison finds two differences, the order that changed during the copy and the order created during it. After replay both copies agree, and running the replay again does nothing, because it only applies changes beyond appliedSeq. In production the feed never stops, so you keep replaying continuously, and you watch lag, the gap between the newest change and the last applied one.

Real change feeds can deliver an event twice or slightly out of order. Upserts keyed by id with a version or timestamp check make replay safe; the stand-in only needs the sequence number because it delivers in order.

Steps 3 to 5: the facade does the cutover

Now the facade gets two switches, one for where reads go and one for where writes go. Keeping them separate is the point: reads are easy to switch and easy to undo, writes are the risky part. When writes move, a reverse sync copies new orders back into the monolith's table so legacy reports and a possible rollback still see everything.

The model below uses a pending queue per direction to mimic replication lag: a change is not visible on the other side until drain() runs. That makes the main hazard visible, read-your-writes: right after a write, a read from the other store can be stale.

Node.js Staged cutover and rollback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Three things to notice in the output. Order 2 reads as null right after the write, then appears after drain(): that is replication lag, and real systems handle it by reading from the primary for the user who just wrote, or by returning the written order in the write response. Order 3 survives the rollback because the reverse sync copied it into the monolith's store. And order 4, written after rollback, still reaches the new service, so the move forward again does not need another backfill.

Making the cutover safe in practice

A model cannot show every operational detail, so here is the checklist teams actually use.

  • Route by user, not by request. Send a stable group of users (by hash of the user id) to the new path first, so a person does not bounce between two behaviours. Start with employees, then 1 percent, 10 percent, everyone.
  • Define the numbers before you start. For example: mismatch rate under 0.01 percent for a week, p99 latency within 10 percent of the monolith, error rate no higher. Write them down so the decision is not a mood.
  • Shadow reads cost money. Compare a sample, not all traffic, and never let the shadow call slow the real answer; run it after you have replied or with a tight timeout.
  • Watch the invisible readers. Reports, exports, cron jobs and other teams' scripts often read the old table directly. Keep the reverse sync until you have found and moved every one.
  • Plan the data rollback. Rollback is only real if data written on the new side can flow back. If it cannot, say so, and treat the write cutover as a one-way door that needs extra caution.
  • Remove the old code last. Keep the old path, switched off but deployable, for a few weeks. Deleting it too early turns every later surprise into an emergency.
Terminal
# Read-only example: a gradual route in NGINX, 10% of users to the new service
split_clients "${cookie_uid}" $orders_backend {
    10%     orders_service;
    *       legacy_monolith;
}
location /orders/ {
    proxy_pass http://$orders_backend;
}

The split_clients block hashes the cookie value, so each user lands on the same backend every time. Real systems also add health checks, timeouts and logging of which backend answered; none of that is shown here.

Pitfalls to expect

  • A shared table that never goes away. If the monolith and the new service both write the same rows, you have not extracted anything. One side owns writes at any moment (data ownership).
  • Dual writes from application code. Writing to both stores in one request can half-fail. Prefer a change feed or an outbox.
  • Skipping the anti-corruption layer. If the new service copies the monolith's odd column names, you have moved the mess, not cleaned it. Translate at the edge (decomposition strategies).
  • Cutting over on a deadline. The schedule is a hope, the mismatch graph is a fact.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do you note the change-feed position before copying the snapshot?

    Writes keep arriving during the copy. Replaying all changes after the noted position closes the gap, and upserts make overlap harmless.
  2. 2. What is the purpose of shadow comparison?

    The monolith still answers clients while you log differences, so mistakes cost nothing yet.
  3. 3. Why separate the read switch from the write switch?

    Moving reads first lets you test the new data safely. Moving writes is the risky step, so it comes later, with reverse sync.
  4. 4. What does the reverse sync protect after writes move to the new service?

    It copies new orders back into the monolith's table, so switching back still shows them, and legacy readers keep working.
  5. 5. Order 2 read as null right after it was written. What caused that?

    Reads went to the new store while the write went to the monolith. Until the sync ran, the new store did not have the row.

Summary

  • Strangling a monolith is a sequence of small, reversible steps behind a routing facade: copy, sync, compare, move reads, move writes, retire.
  • Backfill safely: note the feed position, copy, then replay later changes with idempotent upserts.
  • Shadow comparison turns "I think it is the same" into a measured mismatch rate.
  • Move reads before writes; after the write cutover keep a reverse sync so rollback and legacy readers still work.
  • Watch lag, hidden readers and read-your-writes, and delete the old code only after a quiet period.

Next: Common Microservices Mistakes and Anti-Patterns.