This resume is also available in English.

6. Deploying the system10 / 14 · All columns

Columns › 6. Deploying the system › Part 37

How to Split into Microservices: Rewrite Everything or Carve Out Parts, and How to Cut Over on Kubernetes

微服務怎麼拆:整體重寫還是部分拆,在 Kubernetes 上怎麼切

Once you have decided to split, the next question is how. This article compares a full rewrite with an incremental carve-out, scores the shop’s eight modules against six reasons to split to set the order, moves paths one at a time on Kubernetes with HTTPRoute mirroring and weights, splits the data in three stages, and ends with how to measure success, when to stop, and anti-patterns such as the distributed monolith.

  • Architecture
  • Microservices
  • Kubernetes
In this article
  1. What this article solves
  2. Step 1: Rewrite everything, or carve out parts
  3. Step 2: Reasons to split: business capability first, then whether a separate deployable pays off
  4. Step 3: Scoring the shop’s eight modules
  5. Step 4: Laying it out in the cluster: namespaces and Deployments
  6. Step 5: Moving one path at a time with HTTPRoute
  7. Step 6: The extracted service: its own resources, HPA and NetworkPolicy
  8. Step 7: Splitting the data in three stages
  9. Step 8: How the monolith and the new services call each other
  10. Step 9: How to tell whether the split worked, and when to stop
  11. Step 10: Avoiding the distributed monolith and services that are too small
  12. Common pitfalls
  13. Key takeaways
  14. References
  15. Next

The previous article, “From Monolith to Microservices: Evolving the Architecture at 100K, 1M and 10M Scale”, explained at which scale and on which signals splitting becomes worthwhile, and listed seven steps for safely extracting one service. This article answers the three questions most often asked once the splitting actually starts: should you rewrite everything, or carve out one piece at a time? Which piece goes first, and on what basis? And on Kubernetes, how do you actually move the routing, the deployments and the data across?

What this article solves

The shop has reached the million-user stage. The whole system is still one Go monolith, running as a Deployment called monolith in the shop namespace on Kubernetes, backed by one PostgreSQL; the entry point is one HTTPRoute that sends every path to monolith. Inside, the monolith is divided by business area into eight modules: catalogue, search, cart, order, payment, inventory, notification and admin. Over the past few months several headaches have piled up:

  • During sales, search traffic is more than ten times normal. To keep search alive, the whole monolith has to scale to dozens of replicas, which pushes the number of database connections close to the limit.
  • Once, the external mail service became extremely slow; order requests got stuck waiting for the confirmation email to go out, and the checkout page timed out with them.
  • Payment has to pass a Payment Card Industry Data Security Standard (PCI DSS) audit, but because the payment code shares an executable and a database with everything else, the audit scope has grown to cover the whole monolith.
  • The team has grown from one group to three. Everyone changes the same codebase and queues for the same release train, and a bug in one module sends the whole batch back.

In a meeting, someone proposes: “Let’s just spend six months rewriting the whole system as microservices.” This article starts from that proposal and covers, in order:

  1. The difference between a full rewrite and an incremental split, why big-bang rewrites usually fail, and the few cases where a rewrite is justified.
  2. Six reasons that decide whether something should become its own service, and the signals that say it should not.
  3. A scoring table for the shop’s eight modules, used to set the order of extraction.
  4. How to lay things out in the cluster: namespaces per team or per environment, and which resources each service owns.
  5. The strangler fig pattern with the Gateway API’s HTTPRoute: mirroring, weights, header matches and rollback.
  6. Each extracted service gets its own resource settings, HPA and NetworkPolicy.
  7. Splitting the data in three stages: owned tables, a schema per service, a database per service, plus syncing and cross-service queries during the transition.
  8. Calls between the monolith and the new services: an anti-corruption layer, timeouts and fallback.
  9. How to measure whether splitting worked, and when to stop.
  10. Anti-patterns such as the distributed monolith and services that are too small.

How to find boundaries and bounded contexts, the principle of data ownership and the basics of the strangler fig pattern are covered in “When to Split: Service Boundaries and Decomposition Strategies”; how to write every field, and why, is in “Deploying a Microservice System on Kubernetes” and “A Kubernetes Configuration Reference: What to Write in Each Field, and Why”. This article does not repeat them; it concentrates on making the decision and on cutting over.

Step 1: Rewrite everything, or carve out parts

First, the two paths:

  • Big-bang rewrite: set up a separate team, or pause most feature work, write a new microservice system from scratch, and when it is finished pick a day to move all the traffic and data across at once.
  • Incremental carve-out: the monolith keeps running and keeps shipping features; each time, one piece is extracted from the monolith into its own service, and only once it is stable do you decide on the next. The monolith gradually shrinks, and may keep a core for ever.
Big-bang rewrite Old system: still changing, still fixing bugs New system: rebuilds everything, chasing the old one Switch day All value and risk land on one day; data moves at once; rollback is hard Incremental one at a time Monolith: keeps shipping features, slowly shrinks Notification Search Payment Next? Re-score Every step is small and reversible; value arrives with the first one time

Figure: a full rewrite runs old and new systems side by side and loads all value and risk onto the final switch day; an incremental split ships, and can be rolled back, at every step.

Why big-bang rewrites usually fail. Rewrites rarely fail because the new technology is bad; they fail because the shape of the project is dangerous in itself:

  • Frozen features, or an endless chase. The business does not stop while you rewrite. Either you freeze requirements on the old system and the business loses six months of progress, or you build everything twice and the new system is for ever chasing a moving target.
  • Hidden rules live in the old code. The odd-looking checks in the monolith (a shipping exception for one region, one kind of refund that needs manual review) are often business rules accumulated from years of incidents and written down nowhere. Miss them in a rewrite and they only reappear after launch, as incidents.
  • All the data moves at once. Every table moves to the new structure on the same night. A conversion error in any column affects every feature at the same time, and it is hard to roll back only part of it.
  • No way back. If something goes wrong after the switch, going back to the old system means moving all the data created since the switch back as well. Most teams at that point can only push forward and fix.
  • Value arrives late. For six months to a year, neither users nor the business see any improvement. Running out of budget or patience halfway is the most common ending for rewrite projects.

An incremental split spreads these risks out: each step touches only one feature and part of the data, the old path stays until the new one has proved itself, and value starts arriving as soon as the first piece is out.

AspectFull rewriteIncremental split
Business featuresFrozen, or built twiceMonolith keeps shipping
Risk distributionConcentrated on switch daySpread across every small step
Data migrationEverything at onceOne module’s data at a time
RollbackAlmost impossibleChange the route back at any step
When value appearsAfter everything is doneAfter the first piece
Target architectureMust be decided up frontAdjusted as you go; can stop at any step
FitsTiny system, dead stack, compliance resetMost systems that are live and growing

The few cases where a full rewrite is justified. Rewriting is not always wrong. Three situations deserve serious thought:

  • The system is tiny. For a system of a few thousand lines and a handful of screens, a rewrite takes weeks, and the scaffolding of a split (routing, syncing, comparing) would cost more than the rewrite itself.
  • The technology is dead. The runtime no longer gets security updates, nobody can be hired to maintain it, or it cannot run on modern infrastructure. The premise of an incremental split, that the old system can keep running safely, no longer holds.
  • Compliance requires a reset. For example, rules on data retention or encryption change and the old data model simply cannot comply; it has to be redesigned.

Even then, do not switch in one go: run the old and new systems in parallel for a while (a parallel run). Both handle the same requests, only the old system’s result is used, and the differences are compared; once the comparison is stable, move traffic over in proportions. In other words, even if the code is rewritten as a whole, the launch should still be incremental.

Back to the shop: the system is making money, the team keeps adding features and the tech stack is fine. The answer is clear: carve out parts. The next question is which part first.

Step 2: Reasons to split: business capability first, then whether a separate deployable pays off

The first step in finding boundaries is always business capability and bounded contexts: search, payment and notification are different business capabilities, each with its own language and data. But “it is a separate business capability” only means it can be split, not that it should become a separately deployed service; it can just as well be a module in a modular monolith. For a piece of functionality to be worth the cost of network calls, eventual consistency and another deployment, it needs at least one of the following reasons, and the more the better:

ReasonScenario (examples from the shop)Why it needs its own deploymentWhen it does not hold
Different scaling profileSearch traffic surges during sales; everything else stays flatScale only what needs it, instead of the whole monolith to dozens of replicasScaling the monolith horizontally is still affordable; the bottleneck is the database
Different release cadenceNotification templates change several times a week; checkout once a monthFrequently changed parts do not queue for the monolith’s release trainChange rates are similar, or the release process is already fast
Team ownershipPayment is owned by a dedicated groupOne owner per service: clear responsibility, on-call and decisions (Conway’s law)One group owns several pieces; splitting only adds to their operational load
Fault isolationA slow mail service must not take checkout downSeparate processes, resource limits and timeouts stop failures at the boundaryThe two must succeed together anyway; one is useless when the other is down
Security and compliance boundaryPCI DSS audit scope for paymentKeep tightly controlled code and data inside the smallest possible areaYou use the payment provider’s hosted page, so card numbers never touch you
Different technical needsSearch needs a full-text engine; image processing needs lots of CPUUse a fitting runtime and resources without making the monolith carry themYou just want to try another language or framework

“Conway’s law” in the third row says that the structure of a system ends up mirroring the communication structure of the organisation. With three teams sharing one codebase, conflicts and coordination costs never go away; conversely, if you have one team, splitting into five services does not reduce communication, it only gives the same people four more deployments to run. So team structure is both a reason to split and a reason not to.

Signals not to split. When these appear, stop and rethink the boundary even if the reasons above apply:

  • Shared transactions everywhere. Most writes to the two pieces must happen in the same database transaction, as with an order and its line items. After splitting, every operation becomes a saga and complexity explodes.
  • Same team, same release cadence. Splitting brings no independence, only one more network boundary.
  • Chatty calls. One operation needs several round trips between the two, or most of one side’s features must synchronously query the other. That usually means the boundary is in the wrong place.
  • The business is still changing a lot. While boundaries are unstable, a wrong line inside the monolith is fixed by changing an import; between services, you change APIs, databases and deployments.

Step 3: Scoring the shop’s eight modules

Turn the six reasons from Step 2 into a table. Each reason scores 0 to 2; subtract “coupling” (0 to 3, higher the more shared transactions and synchronous calls it has with other modules), and you get a rough total:

Module Scale Release Team Fault Comply Tech Coupl. Total Recommendation Catalogue · · · · · −2 −1 Stay Search · −1 6 2nd Cart · · · · −2 0 Stay Order · · · · −3 −1 Last or never Payment · · −2 4 3rd Inventory · · · −3 1 If sales spike Notification · · 0 5 1st (pilot) Admin · · · · · −3 −2 Stay Each square = 1 point (max 2), · = 0; total = six reasons − coupling; shaded: total ≥ 4

Figure: each small square is one point, and the total is the sum of the six reasons minus coupling; notification, search and payment, with totals of 4 or more, are the first candidates.

The reasons behind each score:

ModuleMain pointsCouplingTotalRecommendation
CatalogueHeavy reads, but caching handles them (scale 1)Search, cart and order all read it (2)−1Stay in the monolith; publish product events
SearchSurges during sales (scale 2), needs a full-text engine (tech 2), and moreOnly reads product data, which events can sync (1)6Split second
CartFrequent reads and writes (scale 1), suits a cache (tech 1)Closely tied to prices, stock and orders at checkout (2)0Stay in the monolith
OrderOwned by the core team (team 1)At the centre of almost every flow (3)−1Split last, or keep in the monolith’s core for good
PaymentFault isolation 2, compliance 2, plus a dedicated group and its own cadenceCheckout needs the payment result synchronously (2)4Split third
InventoryHot rows and lock contention in flash sales (scale 2), fault 1, team 1Needs strongly consistent reservations with orders (3)1Split when flash sales demand it
NotificationExternal provider often slow (fault 2), templates change often (release 1), and moreOnly needs the fact that an order was placed, asynchronously (0)5Split first (pilot)
AdminChanges often (release 1)Reads everything and changes everything (3)−2Stay in the monolith

Note three things:

The score is a discussion tool, not a formula. Different shops will score the same table differently, and the weights should follow your real pain: if the compliance audit already has a date, payment’s compliance score deserves more weight. The real value of the table is that it forces everyone to state concrete reasons for splitting a piece, instead of “microservices are better”.

The first one out is not necessarily the highest score. Search has the highest total, yet notification goes first: its coupling is 0, it only needs to receive “order placed” asynchronously, and if it goes wrong, users merely get their email a little later. The real job of the first service is to be a pilot: to walk the whole path of CI pipeline, image, namespace, monitoring, alerting and on-call once. Practising on the safest piece is much cheaper than practising on the most valuable and most dangerous one.

Order goes last, or never. Order sits at the centre of every flow; moving it out means turning most transactions into sagas. Once notification, search and payment are out, the remaining monolith (catalogue, cart, order, inventory, admin) is often already a reasonably sized service owned by one team. Stopping there is a perfectly legitimate end point.

So the shop’s order of extraction is notification → search → payment, followed by a fresh scoring round to see whether flash sales make inventory worth extracting.

Step 4: Laying it out in the cluster: namespaces and Deployments

After the three services are out, the production cluster looks like this:

Production cluster (non-prod lives in another cluster) gateway-system: Gateway + HTTPRoute (paths and weights) namespace shop (shop team) search HPA 3–30 notification HPA 2–6 monolith catalogue · cart · order inventory · admin HPA 4–12 namespace nats JetStream shop-payment (PCI scope, own RBAC) payment HPA 2–6 gRPC Each Deployment: own Service, HPA, config, secrets, NetworkPolicy PostgreSQL monolith’s PostgreSQL payment only Search index search only Managed, outside

Figure: search and notification sit with the monolith in the shop team’s shop namespace; payment has its own shop-payment namespace for compliance; each service owns its data store outside the cluster.

Namespaces per team, or per environment? This is the first cluster-level decision when splitting:

ApproachWhat it looks likeBenefitsCostsFits
One per environmentshop, shop-dev, every service insideSimple; services call each other by short names; one set of NetworkPolicyPermissions and quotas cannot differ per team; one team’s mistake affects every serviceOne team, or the start of a split
One per teamshop, shop-payment …, each environment in its own clusterRBAC, ResourceQuota and NetworkPolicy boundaries match ownershipCross-namespace calls need full DNS names; cross-namespace routes need a ReferenceGrantSeveral teams, or a compliance boundary
One per team per environmentpayment-prod, payment-dev … in the same clusterFewest clustersNamespaces multiply; prod and non-prod share a control plane and nodes; weakest isolationSmall organisations, non-prod clusters

The shop’s choice: production and non-production in different clusters, and namespaces per team inside each cluster. The monolith, search and notification, owned by the shop team, live in shop; the payment group’s service lives in shop-payment. Compared with the shop and shop-dev of “Deploying a Microservice System on Kubernetes”, the difference is an extra team and compliance boundary. If you have one team, keep one namespace per environment; there is no need to split namespaces just because you split services.

The payment namespace carries Pod Security labels and grants permissions only to the payment group:

# deploy/k8s/payment/namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: shop-payment
  labels:
    pod-security.kubernetes.io/enforce: restricted
    app.kubernetes.io/part-of: shop
    team: payments
---
# The payment group can edit in its own namespace; other teams cannot
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: payments-team-edit
  namespace: shop-payment
subjects:
  - kind: Group
    name: payments-team # matches the group name in the identity provider
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: edit
  apiGroup: rbac.authorization.k8s.io

edit is a built-in user-facing ClusterRole in Kubernetes; bound with a RoleBinding, it applies only in this namespace. Give each team’s namespace its own ResourceQuota and LimitRange as in “A Kubernetes Configuration Reference: What to Write in Each Field, and Why”, so that one team’s runaway replicas cannot eat the whole cluster.

A word of caution: a namespace is not complete compliance isolation. It draws the boundary for permissions, quotas and network rules, but payment Pods may still run on the same node as other Pods. How strict the isolation must be (a dedicated node pool, a dedicated cluster) is something to confirm with your auditor. Another common approach is to use the payment provider’s hosted payment page or tokenisation, so card numbers never pass through your own system and the scope shrinks at the source.

Because the monolith calls payment across namespaces, the address uses the full name: PAYMENT_ADDR=payment.shop-payment.svc.cluster.local:9090. Search and notification, in the same namespace, can still use short names.

Step 5: Moving one path at a time with HTTPRoute

“When to Split: Service Boundaries and Decomposition Strategies” showed the strangler fig routing layer as a Go reverse proxy. On Kubernetes, the same thing can be written straight into a Gateway API HTTPRoute: which paths go to the monolith, which to the new service, and in what proportion, all as declarative configuration that lives in git, gets reviewed, and is applied by the flow from “GitOps with Argo CD: Let the Cluster Follow git on Its Own”. Rolling back is a git revert.

Tip: keep routing in one layer. If you already have a Go gateway like the one in “Building an API Gateway in Go: Routing, Authentication and Rate Limiting”, write the migration rules in the gateway’s routing table and let the HTTPRoute simply hand traffic to the gateway. If two layers both decide where the same path goes, nobody can tell where traffic actually went during an incident. The shop in this article has no separate gateway yet, so it uses the HTTPRoute directly.

Taking search as the example, the move has three stages:

① Shadow: mirror HTTPRoute PathPrefix /api/search monolith search serves mirror Users only see monolith results ② Weights 90 / 10 HTTPRoute PathPrefix /api/search monolith search 90 10 On errors, set 10 back to 0 ③ Weights 0 / 100 HTTPRoute PathPrefix /api/search monolith search 0 100 Stable a cycle: delete old code Every other path (/api/orders, /api/cart …) stays on the monolith throughout

Figure: mirror first and only compare; then send a small share by weight; finally hand everything to the new service while the monolith keeps a weight of 0 for rollback.

Stage one: mirroring (shadow traffic). The monolith still answers users’ requests, and a copy of each is sent to search:

# deploy/k8s/shop/httproute.yaml (stage one)
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: shop
  namespace: shop
spec:
  parentRefs:
    - name: public
      namespace: gateway-system
  hostnames:
    - shop.example.com
  rules:
    - matches:
        - path:
            type: PathPrefix
            value: /api/search
          method: GET
      filters:
        - type: RequestMirror
          requestMirror:
            backendRef:
              name: search
              port: 8080
            percent: 100
      backendRefs:
        - name: monolith
          port: 8080
    - matches:
        - path:
            type: PathPrefix
            value: /
      backendRefs:
        - name: monolith
          port: 8080

Points to watch:

  • Mirrored responses are discarded. The specification says responses from the mirror target are ignored, so the gateway does not compare results for you. Comparison is a separate job: both sides log their results under the same request ID (the request ID from “Observability in Go: Logs, Metrics and Tracing” earns its keep here), and an offline program pairs and compares them by request ID. Search results need not match word for word; a metric such as “overlap of the top 10 results” is more practical.
  • Mirror reads only. The rule is limited with method: GET. Never mirror write requests, or the same operation runs twice.
  • percent controls the mirrored share. If the new service cannot take full traffic yet, start at 10. With neither percent nor fraction set, everything is mirrored.
  • Mirroring is an “Extended” feature. The Gateway API divides features into Core (every implementation must support them) and Extended (implementations may choose to). RequestMirror and method matching are both Extended; before applying, confirm your Gateway implementation supports them, and check the HTTPRoute status for error conditions.

Stage two: weights and header matches. Once the comparison is stable, let the new service really answer part of the requests:

# deploy/k8s/shop/httproute.yaml (stage two)
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: shop
  namespace: shop
spec:
  parentRefs:
    - name: public
      namespace: gateway-system
  hostnames:
    - shop.example.com
  rules:
    # Requests carrying this header always go to the new service, for internal testing
    - matches:
        - path:
            type: PathPrefix
            value: /api/search
          headers:
            - name: X-Shop-Canary
              value: search
      backendRefs:
        - name: search
          port: 8080
    # Everyone else is split by weight: weight is a proportion, not a percentage
    - matches:
        - path:
            type: PathPrefix
            value: /api/search
      backendRefs:
        - name: monolith
          port: 8080
          weight: 90
        - name: search
          port: 8080
          weight: 10
    - matches:
        - path:
            type: PathPrefix
            value: /
      backendRefs:
        - name: monolith
          port: 8080
  • Match precedence follows rules. The specification compares the path first (Exact beats PathPrefix, and a longer prefix wins), then the method when paths tie, then the number of header matches. So requests with X-Shop-Canary hit the first rule, ordinary /api/search requests hit the second, and everything else hits /. Do not rely on the order of rules in the file to set priority.
  • weight is a proportion. The actual share is a backend’s weight divided by the sum of all weights, and the sum need not be 100; a weight of 0 sends no traffic. If omitted, the weight defaults to 1.
  • Anyone can send a header. External users can add X-Shop-Canary themselves too. For read-only search that is harmless; on paths that change data, strip or validate the header at the edge, and never treat it as a permission.
  • Weights are drawn per request. The same user’s two consecutive searches may land on the monolith and then on the new service. Search can live with that; where users would notice the difference (a cart, say), use a header or cohort-based routing so the same person always lands on the same side.

Step the weights through 90/10, 50/50 and 0/100, watching error rates, latency and comparison results between steps. If something goes wrong, set search’s weight back to 0; once the Gateway configuration updates, new requests go back to the monolith, with no program redeployed.

Stage three: everything to the new service. The weights become monolith: 0 and search: 100, and the monolith entry stays for a while as a way back. After at least one full business cycle (one big sale, say) without problems, simplify the rule to point at search only, and delete the search code from the monolith.

Finally, a route’s backendRefs can by default only point at Services in the same namespace. To send a path to another namespace (for example, a future public callback endpoint for payment), the target namespace must create a ReferenceGrant that allows the reference. This is a deliberate safety mechanism in the Gateway API, so that no namespace can direct traffic at someone else’s service.

Step 6: The extracted service: its own resources, HPA and NetworkPolicy

A main reason to split is to let each service scale and be protected in its own way. If the extracted search service keeps the monolith’s resource settings and replica count, the benefit of splitting is wasted. Write the Deployment’s full set of fields as in “Deploying a Microservice System on Kubernetes”; only the parts where search differs from the monolith are shown here:

# deploy/k8s/shop/search/deployment.yaml (only the parts that differ from the monolith)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: search
  labels:
    app.kubernetes.io/name: search
    app.kubernetes.io/part-of: shop
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: search
  template:
    metadata:
      labels:
        app.kubernetes.io/name: search
        app.kubernetes.io/part-of: shop
    spec:
      containers:
        - name: app
          image: registry.example.com/shop/search:latest
          ports:
            - name: http
              containerPort: 8080
          envFrom:
            - configMapRef:
                name: search-config # only the settings search needs
          volumeMounts:
            - name: secrets
              mountPath: /etc/shop/secrets
              readOnly: true
          resources:
            requests:
              cpu: 250m # search is CPU-bound; measure it separately from the monolith
              memory: 256Mi
            limits:
              memory: 512Mi
      volumes:
        - name: secrets
          secret:
            secretName: search-secrets # only the search index credentials, not the monolith's DB password
---
apiVersion: v1
kind: Service
metadata:
  name: search
  labels:
    app.kubernetes.io/name: search
spec:
  selector:
    app.kubernetes.io/name: search
  ports:
    - name: http
      port: 8080
      targetPort: http
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: search
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: search
  minReplicas: 3
  maxReplicas: 30
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 60
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0
    scaleDown:
      stabilizationWindowSeconds: 600

The differences from the monolith map directly onto the reasons in Step 2:

  • Separate scaling range. Search can grow from 3 to 30 replicas during a sale while the monolith stays at 4 to 12. Before, scaling for search meant dozens of monolith replicas, each holding a set of database connections; now only search scales, and search does not connect to the monolith’s database at all.
  • Separate scaling pace. Search traffic arrives suddenly, so scaleUp does not wait and scaleDown watches for 10 minutes; the monolith can keep more conservative settings.
  • Separate config and secrets. The search Pods mount only search-config and search-secrets and do not reference the monolith’s database password. Combine this with one ServiceAccount per service and no API permission to read Secrets, and even a compromised search service cannot reach order or payment data.

NetworkPolicy: write the call graph down as rules. Every time you extract a service, write down who may call it at the same time. Keep the default-deny approach (Step 5 of “Deploying a Microservice System on Kubernetes”) and allow paths one by one:

# shop namespace: search accepts traffic only from the Gateway
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: search-from-edge
  namespace: shop
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/name: search
  policyTypes: ['Ingress']
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: gateway-system
      ports:
        - port: 8080
---
# shop-payment namespace: deny all incoming connections by default
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-ingress
  namespace: shop-payment
spec:
  podSelector: {}
  policyTypes: ['Ingress']
---
# Only the monolith in the shop namespace may call payment's gRPC port
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: payment-from-monolith
  namespace: shop-payment
spec:
  podSelector:
    matchLabels:
      app.kubernetes.io/name: payment
  policyTypes: ['Ingress']
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: shop
          podSelector:
            matchLabels:
              app.kubernetes.io/name: monolith
      ports:
        - port: 9090

In the last rule, namespaceSelector and podSelector sit in the same from entry, meaning “Pods labelled monolith in the shop namespace”: both conditions must hold. Written as two entries each starting with -, it becomes “any Pod in the shop namespace, or the monolith in this namespace”, which lets far more through. This is one of the most common NetworkPolicy mistakes.

Notification only receives events from NATS and calls out to the mail provider; nobody needs to connect to it, so apart from monitoring scraping metrics, no incoming connections need to be allowed. Services in compliance scope such as payment usually also need egress restrictions (only their own database and the payment provider); when writing Egress rules, remember to allow DNS.

Step 7: Splitting the data in three stages

Once routing and deployment are split, the data is often still in the monolith’s database. Code split but data not is the most common half-finished state. The end point is clear, each service owns its own database, but jumping there in one step is as risky as a full rewrite. A steadier route has three stages:

① Shared DB, owned tables monolith payment PostgreSQL orders, carts … payments, refunds Only payment’s role writes ② One instance, own schema monolith payment Same instance public payment Remove cross-schema JOINs ③ Own database monolith payment DB monolith DB payment Scale and audit apart Transition: sync via outbox/CDC, dual-read and compare, then hand over writes

Figure: first give every table a single owner, then move the tables into their own schema, and finally into their own database; between stages, syncing and comparison confirm the data agrees.

Stage one: shared database, but every table has one owner. The payment code is still in the monolith (or has just moved out), and the data is still in the same database. The goal here is to turn “only payment writes payment tables” from an agreement into a rule the database enforces. A monolith usually connects with a single database account, so first give the payment module a second connection pool inside the monolith, connecting with its own account, and then revoke the other accounts’ write access:

-- Stage one: tables stay in public, but only payment's account can write
CREATE ROLE payment_svc LOGIN;
GRANT SELECT, INSERT, UPDATE ON payments, refunds TO payment_svc;
GRANT USAGE ON SEQUENCE payments_id_seq, refunds_id_seq TO payment_svc;
REVOKE INSERT, UPDATE, DELETE ON payments, refunds FROM monolith_app;

-- Stage two: move into a separate schema the monolith's account cannot see at all
CREATE SCHEMA payment AUTHORIZATION payment_svc;
ALTER TABLE payments SET SCHEMA payment;
ALTER TABLE refunds SET SCHEMA payment;
REVOKE ALL ON SCHEMA payment FROM PUBLIC;
ALTER ROLE payment_svc SET search_path = payment;

After the write access is revoked, any stray write (a button in admin, some batch job) fails outright and leaves an error behind, instead of quietly carrying on. That is far more reliable than finding omissions in code review. Stage one still lets the monolith read payment data, but list every read; they are what the next stage must deal with.

Stage two: one instance, a schema per service. Move the payment tables into the payment schema. The monolith’s account has no usage right on that schema and cannot even read it. ALTER TABLE … SET SCHEMA moves the table’s indexes, constraints and column-owned sequences along with it, and must be run by the table’s owner (usually the migration account); before moving, make sure every cross-schema JOIN has been removed. This stage is cheap: still the same database, the same backups and monitoring, but the boundary is now real. If the boundary turns out to be wrong, moving the table back is one line of SQL.

Stage three: a database per service. When payment needs to scale on its own, needs its own audit scope, or simply should not suffer from other services’ slow queries, move it to its own database instance. Only this step needs a real data migration: a full copy first, then a sync mechanism to catch up on changes, and the write cut-over once the two agree.

Syncing during the transition. Around the stage-three cut-over, both sides must stay in sync, using the approach from “Distributed Transactions: Sagas and the Outbox Pattern”: the writer stores the data and an outbox row in the same transaction and a relay publishes the event; or CDC reads the database’s transaction log. The difference between the two, and why not to dual-write from the application, was covered in Step 7 of the previous article. One practical addition here is dual reads with comparison: before the cut-over, the reading code reads both old and new, returns the old result, compares the new one and records differences as a metric. Hand over write ownership only after the difference rate has stayed at zero for a while.

After the split, what about cross-service queries? The admin “order list” shows orders together with their payment status. That used to be one JOIN; now the two sets of data live in different databases. There are two common approaches:

ApproachHowFitsDoes not fit
API compositionQuery orders, then batch-query the payment service by order ID and merge in memorySmall result sets that need fresh values, e.g. order detailsLarge lists filtered, sorted or paged by the other side’s fields
Read modelSubscribe to payment events and maintain a read-only query table on your own sideAdmin lists, reports, search and other read-heavy usesFlows that must read a value just written and cannot accept lag

With API composition, query in batches (a batch of IDs at once, never one by one) and prepare a degraded display for when the other side is down (for example, payment status shown as “temporarily unavailable”). A read model must accept lag and make its event handling idempotent. When neither works, it usually means those two sets of data should not have been split.

Step 8: How the monolith and the new services call each other

Notification is the first service out. The order module in the monolith used to call the notification module’s function directly to send the confirmation email; once notification moves out, that call becomes a network call. The key is not to let the rest of the monolith know: it keeps depending on the same interface, and behind it sits an anti-corruption layer. The anti-corruption layer does three things:

  1. Translates the model. The monolith’s Order has dozens of fields, some of them internal notes that must not reach other services. The anti-corruption layer picks only the fields notification needs and converts them to the notification service’s contract. The new service’s model is not polluted by the monolith’s history, and the monolith does not depend on the new service’s data structures.
  2. Adds a timeout. A local function call never “gets five seconds slower”; a network call does. Every call needs its own timeout.
  3. Falls back to the old implementation. During the move, when the remote call fails, it falls back to the monolith’s original mail code, and a switch can send everything back to it.
// Package notify is the notification module inside the monolith. It offers the
// Notifier interface to the other modules, and uses an anti-corruption layer to
// translate the monolith's data model into the notification service's contract.
package notify

import (
	"context"
	"errors"
	"strconv"
	"sync/atomic"
	"time"
)

// Order is the monolith's order model (simplified); the notification service should not know its shape
type Order struct {
	ID            string
	CustomerEmail string
	CustomerName  string
	TotalMinor    int64 // minor units, e.g. whole dollars for TWD, cents for USD
	Currency      string
	InternalNote  string // used only inside the monolith; must not leak to other services
}

// Notifier is the interface the rest of the monolith sees; it does not change during the move
type Notifier interface {
	OrderConfirmed(ctx context.Context, o Order) error
}

// SendRequest is the notification service's contract (generated from .proto in practice)
type SendRequest struct {
	IdempotencyKey string
	Template       string
	To             string
	Params         map[string]string
}

// Client calls the notification service (a generated gRPC client in practice)
type Client interface {
	Send(ctx context.Context, req SendRequest) error
}

// Adapter is the anti-corruption layer: it translates the model, adds a timeout,
// and falls back to the old implementation inside the monolith when the remote call fails
type Adapter struct {
	Remote    Client
	Legacy    Notifier    // the monolith's original mail code, kept during the move
	Enabled   func() bool // switch wired to config or a feature flag; off means old code only
	Timeout   time.Duration
	Fallbacks atomic.Int64 // number of fallbacks; export it as a metric and alert on it
}

// OrderConfirmed implements Notifier; callers cannot tell whether it is remote or local
func (a *Adapter) OrderConfirmed(ctx context.Context, o Order) error {
	if a.Enabled == nil || !a.Enabled() {
		return a.Legacy.OrderConfirmed(ctx, o)
	}
	rctx, cancel := context.WithTimeout(ctx, a.Timeout)
	err := a.Remote.Send(rctx, translate(o))
	cancel()
	if err == nil {
		return nil
	}
	// The caller cancelled or ran out of time: do not fall back after the user has gone
	if ctx.Err() != nil {
		return ctx.Err()
	}
	a.Fallbacks.Add(1)
	if lerr := a.Legacy.OrderConfirmed(ctx, o); lerr != nil {
		return errors.Join(err, lerr)
	}
	return nil
}

// translate picks only the fields a notification needs and formats the amount as the contract expects
func translate(o Order) SendRequest {
	return SendRequest{
		IdempotencyKey: "order-confirmed:" + o.ID,
		Template:       "order_confirmed",
		To:             o.CustomerEmail,
		Params: map[string]string{
			"name":        o.CustomerName,
			"order_id":    o.ID,
			"total_minor": strconv.FormatInt(o.TotalMinor, 10),
			"currency":    o.Currency,
		},
	}
}

The code comes with tests covering: only the old implementation runs when the switch is off; on remote success the translation is correct and the internal note does not leak; on a remote error or timeout it falls back; when the caller itself times out it does not fall back; and when both sides fail, both errors are kept. A few design trade-offs:

  • The timeout must be shorter than the caller’s. The anti-corruption layer’s timeout (say 300 milliseconds) must be clearly shorter than the whole checkout request’s deadline, to leave time to fall back. The full design of timeouts, retries and circuit breakers is in “Timeouts, Retries and Circuit Breakers”; add a circuit breaker when the remote side keeps failing, so you do not wait out the full timeout before every fallback.
  • Fallback can cause duplicates. If the remote side actually sent the email but replied too slowly, the old code sends it again after fallback. IdempotencyKey lets the notification service deduplicate on its own, but the old mail code cannot. For a confirmation email, an occasional duplicate is better than a missing one, so the trade-off is acceptable. Never do this for payment: a payment call must not “fail and then try another route”; it may only retry the same service with an idempotency key, see “Idempotency and Distributed Locks”.
  • Fallback is a tool for the transition. Export Fallbacks as a metric and alert on it. Once the new service has been stable for a while, delete Legacy and the switch, leaving only translation and the timeout in the anti-corruption layer.
  • It can become an event later. Notification does not really need a synchronous call: the monolith writes to the outbox in the order transaction and publishes an order.placed event, and notification subscribes. At that point you only swap Adapter for an implementation that writes to the outbox; the Notifier interface and its callers do not change at all. That is the value of putting the interface in place first.

Synchronous calls between services use gRPC, with the contract in a .proto file; the generated client fits the Client interface above, see “gRPC and Protocol Buffers in Go”.

Step 9: How to tell whether the split worked, and when to stop

Splitting is an investment and should be judged by results. Take a baseline before you start and compare after every extracted service:

MetricHow to measureLooks like it workedLooks like it went wrong
Deployment frequencyReleases per service per weekExtracted services release noticeably more oftenNo change, or everyone still rides the same train
Lead time for changesTime from merge to productionShorterLonger, because several services must be coordinated
Change failure rate, time to restoreShare of releases needing rollback or a fix; time to fixSmaller blast radius, faster rollbackOne release often needs several services rolled back
Coordinated releasesHow many services one change must touch and release togetherMost changes touch one serviceTwo or three services often ship together
Cross-service incidentsHow often one service’s failure affects othersNotification down, checkout fineOne slow service slows the whole call chain
Peak latency and costp99 latency at the entry; cluster and database billsOnly search scales during sales; cost goes downExtra network hops; latency and cost both rise

The first four are variants of the well-known DORA metrics; the last two map directly onto “scaling” and “fault isolation” from Step 2. If none of these numbers improve after a service is extracted, do not rush to the next one; go back and check the boundary.

When to stop. Splitting does not have to continue until the monolith is gone. These are the moments to stop:

  • The original pain points (search scaling, mail stalling checkout, payment audit scope, teams blocking each other) are solved.
  • In a fresh scoring round, every remaining module scores low or is highly coupled.
  • The remaining monolith is owned by one team, is understandable in size and releases smoothly: it is already a good service, it just happens to be called a monolith.
  • The operational load (on-call, monitoring, upgrades) starts to exceed what the team can carry.

After notification, search and payment are out, inventory scores just 1 in the next round. Until flash sales actually cause problems, stopping here is the right answer.

Step 10: Avoiding the distributed monolith and services that are too small

The most common failure of a split is not failing to extract anything; it is extracting something worse than the monolith.

Distributed monolith Well-cut services api-gateway order inventory payment notification Shared database 4 sync hops; ship together, fail together api-gateway order payment gRPC NATS events: order.placed … inventory DB search DB notification DB One sync call; the rest via events; own data

Figure: on the left, one request passes synchronously through four services sharing one database, so trouble in any service affects the whole chain; on the right, only the necessary synchronous call remains, the rest go through events, and each service owns its data.

The distributed monolith. The code is split into several Deployments, but they share a database, synchronous calls stack layer upon layer, and changing one column means releasing several services together. You pay every cost of microservices (network latency, more deployments, distributed debugging) and get no independence. On Kubernetes it has some observable symptoms:

  • In Argo CD, syncing one service only works if another service has been synced first.
  • One service failing readiness makes the error rates of several others rise at the same time.
  • Your NetworkPolicy ends up letting almost every service reach every other.
  • Several services’ Secrets contain the same database username and password.

The fix is to go back to Steps 2 and 7: split the shared data, turn the steps of the synchronous chain that do not need an immediate answer into events, and merge back services that always change together.

Nano-services. One service per entity, or even per function. Each service is small and easy to understand, but one feature passes through five or six services, any call can time out, and every service must be deployed, monitored and covered on call.

Monolith Modular monolith A few services by capability One service per entity One service per function Where most teams belong ← Too coarse: tied deploys, one fault hits all Too fine: calls, deploys and on-call explode →

Figure: the spectrum from a monolith to one service per function; for most teams, a few services cut by business capability is the right place.

There is no standard answer for granularity, but there is a practical upper bound: one service should be fully owned by one team, and the number of services a team owns should be small enough that each gets proper care. Three teams and, after the split, four deployable units (monolith, search, notification, payment) is a sensible ratio for the shop.

Two more anti-patterns that show up easily during a split:

  • Shared libraries holding business logic. To “avoid duplication”, order total calculation and discount rules go into a package every service imports. Every rule change means upgrading the package in every service and redeploying, and different services end up running different versions of the rules. Shared libraries should hold only genuinely generic things (log format, tracing, gRPC interceptors); business rules stay in the service that owns them, and other services get results through APIs or events.
  • Splitting by technical layer. An “API service”, a “business logic service” and a “data access service”. Every feature passes through three services and every change touches all three. Cut services vertically by business capability, not horizontally by technical layer.

Common pitfalls

  • Disguising a rewrite as a split. While extracting a service you also redesign the data model, switch language, switch framework and add features. Every extra variable adds a difference the comparison cannot explain. Make the new service behave exactly like the monolith during the split, and improve it after the cut-over.
  • Extracting the most central module first. With order or payment as the pilot, the team is learning a new pipeline, monitoring and on-call while facing the highest risk. Choose the least coupled piece with the smallest blast radius for the first service.
  • Mirroring write requests. A RequestMirror on a path that includes POST makes the new service perform the write too, and the same operation happens twice. Always restrict mirroring rules to read-only methods, or have the new service write nothing in shadow mode.
  • Treating a header match as a permission. Routing with a header like X-Shop-Canary is convenient, but anyone can send that header. Paths that change data must not rely on it alone to decide where requests go.
  • Splitting from into two entries in a NetworkPolicy. With namespaceSelector and podSelector as two separate entries starting with -, the result is an “or”, which lets more through than intended. To express “certain Pods in a certain namespace”, put both in the same entry.
  • Splitting the code but not the data, and stopping there. The new service reads and writes tables in the monolith’s database directly, with a promise to “split the data later”. That later often never comes, and the system becomes a distributed monolith. Get at least to stage one of Step 7: the database enforces a single owner per table.
  • Never deleting the old code. The weights have been 0/100 for six months, yet the old search code in the monolith, the weight-0 entry in the HTTPRoute and the fallback path in the anti-corruption layer are all still there. Keeping a way back for one full business cycle is enough; after that, put the deletion on the plan.
  • Splitting without a baseline. If you cannot say afterwards whether deployment frequency, incident count or latency got better or worse, you cannot judge whether the next split is worth it. Measure first, then split.

Key takeaways

  • A system that is already live should almost always be split incrementally: every step small, reversible and delivering value. Consider a full rewrite only for a tiny system, a dead stack or a compliance reset, and even then launch with a parallel run and a gradual switch.
  • Business capability decides where you can cut; six reasons (scaling profile, release cadence, team ownership, fault isolation, compliance boundary, technical needs) decide whether a separate deployable pays off. Shared transactions everywhere, the same team and chatty calls are signals not to split.
  • Use a scoring table to make the reasons explicit, and extract the least coupled module first as the pilot; the shop’s order is notification, search, payment, with order last or never.
  • With several teams or a compliance boundary, use namespaces per team and separate environments by cluster; a namespace is not complete compliance isolation.
  • On Kubernetes, move paths with an HTTPRoute: RequestMirror for read-only shadowing with offline comparison first, then weight to ramp up, header matches for internal testing, and rollback by changing a weight.
  • Each extracted service needs its own resources, HPA, config, secrets and NetworkPolicy, or the benefits of splitting never materialise.
  • Split data in three stages: the database enforces one owner per table, then a schema per service, then a database per service; sync with an outbox or CDC and compare with dual reads during the transition; handle cross-service queries with API composition or read models.
  • The monolith calls new services through an anti-corruption layer that translates the model, adds a timeout and can fall back during the move; operations like payment must never use a “fail, then try another route” fallback.
  • Judge results by deployment frequency, lead time, failure rate, coordinated releases and cross-service incidents; stop once the pain is gone, and avoid the distributed monolith and nano-services.

References

  • Strangler Fig (Martin Fowler): replacing a system gradually instead of a big-bang rewrite, used in steps 1 and 5.
  • API Reference (v1.7) (official Gateway API documentation): match precedence, weight defaulting to 1 and mirrored responses being ignored, used in step 5.
  • HTTP request mirroring (official Gateway API documentation): how to configure RequestMirror, used in phase one of step 5.
  • ReferenceGrant (official Gateway API documentation): cross-namespace references requiring permission from the target namespace, noted at the end of step 5.
  • Network Policies (official Kubernetes documentation): namespaceSelector and podSelector in a single from element meaning AND, used in step 6.
  • ALTER TABLE (official PostgreSQL documentation): moving tables with SET SCHEMA, used in phase two of step 7.
  • Anti-Corruption Layer Pattern (Microsoft Azure Architecture Center): a translation layer between subsystems with different semantics, the anti-corruption layer in step 8.
  • DORA's software delivery performance metrics (DORA): deployment frequency, change lead time and failure rate, used to measure results in step 9.

Next

After the split, every service has its own database, but the data does not shrink: the order table keeps growing day by day, queries keep getting slower, and the first fix that comes to mind is usually an index. The next article, “Adding Indexes Safely: Indexing Large Tables Without an Outage”, moves down to the data layer: how to find the index you need from the evidence in EXPLAIN, how to design it, and how to add it safely to a large table that is taking orders.