Software Architecture

The Strangler Fig Pattern in Practice: Routing, Cutover and Data

Rewriting a large monolith from scratch is risky: the old system keeps changing while the new one is built, and nothing reaches users until the switch-over at the end. The Strangler Fig pattern avoids that by replacing the monolith one feature at a time, with a routing layer deciding which system serves each request. At every step the system keeps working, and each step can be undone.

This guide walks through the mechanics with Nginx as the routing layer: picking a first feature, routing it to a new service, shifting traffic gradually instead of all at once, and the part that decides whether the migration succeeds, which is what happens to the data.

Understanding the Strangler Fig Pattern

Martin Fowler named the pattern in 2004 after strangler figs, which grow around a host tree and eventually replace it. In software architecture, the 'host tree' is your existing monolithic application, and the 'strangler' is a new, modern microservice that gradually takes over specific functionalities.

The core idea is simple: instead of rewriting everything at once, you introduce a facade (typically an API Gateway or a reverse proxy) in front of your monolith. This facade initially directs all traffic to the monolith. As you build new microservices to replace specific features, you configure the facade to route requests for those features to the new services, effectively 'strangling' the corresponding functionality out of the monolith. The old code in the monolith becomes unused and can eventually be safely removed.

This approach offers significant benefits:

  • Value arrives early: each extracted feature ships on its own, rather than everything at the end.
  • Risk is limited to one feature at a time, and routing changes can be reversed.
  • You can stop at any point. Many teams extract the parts that need independent scaling or deployment and leave the rest as a smaller, well-understood monolith. That's a perfectly good outcome.

Implementing the Strangler Fig Pattern: A Step-by-Step Guide

Let's walk through how you can implement this pattern, using a reverse proxy (like Nginx) to demonstrate the core mechanism.

Step 1: Identify a Candidate Feature for Extraction

The first, and arguably most critical, step is choosing the right feature to extract. Look for a module within your monolith that:

  • Has a relatively clear, well-defined boundary (a "bounded context").
  • Has minimal, well-understood dependencies on other parts of the monolith.
  • Provides business value, making its independent development worthwhile.
  • Ideally, is not excessively complex or a mission-critical, high-risk component for your first attempt.

For instance, an Order Status lookup, a User Profile Management module, or a Product Catalog Search are often good candidates. Let's imagine we're extracting a User Profile service from an existing monolithic application that handles various user operations.

Step 2: Set Up an API Gateway or Reverse Proxy

Your proxy will be the nerve center of your strangler architecture. All incoming requests will first hit this proxy, which will then decide whether to forward them to the monolith or a new microservice. For simplicity, we'll use Nginx.

Initially, Nginx will act solely as a pass-through proxy to your existing monolith.

Nginx
# /etc/nginx/sites-available/monolith_proxy.conf

server {
    listen 80;
    server_name your-application.com;

    location / {
        proxy_pass http://monolith-backend:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Replace monolith-backend:8080 with the actual address and port of your monolithic application. After configuring Nginx, restart it and ensure all traffic still flows to your monolith as expected.

Step 3: Develop the New Microservice

Now, build your new microservice, focusing only on the functionality you identified in Step 1. This service should be independently deployable, have its own data store (or share the monolith's database carefully, if necessary, for the transition period), and expose a clear API.

Let's assume we're creating a simple User Profile Service that handles requests to /api/users/{id}/profile. Here's a minimal Python Flask example:

Python
# profile_service.py
from flask import Flask, jsonify, request

app = Flask(__name__)

# In a real application, this would interact with a database
user_profiles = {
    '123': {'name': 'Alice Smith', 'email': 'alice@example.com', 'bio': 'Software Engineer'},
    '456': {'name': 'Bob Johnson', 'email': 'bob@example.com', 'bio': 'DevOps Specialist'},
}

@app.route('/api/users/<user_id>/profile', methods=['GET'])
def get_user_profile(user_id):
    profile = user_profiles.get(user_id)
    if profile:
        return jsonify(profile)
    return jsonify({'message': 'Profile not found'}), 404

@app.route('/api/users/<user_id>/profile', methods=['PUT'])
def update_user_profile(user_id):
    if user_id not in user_profiles:
        return jsonify({'message': 'Profile not found'}), 404
    data = request.json
    user_profiles[user_id].update(data)
    return jsonify(user_profiles[user_id])

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001)

This service would run on a separate port, say 5001, and handle requests for user profiles.

Step 4: Divert Traffic to the New Service

Update your Nginx configuration to route requests specifically for User Profile operations to your new microservice. All other requests will continue to go to the monolith.

Nginx
# /etc/nginx/sites-available/monolith_proxy.conf (updated)

server {
    listen 80;
    server_name your-application.com;

    # Route specific /api/users/{id}/profile requests to the new microservice
    location ~ ^/api/users/[0-9]+/profile {
        proxy_pass http://profile-service:5001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # All other requests still go to the monolith
    location / {
        proxy_pass http://monolith-backend:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Now your-application.com/api/users/123/profile goes to profile-service:5001, and everything else, like /api/products or /dashboard, still goes to the monolith. Check that the regular expression matches exactly the URLs you intend. Here, user IDs must be numeric, and /api/users/123/profile/photo would also match because the pattern has no $ anchor.

Step 5: Shift Traffic Gradually

Switching 100% of a feature's traffic at once turns any bug in the new service into a full outage of that feature. Nginx's split_clients can send a percentage of users to the new service, based on a stable hash so each user consistently lands on the same side:

Nginx
# in the http {} block
split_clients "${cookie_session_id}${remote_addr}" $profile_backend {
    10%     profile-service:5001;
    *       monolith-backend:8080;
}

# in the server {} block
location ~ ^/api/users/[0-9]+/profile$ {
    proxy_pass http://$profile_backend;
    # ... same proxy_set_header lines as before
}

Using a variable in proxy_pass makes Nginx resolve the hostname at request time, which requires a resolver directive (for example, your cluster's or VPC's DNS server).

Compare error rates and latency between the two backends, then raise the percentage in steps. For read-only endpoints, you can go further before any user traffic moves: mirror requests to the new service with Nginx's mirror directive and compare its responses with the monolith's offline.

Step 6: Remove the Old Code

Once the new service handles all traffic for the feature and has been stable for a while, delete the corresponding code from the monolith. Skipping this step is common, and it leaves two implementations that drift apart and confuse everyone who works on the code later. Before deleting, check the monolith's logs to confirm the old endpoints get no traffic. Internal callers such as batch jobs and admin screens often call the old code directly, without going through the proxy.

Repeat this entire process for other features, gradually 'strangling' them out of the monolith. Over time, your monolith will shrink, becoming a 'mini-monolith' with only leftover, unmigrated functionality, or eventually disappearing altogether.

Key Architectural Considerations

Extracting services isn't just about routing. There are deeper architectural considerations:

Data Migration and Synchronization

This is usually the hardest part. Routing moves requests, but the data stays in the monolith's database, where other parts of the monolith probably still read and join against it. Common stages:

  1. Shared database first: the new service reads and writes the monolith's tables. It's the fastest way to move the code, but the service is still coupled to the monolith's schema.
  2. Service owns the data, monolith reads a copy: the service writes to its own store, and changes flow back to the monolith (through events, or change data capture with a tool like Debezium) for the parts that still need them.
  3. Monolith stops using the data: the remaining readers move to the service's API, and the old tables are dropped.

Avoid having application code write to both databases in the same request ("dual writes"). If one write succeeds and the other fails, the two stores silently diverge. Prefer one system of record per piece of data at any moment, with changes propagated from it.

Shared Libraries and Dependencies

As you extract services, you'll find common utility code, authentication logic, or domain models. Duplicating small amounts of code is often cheaper than coupling services through a shared domain library that forces them to deploy together. Authentication is the exception: centralize it at the gateway or in an identity provider early, so every new service validates the same tokens the same way.

Observability

With two (or more) systems running concurrently, robust logging, monitoring, and tracing become even more vital. Implement distributed tracing (e.g., OpenTelemetry) to understand request flows across your monolith and new services. Centralized logging (e.g., ELK stack) helps correlate events.

Rollback Strategy

Reverting the proxy configuration sends traffic back to the monolith, and that's a real advantage of this pattern, but only while both systems share the same data. Once the new service writes to its own store, rolling back routing means the monolith doesn't see any writes made in the meantime. Plan for that before the data moves: either propagate the service's changes back to the monolith until the cutover is final, or accept that rollback after that point means a data repair job.

⚠️ Common mistake: Extracting a service whose data is joined against everywhere in the monolith (such as users or products) as the first step. Every remaining query that joins those tables becomes a cross-service call. Start with a feature whose data is mostly self-contained.

Summary

  1. Pick a first feature with clear boundaries and self-contained data, and treat it as a learning exercise for the team.
  2. Put the routing layer in place first and manage its configuration like code. It controls every cutover and rollback.
  3. Move traffic gradually with percentage splits or mirroring, and compare both backends before going to 100%.
  4. Plan the data stages up front, keep one system of record at a time, and know what rollback means once data has moved.
  5. Delete the old code once it gets no traffic.
Advertisement