What is the strangler fig pattern with a reverse proxy, and why use it?

The strangler fig pattern is an incremental migration strategy. Instead of replacing a monolith all at once, you put a reverse proxy in front of it and move individual URL paths to a new service one at a time. Every request still enters through the same front door. The proxy decides, path by path, which backend answers it. Over time the new service takes over more routes until the monolith handles nothing and can be switched off.

                 +-------------------+
  client ------> |   reverse proxy   |
                 +-------------------+
                   |               |
         /orders/* |               | everything else
                   v               v
          +-------------+   +-------------+
          | new service |   |  monolith   |
          +-------------+   +-------------+
                   \             /
                    v           v
                +-------------------+
                |   shared state    |  <- coupling point
                | (DB, sessions)    |
                +-------------------+

Treat the proxy as the migration's control plane. Its routing rules decide what is migrated, so manage them like application code. Keep them in version control, review them, test them in CI, and deploy them through a pipeline. Moving a route forward or back is then a small, auditable diff.

Teams choose this over a flag-day legacy rewrite for three reasons:

  • Smaller blast radius. A bad cutover affects one path, not the whole product.
  • Continuous delivery of value. Each migrated route ships on its own, so the rewrite never sits unreleased for months.
  • Fast rollback. Pointing a route back at the monolith is a one-line config change.

The diagram also shows the main risk. Shared state, such as a common database or session store, still couples the two systems after their traffic is separated.

The pattern suits backend and platform teams whose monolith has domain boundaries that roughly match URL boundaries. If /billing really does mean billing code, path-based routing gives you clean seams to cut along.

                      +------------------+
                      |      client      |
                      +------------------+
                               |
                               | all requests (same front door)
                               v
  +-----------------------------------------------------------+
  |               reverse proxy (control plane)               |
  |                                                           |
  |   routing rules: versioned, reviewed, tested, reversible  |
  |     /orders/*   -> new service                            |
  |     /*          -> monolith (default)                     |
  +-----------------------------------------------------------+
           |                                    |
           | /orders/*                          | everything else
           v                                    v
  +------------------+                 +------------------+
  |   new service    |                 |     monolith     |
  | (grows per path) |                 | (shrinks per path)|
  +------------------+                 +------------------+
           |                                    |
           +----------------+-------------------+
                            |
                            v
               +--------------------------+
               |       shared state       |  <- coupling point
               |  (database, sessions)    |
               +--------------------------+

The reverse proxy routes each path to either the new service or the monolith using versioned rules, while shared state such as the database and sessions remains the point where the two stay coupled.

When should you avoid the strangler fig pattern?

The converse also holds: when URLs don't map to domains, the proxy has nothing clean to route on. Skip the pattern in these cases:

  • Features that span many endpoints. If checkout touches /cart, /orders, /payments and /inventory, moving one path at a time splits a single business transaction across two systems.
  • Endpoints whose behaviour depends on parameters. A path like /api?action=refund hides many operations behind one route. Splitting them requires query-string rules that are brittle and hard to test.
  • A heavily shared database with no clear owners. If many modules write the same tables, the new service cannot own its data. You have moved code but not responsibility.
  • Small, well-understood modules. A planned rewrite often costs less than building proxy routing and running two versions in parallel.

Running in parallel has real costs. You maintain two deploy pipelines and two on-call surfaces. Logic such as validation or pricing rules ends up duplicated. A fix lands in one copy and not the other, so users get different answers depending on which route served them.

The larger risk is a permanent hybrid. Teams migrate the easy routes first. The hard routes stay put, and priorities shift. You end up paying for both systems indefinitely.

Alternative Fits when Cost Risk
Refactor to a modular monolith Boundaries are unclear, one deployable is acceptable Moderate, spread over time Low; boundaries can erode without enforcement
Branch by abstraction Change sits behind an internal interface Low to moderate Low; toggles must be removed
Planned rewrite of one module Small, well-specified scope Bounded up front Medium; missed edge cases
Event interception / change data capture Data sync matters more than request routing High tooling and operations cost Medium; ordering and consistency bugs

How do you put a reverse proxy in front of the monolith first?

Before routing anything to a new service, deploy the proxy as a pure pass-through: every request goes to the monolith, unchanged. This step exists so that any regression it causes can only be the proxy's fault. If you change topology and routing at the same time, a spike in 502s or a broken redirect becomes ambiguous. You can't tell whether the proxy or the new service caused it.

Run the pass-through long enough to cover normal traffic peaks, then compare it with the direct path:

  • Latency and error rates: p50/p99 and 5xx rates should match what the monolith reported before.
  • Headers: the monolith must still see the original Host, the real client IP via X-Forwarded-For, and the original scheme via X-Forwarded-Proto. Without these, absolute URLs, redirects and "secure" cookie logic often break.
  • TLS: if the proxy now terminates TLS, check certificate chains, protocol versions, and any HSTS headers the monolith used to send.
  • Logging: generate a request ID at the proxy with nginx's $request_id and forward it as a header. Then one request can be traced through both proxy and application logs.

The nginx config for this stage forwards those three headers and adds the request ID. Its access log format records $upstream_addr, $upstream_status and $upstream_response_time alongside total request time. Those fields will later show which backend served each request and whether slowness came from the hop or the service.

The trade-off is a new single point of failure and an extra network hop on every request. Run at least two proxy instances behind a load balancer or a shared virtual IP, and give them health checks. Size them for peak connection counts, not average request rates.

# /etc/nginx/conf.d/monolith-passthrough.conf (included inside the http {} block)
# Stage 0: pure pass-through. No routing rules yet; every request goes to the monolith.

# Record which upstream served the request and how long it took, so later you can
# separate proxy-hop latency ($request_time) from backend latency ($upstream_response_time).
log_format upstream_timing '$remote_addr [$time_local] "$request" '
                           'status=$status req_id=$request_id '
                           'upstream=$upstream_addr upstream_status=$upstream_status '
                           'request_time=$request_time upstream_time=$upstream_response_time';

upstream monolith {
    server 10.0.1.10:8080;      # placeholder address of the existing monolith
    keepalive 32;               # reuse connections so the extra hop adds less overhead
}

server {
    listen 443 ssl;
    server_name app.example.com;

    # The proxy now terminates TLS: compare chain and protocols with the old direct path.
    ssl_certificate     /etc/nginx/tls/app.example.com.crt;
    ssl_certificate_key /etc/nginx/tls/app.example.com.key;

    access_log /var/log/nginx/monolith_access.log upstream_timing;

    location / {
        proxy_pass
        proxy_http_version 1.1;           # required for upstream keepalive
        proxy_set_header Connection "";

        # Preserve what the monolith saw before the proxy existed.
        proxy_set_header Host              $host;
        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # One ID per request, visible in proxy logs, app logs and the client response.
        proxy_set_header X-Request-ID $request_id;
        add_header       X-Request-ID $request_id always;
    }
}

A minimal nginx pass-through that forwards Host, X-Forwarded-For and X-Forwarded-Proto, propagates a per-request ID, and logs upstream address, status and response time alongside total request time.

How does nginx routing work for path-based cutover?

nginx picks one location block per request, and the order it evaluates them is not the order they appear in the file. When the monolith and the new service share a URL space, that difference decides which backend gets the request.

Modifier Match type Precedence
= Exact URI Checked first; a match stops the search
^~ Prefix If it is the longest prefix match, regexes are skipped
~ / ~* Regex (case-sensitive / insensitive) Checked in config order; first match wins
none Prefix Longest match is used only if no regex matches

Silent misrouting

Suppose you add location /orders/ pointing at the new service, while the monolith config already has location ~ \.json$. A request for /orders/42.json matches the regex, which overrides the plain prefix, so it goes to the monolith. Nothing errors, and the request reaches the wrong backend. Declare migrated routes with ^~ so that existing regexes cannot claim them. After every change, test representative URLs against the proxy.

What gets forwarded upstream

proxy_pass without a URI forwards the original path unchanged. proxy_pass with a URI replaces the matched location prefix, so /orders/42 arrives upstream as /42. A single trailing slash makes this difference. Pick one form and use it for every migrated route.

Redirects and absolute URLs

If the new service builds URLs from the Host header, set proxy_set_header Host $host so it sees the public hostname. Also pass X-Forwarded-Proto. Use proxy_redirect to fix Location headers that leak internal hostnames. proxy_redirect does not rewrite URLs inside response bodies, so the service itself has to generate correct absolute links.

upstream monolith  { server 10.0.1.10:8080; }
upstream orders_svc { server 10.0.2.20:8080; }

server {
    listen 80;
    server_name shop.example.com;

    # Inherited by every location below (none of them set their own headers).
    # Backends see the public hostname and scheme, so the URLs they build are correct.
    proxy_set_header Host              $host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;

    # Existing monolith rule. Without ^~ below, it would claim /orders/42.json.
    location ~ \.json$ {
        proxy_pass
    }

    # Migrated route. ^~ means a longest-prefix match here skips all regexes.
    location ^~ /orders/ {
        # No URI after the upstream name, so /orders/42 is forwarded as /orders/42.
        # Writing  would forward /orders/42 as /42.
        proxy_pass

        # Rewrite Location headers that expose the service's internal address.
        proxy_redirect  /;
    }

    # The exact match is checked first. It sends the bare path to the canonical prefix.
    location = /orders {
        return 301 /orders/;
    }

    # Everything that has not been migrated stays on the monolith.
    location / {
        proxy_pass
    }
}

Routes /orders/ to the new service with ^~ so the monolith's .json regex cannot claim it, forwards the path unchanged, and keeps Host and redirects consistent.

How do you choose the first route and decide who owns the data?

Pick the first route by what it touches, not by how much it hurts. Before choosing, list candidate routes and map each one to the tables, caches and queues it reads or writes. A route that looks self-contained often joins five tables or invalidates a shared cache key. The best first candidate is bounded, low-write and well understood. A read-only lookup such as GET /products/{id} is a good example. A small first route lets you prove the proxy, deployment and rollback path while little is at stake. Starting with the most painful legacy area combines routing risk with domain risk.

Next, decide who is authoritative for the data. Avoid dual writes, where both systems write the same records. Without a distributed transaction, a failure between the two writes leaves the systems silently inconsistent, and nothing tells you which copy is correct. There are two safer options:

  • Monolith stays the system of record. The new service reads through a monolith API or a read replica. This is simple, but the service inherits the legacy schema and replica lag.
  • New service owns the data. The monolith calls the service's API for those records. This is cleaner long term, but it requires a one-time migration and gives the monolith a new runtime dependency.

Record authority for every stage so nobody has to guess:

Route Stage Authoritative system Other system's access
GET /products/{id} Shadow Monolith Service reads replica
GET /products/{id} Cutover Monolith Service reads via API
/products/* writes Owned New service Monolith calls service API

How do you handle sessions, auth and cookies across both services?

Authentication is usually the first route that breaks, because the monolith's session is the one thing every request depends on. Before the new service can handle /products/*, it must recognize who the caller is. You have three options: read the monolith's session, validate a token the monolith issues, or move authentication to the proxy and forward a trusted identity header.

Cookie scope determines whether the browser sends the session cookie at all. If the monolith sets Path=/app and the new service lives under /products, the cookie never reaches the service. Moving the service to a subdomain raises the same problem with Domain. Behind a single proxy hostname, nginx's proxy_cookie_path and proxy_cookie_domain can rewrite Set-Cookie headers so both backends see one consistent scope.

A shared session store is the fastest route to compatibility. The trade-off is that the new service then depends on the monolith's serialization format and key layout. If the monolith changes either one, the service breaks. Stateless token validation removes that runtime dependency. It does require the monolith to issue tokens, and revocation becomes harder. Edge authentication keeps both backends simple. It only works if the backends accept identity headers exclusively from the proxy. Strip any client-supplied copies with proxy_set_header.

Weighted rollouts add a separate risk. If one user's requests alternate between backends, any session state that only one side writes will appear to vanish. Examples include a cart, a CSRF token, or a refreshed expiry. Either make routing sticky per user, for example by hashing on the session cookie, or confirm that every piece of mutable session state lives in the shared store.

# Both backends sit behind one public hostname: shop.example.com
upstream monolith     { server monolith.internal:8080; }
upstream products_svc { server products.internal:9000; }

# Weighted rollout that stays sticky per session: the same session cookie
# always hashes to the same bucket, so one user never alternates backends.
# Requests with no cookie all hash the same empty string and land together.
split_clients "${cookie_sessionid}" $products_backend {
    10%  products_svc;
    *    monolith;
}

server {
    listen 80;
    server_name shop.example.com;

    location /products/ {
        proxy_pass    # resolves to an upstream name
        proxy_set_header Host $host;
        # Cookie header is forwarded by default, so both backends see sessionid.
        # Clear any client-supplied identity header. Edge auth, if added, sets
        # it here, and backends trust it only from this proxy.
        proxy_set_header X-User-Id "";
        proxy_cookie_domain products.internal shop.example.com;
    }

    location / {
        proxy_pass
        proxy_set_header Host $host;
        proxy_set_header X-User-Id "";
        # Monolith sets Path=/app/ and an internal Domain. Widen both so the
        # browser also sends the session cookie to /products/.
        proxy_cookie_path   /app/ /;
        proxy_cookie_domain monolith.internal shop.example.com;
    }
}

An nginx config that keys a 10% rollout on the session cookie to keep each user on one backend, rewrites the monolith's cookie Path and Domain so the cookie also reaches /products/, and strips client-supplied identity headers.

How can you shift traffic gradually and roll back in one change?

Start with internal users. A map on a header such as $http_x_route_new or a cookie such as $cookie_route_new can select the new upstream for staff only, so they test real production paths before any customer does. Next, use split_clients on a stable key like $cookie_session to send a small, sticky percentage to the new service. Hashing the session keeps each user on one side. Weighted server entries in an upstream block also split traffic, but per request, so one user can bounce between implementations.

The mirror directive copies requests to the new service and discards its responses. That makes it safe only for read-only routes. A mirrored POST can charge a card twice or write conflicting rows. Because nginx ignores the mirror's responses, the comparison has to happen elsewhere, usually by logging responses on both sides and diffing them offline. Expect noise from timestamps, generated IDs and field ordering. Normalize these fields before diffing, or every response will look different.

To make decisions, log $upstream_addr, $status and $upstream_response_time per route. Then compare old and new error rates and latency percentiles side by side. Agree on rollback triggers before shifting any traffic, for example a higher 5xx rate or slower p99 than the monolith. That way rollback is a planned action, not a debate during an incident.

Keep the config in version control. Review it like application code and test it in CI. Run nginx -t before applying a change, then nginx -s reload. A reload lets existing workers finish their connections, while a restart drops them. Rolling back is then a single reverted commit and another reload.

How does the strangler fig approach affect development cost, and when are you done?

The strangler fig approach costs money while it runs. During the overlap you operate two systems, keep duplicated logic in sync wherever both sides still touch the same behaviour, and maintain the proxy layer. In return, every change is small enough to review and revert, and feature work never stops for a rewrite freeze. Those savings are harder to see than the overlap cost.

Illustrative estimate (assumed numbers, not a benchmark).

  • Overlap cost = overlap months × extra engineer-months per month
  • Freeze cost = freeze months × engineers blocked from feature work

Assume a 12-month overlap with 0.5 engineer-months per month of extra operations and duplicate maintenance. That comes to 6 engineer-months. Compare it with a planned rewrite that freezes 4 engineers' feature work for 6 months, which comes to 24 engineer-months. That figure is before any schedule slip or a failed big-bang cutover. Plug in your own numbers. If the overlap has no end date, the comparison turns against you.

Finishing the job

Once a route has been stable on the new service for an agreed period, delete its monolith code path and tests. That period should cover at least one full business cycle, such as month-end jobs. Unused code still costs you in reviews and security patches.

Also remove the obsolete proxy rules: weighted splits, fallback upstreams and the monolith's location block for that path. Stale rules confuse whoever handles the next incident.

Give the migration one named owner and a written end state, such as "monolith decommissioned" or "monolith serves only internal reporting." Stop strangling when the remainder changes rarely and carries little traffic. At that point, extracting it costs more than keeping it, so freeze it and document it.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to strangler fig pattern reverse proxy, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.