Columns › 3. Splitting into microservices › Part 9
When to Split: Service Boundaries and Decomposition Strategies
什麼時候該拆:邊界與拆分策略
Microservices are not the default answer. Starting from a modular monolith, this article shows how to find boundaries with bounded contexts and data ownership, migrate piece by piece with the strangler fig pattern, and recognise when not to split at all.
In this article
- What this article solves
- Step 1: First, admit the monolith is not the problem
- Step 2: Draw module boundaries inside the monolith
- Step 3: Find the real boundaries with bounded contexts
- Step 4: Data ownership is the real dividing line
- Step 5: Move one small piece at a time with the strangler fig pattern
- Step 6: Know when not to split
- Common pitfalls
- Key takeaways
- Next
In the previous article, “Testing in Go: Table-Driven Tests, httptest and Integration Tests”, we gave the order service a full set of unit and integration tests; by now it is a clearly structured Go program that you can change with confidence. This article answers a question every growing system runs into sooner or later: should it be split into several services? And if so, where should the boundaries be drawn, and how do you split it step by step?
What this article solves
"Microservices" is often treated as a synonym for an architecture upgrade, as if a system should be split once it is big enough. In reality, splitting services is a trade: you replace function calls with network calls, a single database transaction with eventual consistency, and one deployment pipeline with many, and in exchange teams can release independently, services can scale independently, and failures can be isolated to one part. If you have no use for what you get, everything you paid is wasted.
This article is in no hurry to write gRPC or a gateway; first it makes the "judgement" clear:
- Why a modular monolith is recommended first, rather than splitting from the start.
- How to find the real boundaries using bounded contexts and data ownership.
- How to use the strangler fig pattern to move one piece out of the monolith safely, with the ability to roll back at any time.
- In which situations splitting only makes things worse.
We continue with the online shop from the previous articles: at first there is just one order program, which handles ordering, payments and inventory. The goal of this article is to reshape it so that it can be split into three services, order, payment and inventory, and to actually move the first service out.
Step 1: First, admit the monolith is not the problem
Many teams want to split services because "the code keeps getting messier, and changing one place breaks three others". But that is usually a problem of unclear module boundaries, not of the deployment unit being too large. Cut a mess of code into three services and you get three messes, plus three times the network errors.
A monolith has several often underrated advantages:
| Aspect | Monolith | Microservices |
|---|---|---|
| Cost of a call | A function call: nanoseconds, cannot fail | A network call: milliseconds, can time out, can partially fail |
| Data consistency | Guaranteed by a single database transaction | Needs extra design: sagas, outbox, idempotency |
| Refactoring | One-click rename in the IDE, checked by the compiler | Changing an interface means old and new versions must coexist |
| Deployment | One pipeline, one image | Many pipelines, a version compatibility matrix |
| Debugging | One log, one stack trace | Needs distributed tracing to see the whole picture |
| Independent scaling | Can only scale the whole thing together | Can scale just the service under heavy load |
| Team autonomy | Everyone changes the same codebase on the same release cadence | Each team has its own release cadence |
The last two rows on the right of the table are what splitting services really buys you. So the first question to ask is not "is the system big enough", but: is there a part that needs to be released independently, scaled independently, or have its failures isolated? If the answer is no, tidying up the monolith is far better value than splitting it.
Tip: The industry saying "Monolith First" doesn't tell you never to split; it tells you to practise getting the boundaries right inside the monolith first. A boundary drawn wrongly in a monolith is fixed by changing an import; drawn wrongly between microservices, you have to change APIs, databases and deployments.
Step 2: Draw module boundaries inside the monolith
The first step in splitting services is to make the code "look as if" it has already been split, without changing how it is deployed. This is a modular monolith: the same process and the same binary, but each business domain has its own package, and they communicate only through explicit interfaces.
Following the project structure from the earlier articles, we split internal/ by domain:
example.com/shop
├── cmd/
│ └── order/main.go # currently the only binary, wiring up every module
├── internal/
│ ├── order/ # orders: handler.go, service.go, repository.go
│ ├── payment/ # payments: exposes only a Service interface
│ └── inventory/ # inventory: exposes only a Service interface
├── api/proto/ # gRPC contracts go here later (next article)
└── deploy/ # compose and k8s configurationThis structure has three rules, which matter more than the directories themselves:
- Modules may only call each other's public interfaces; they may not import each other's repositories, let alone query each other's tables directly.
- Each module owns its own tables. Only the
ordermodule may write theorderstable, and only theinventorymodule may write thestocktable. Even while they are still in the same database, pretend they aren't. - Wiring happens only in
cmd/. This continues the approach from “Layered Architecture and Dependency Injection in Go”: dependency injection means theordermodule receives an interface, without knowing whether behind it is a struct in the same process or a remote service.
The code below makes the rules concrete. OrderService depends on the InventoryService interface rather than on the inventory tables; when stock is insufficient it returns the sentinel error ErrOutOfStock, which the caller checks with errors.Is, the pattern covered in “Error Handling in Go: Wrapping, Sentinels and Custom Types”:
// Modular monolith: the order module talks to the inventory module only through the inventory.Service interface.
// In a real project they live in internal/order and internal/inventory; here they share one file so it can run on its own.
package main
import (
"context"
"errors"
"fmt"
"sync"
)
// ---- internal/inventory: exposes only this interface and error ----
type InventoryService interface {
Reserve(ctx context.Context, orderID string, items []Item) error
}
var ErrOutOfStock = errors.New("inventory: out of stock")
// inventoryModule owns its own data; other modules may not touch stock directly.
type inventoryModule struct {
mu sync.Mutex
stock map[string]int
}
func (m *inventoryModule) Reserve(ctx context.Context, orderID string, items []Item) error {
if err := ctx.Err(); err != nil {
return err
}
m.mu.Lock()
defer m.mu.Unlock()
for _, it := range items { // check everything first, then deduct together, so we never stop halfway
if m.stock[it.SKU] < it.Qty {
return fmt.Errorf("reserve %s for %s: %w", it.SKU, orderID, ErrOutOfStock)
}
}
for _, it := range items {
m.stock[it.SKU] -= it.Qty
}
return nil
}
// ---- internal/order ----
type Item struct {
SKU string
Qty int
Price int64 // unit price, in cents
}
type Order struct {
ID string
UserID string
Items []Item
Total int64 // in cents, to avoid floating-point errors
Status string
}
const (
StatusPending = "pending"
StatusPaid = "paid"
StatusCancelled = "cancelled"
)
type OrderService struct {
inv InventoryService // depends on the interface, not on inventory's tables
}
func (s *OrderService) PlaceOrder(ctx context.Context, id, userID string, items []Item) (*Order, error) {
if err := s.inv.Reserve(ctx, id, items); err != nil {
return nil, fmt.Errorf("place order %s: %w", id, err)
}
o := &Order{ID: id, UserID: userID, Items: items, Status: StatusPending}
for _, it := range items {
o.Total += it.Price * int64(it.Qty)
}
// Only then write to the orders table (the order module's own data)
return o, nil
}
func main() {
inv := &inventoryModule{stock: map[string]int{"SKU-1": 3}}
orders := &OrderService{inv: inv}
ctx := context.Background()
o, err := orders.PlaceOrder(ctx, "o-1", "u-1", []Item{{SKU: "SKU-1", Qty: 2, Price: 19900}})
fmt.Println(o.Status, o.Total, err) // pending 39800 <nil>
_, err = orders.PlaceOrder(ctx, "o-2", "u-2", []Item{{SKU: "SKU-1", Qty: 2, Price: 19900}})
fmt.Println(err, errors.Is(err, ErrOutOfStock))
}So that it can run on its own, this program puts both modules in one file, but note that their only point of contact is the InventoryService interface and ErrOutOfStock. When inventory one day becomes a separate service, you only need to write a new type implementing the same interface (sending gRPC requests inside), and not a single line of OrderService changes. That is the practical payoff of "practising boundaries inside the monolith first": splitting a service becomes swapping an interface implementation, not rewriting business logic.
Figure: On the left, three modules share one database but each owns its own tables; on the right, after splitting into three services, each service owns its own database and they communicate only through APIs or events.
A practical check: add a rule in CI that forbids internal/order from importing any package under internal/inventory other than the interface. Go's internal directory only restricts imports from "outside the tree"; it cannot restrict imports between sibling modules, so rules like this usually have to be enforced by a lint tool or a short script that scans the output of go list -deps.
Step 3: Find the real boundaries with bounded contexts
How the directories are cut can seem subjective; is there a more objective method? The "bounded context" from domain-driven design (DDD) is currently the most widely used tool. Its core observation is: the same word often means different things in different business contexts.
Take "product" in the shop as an example:
- In the world of orders, a product is an order line: which SKU, how many were bought, and the unit price at the moment of the sale. What matters is "a snapshot at the moment of ordering"; if the product's price changes later, the amount on old orders must not change with it.
- In the world of payments, nobody cares about the product's colour or size, only how much to charge, in which currency, and whether the payment status is
pendingorpaid. - In the world of inventory, a product is an item in the warehouse: which storage location it is in, how much is currently available, and how much is reserved. It doesn't care about the selling price.
If you insist on designing a "universal product model" shared by all three, the model keeps growing, each field matters to only some of the people, and every change needs a meeting of three teams. Conversely, accept that these are three different models, each living in its own context, and the boundaries emerge naturally.
Figure: The same "product" is three different models in the order, payment and inventory contexts, each keeping only the fields it needs.
When looking for boundaries, ask these questions:
| Question | Leans towards one service | Leans towards splitting |
|---|---|---|
| Do these two pieces of data need to change in the same transaction? | Yes, and often | Rarely, or eventual consistency is acceptable |
| When one changes, does the other often have to change too? | Often change together | Each changes on its own |
| Are their load characteristics very different? | Roughly the same | One is read-heavy, the other has sharp peaks |
| Are they owned by the same people? | The same team | Different teams, different release cadences |
| Is their tolerance for failure the same? | The same | When one goes down, the other must keep working |
Between orders and payments, the answers usually lean towards splitting: payments connect to external payment providers, have complex rules and need independent auditing, and when the payment service is temporarily down, users should at least still be able to browse their orders. Orders and "order lines", on the other hand, almost always stay together: they must be created in the same transaction, and splitting them only causes trouble.
Tip: Whether a boundary is well drawn shows in "how frequent and how chatty the calls across it are". If completing one operation takes five or six round trips between two services, the boundary is probably wrong, and part of it should be merged back.
Step 4: Data ownership is the real dividing line
The hardest part of splitting services is never the code; it is the data. A hard rule: every piece of data has exactly one owner, only the owner may write it, and anyone else who wants it asks the owner.
The most common anti-pattern is "split the code but not the database": three services deployed separately, but all connected to the same database, with the order service conveniently JOINing the inventory table directly. The result is that you get all the costs of microservices (network, deployment, versions) and none of the benefits: when the inventory team renames a column, the order service breaks, and the two services still have to be released together. This is usually called a "distributed monolith", the worst combination there is.
Once data ownership is settled, other services can use the data in three ways:
- Synchronous queries: when you need the latest value, call the owner's API. For example, ask
inventorywhether there is enough before placing an order. Simple and direct, but when the owner is down, you are affected too. - Keeping a copy: subscribe to the events the owner emits and keep a read-only copy on your side. For example,
orderkeeps a snapshot of product names and prices to display orders. Reads don't depend on the other service, at the cost of the data lagging slightly behind. - Carrying it in the request: the caller puts the data it needs straight into the request, and the receiver doesn't go back to look it up.
None of these is always right, but one signal deserves attention: if most of a service's features can only be completed by synchronously querying another service, their boundary probably ought to be merged.
Splitting the database also means losing database transactions across services. When placing an order, "create the order + reserve stock + take payment" can no longer be wrapped in a single BEGIN ... COMMIT; that is exactly the problem “Distributed Transactions: Sagas and the Outbox Pattern” deals with later. Before deciding to split, think it through: can this business flow accept eventual consistency such as "create the order first, confirm the payment a little later"? If the business absolutely cannot accept it, the two probably shouldn't be split.
Step 5: Move one small piece at a time with the strangler fig pattern
With the boundaries and the data thought through, next comes how to move. The most dangerous approach is the "big-bang rewrite": stop developing the monolith for six months, start from scratch on a whole set of microservices, then switch over all at once one day. Projects like this often fail because the new system never catches up with the old system's features.
The strangler fig pattern is named after a plant that grows along a host tree and eventually replaces it. It works like this:
- Put a routing layer (a reverse proxy) in front of the monolith. At first, all traffic is passed to the monolith unchanged.
- Pick a feature with a clear boundary and manageable risk, such as payments, and implement it in a new service.
- Change the routing so this small group of paths goes to the new service, while the rest still goes to the monolith.
- Watch for a while; once it is confirmed correct, delete the corresponding code from the monolith; if there is a problem, switch the route back.
- Repeat until only the core of the monolith remains, or it disappears entirely.
The routing layer can be written with the standard library's httputil.ReverseProxy, and with the "method + path" patterns that http.ServeMux supports since Go 1.22, the endpoints that have moved are obvious at a glance:
// The strangler fig routing layer: paths that have moved go to the new service; everything else still goes to the monolith.
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
)
func mustProxy(raw string) *httputil.ReverseProxy {
u, err := url.Parse(raw)
if err != nil {
log.Fatalf("bad upstream %q: %v", raw, err)
}
return httputil.NewSingleHostReverseProxy(u)
}
func env(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
func main() {
monolith := mustProxy(env("MONOLITH_URL", "http://127.0.0.1:9000"))
payment := mustProxy(env("PAYMENT_URL", "http://127.0.0.1:9100"))
mux := http.NewServeMux()
// Endpoints already moved to the payment service (Go 1.22 method + path patterns)
mux.Handle("POST /api/payments", payment)
mux.Handle("GET /api/payments/{id}", payment)
// Switch: if something goes wrong, set PAYMENT_ROLLBACK=1 to send all of it back to the monolith
if os.Getenv("PAYMENT_ROLLBACK") == "1" {
mux = http.NewServeMux()
}
// Everything else goes to the monolith
mux.Handle("/", monolith)
addr := env("ADDR", ":8080")
log.Printf("strangler router listening on %s", addr)
log.Fatal(http.ListenAndServe(addr, mux))
}This program deliberately keeps a "rollback switch": set PAYMENT_ROLLBACK=1 and restart, and all payment paths go back to the monolith. During a migration, being able to roll back quickly matters more than anything. In practice this switch is often a setting that can be changed live, or traffic is ramped up gradually by user percentage (1% first, then 10%, and so on).
Figure: The routing layer sends the payment paths that have moved to the new service and everything else to the monolith as before; if something goes wrong, just change the routing to roll back.
This routing layer later grows into a proper API gateway with authentication, rate limiting and request IDs, the subject of “Building an API Gateway in Go: Routing, Authentication and Rate Limiting”.
Two more things must be planned along with the migration:
- How the data moves: once the new service has its own database, the old data has to be migrated over. A common approach is to first have the monolith also write a copy to the new database on every write (or sync it via events); after the new service goes live, it only reads at first and its results are compared, and the write ownership is handed over only once they are confirmed consistent.
- What to move first: prefer parts with clear boundaries, little coupling to other modules, and a clear need for independence. Payments are often a good choice, because they already have to integrate with external payment providers and their interface is relatively stable; conversely, a module like orders, at the centre of every flow, is usually moved last.
Step 6: Know when not to split
The last and most important step is learning to say no. In the following situations, splitting services usually does more harm than good:
| Situation | Why splitting makes it worse | A better approach |
|---|---|---|
| The team is only a handful of people | Operating many services eats into development time | A modular monolith deployed as several replicas |
| The business is still exploring rapidly | Boundaries will still shift a lot, and cross-service refactoring is expensive | Wait until the boundaries settle before splitting |
| You just want to "scale performance" | A monolith can scale horizontally too | Find the bottleneck first (see “Performance Tuning in Go: pprof and Benchmarks”) |
| Two pieces of data must be strongly consistent | Across services you only get eventual consistency | Keep them in the same service, in the same transaction |
| No automated deployment or observability | When something breaks, you can't find the cause | Build CI/CD, logs, metrics and tracing first |
| The motive is "it looks good on a CV" | The costs are real, the benefits are not | Be honest about the requirements |
Before splitting services, the infrastructure should at least provide: every service built automatically into a container image and deployed, logs that can be searched centrally, basic metrics and alerts, and the ability to trace which services a request passes through. These are the subject of “Observability in Go: Logs, Metrics and Tracing” and the deployment articles in the second half of the series. Without them, when a microservice breaks you will be looking for your keys in the dark.
Remember too that "splitting" is not one-way. If two services later prove to call each other too often, always change together, and need strongly consistent data, merging them back is a perfectly legitimate decision, not a failure.
Common pitfalls
- Splitting services by technical layer: splitting into an "API service", a "business logic service" and a "data access service". Every feature has to pass through three services, and any change has to be released in all three. Split services by business capability, not by technical layer.
- A shared database: splitting the code but not the data. The result is a distributed monolith, with no less coupling at all.
- Splitting too finely: one service per entity (a user service, an address service, a phone service…). Call chains get longer, and latency and failure probability grow with them.
- A shared "common" library that keeps growing: putting domain models into a package everyone shares just ties the services together in another way. Only genuinely generic utilities (such as the log format) should be shared, not business models.
- Synchronous call chains that are too long: A calls B, B calls C, C calls D. If any one of them is slow, the whole chain is slow; the availability of each service multiplies, and overall availability drops noticeably. Whatever can become an asynchronous event should.
- Big-bang cutover: switching every feature to the new system at once, with no way back. Use the strangler fig pattern, one small piece at a time.
- Forgetting data migration and dual-write consistency: the code has moved, but the old data is still in the monolith's tables. Design the migration plan together with the code migration.
Key takeaways
- Microservices are a trade: network calls, eventual consistency and more complex operations in exchange for independent releases, independent scaling and failure isolation. If you can't use those benefits, don't split.
- Start with a modular monolith: packages by business domain, communication only through interfaces, each module owning its own tables, wiring only in
cmd/. - Find boundaries with bounded contexts: the same word is a different model in different contexts; don't chase a universal model.
- Data ownership is the real dividing line: each piece of data has only one owner, and other services get it through synchronous queries, event-fed copies, or by carrying it in requests.
- Migrate incrementally with the strangler fig pattern: put a routing layer in front, move one small group of paths at a time, and always keep the ability to roll back.
- Don't split before you have automated deployment and observability; if you split wrongly, merging back is a legitimate choice too.
Next
The boundaries are drawn, but how does order talk to the newly independent inventory? JSON over HTTP works, but the types easily drift apart, and there is no standard way to do streaming or deadlines. The next article, “gRPC and Protocol Buffers in Go”, pins down the interface between services with a .proto contract and generates type-safe Go code.