Go microservices split one big application into small services that talk to each other over the network. In this post, you will learn what a microservice is, when it helps and when it only adds trouble. Then we will build two tiny services, an order service and an inventory service, and make them handle failures safely.
This lesson builds on Go REST API for beginners and Go HTTP client guide. We also use ideas from Go context for beginners and Go clean architecture. So it helps to read those first.
What Are Go Microservices?
In short, a microservice is a small program that does one job and exposes it through an API. For example, one service handles orders, another handles stock and a third sends emails. Each service has its own code, its own data and its own release cycle.
Think of a food court. Each stall cooks one kind of food, because the stalls do not share a kitchen. When the pizza stall closes for cleaning, the noodle stall keeps serving. Similarly, Go microservices let one part of a product fail or change without stopping the rest.
The opposite style is called a monolith. A monolith is one program that holds every feature. It is simple to start with, so it is often the right first choice. As a result, you should treat microservices as a tool for growth, not as a starting rule.
Why Go Microservices Matter
Go is a popular language for services because it starts fast, uses little memory and builds into one small binary. Besides that, its standard library already includes a strong HTTP server and client. Here is what Go microservices give you.
- Independent releases: a team can deploy the inventory service without touching orders, which lowers the risk of each release.
- Targeted scaling: you run ten copies of a busy service and one copy of a quiet one.
- Fault isolation: a bug in one service does not crash the others.
- Team ownership: each team owns a clear boundary and its own data.
- Technology freedom: services only need to agree on the API, not on the code.
However, these benefits cost something. Every call that used to be a function call is now a network call, and networks fail. Therefore, good Go microservices spend a lot of effort on timeouts, retries and clear errors.
How Go Microservices Work
Each service runs as its own process and listens on its own port. When the order service needs stock information, it sends an HTTP request to the inventory service. Then the inventory service answers with JSON. This is the basic pattern behind every Go microservices system, even a very large one. Then the order service decides what to do with the answer.

Notice that the order service never reads the inventory data directly. In other words, it only talks to the public API. This rule keeps services independent, so each team can move at its own speed. Likewise, the inventory team can change its database later, and the order service will not even notice.
How Services Find Each Other
Before it can call anything, the order service needs the address of the inventory service. In small setups, you pass it as an environment variable, such as INVENTORY_URL. In larger setups, tools such as Kubernetes give each service a stable name. As a result, the address does not change when a copy restarts. Your code stays the same in both cases, because it only reads the URL from the environment.
What to Do When a Call Fails
A network call can fail in four common ways. The table below shows each one, plus a safe response.
| Failure | What you see | Safe response |
|---|---|---|
| Service is down | Connection refused | Return a clear error, retry later |
| Service is slow | No answer in time | Stop waiting with a timeout |
| Bad input | 4xx status code | Do not retry, fix the request |
| Server bug | 5xx status code | Retry a few times, then give up |
Go Microservices vs a Monolith
Neither style is better in every case. The table below compares them side by side.
| Feature | Monolith | Microservices |
|---|---|---|
| Deploying | One unit, all at once | Many small units |
| Calls between parts | Function calls | Network calls |
| Debugging | One log, one process | Many logs, many processes |
| Scaling | Copy the whole app | Copy only the busy part |
| Best for | Small teams, new products | Large teams, clear boundaries |

So when should you use which? Start with a well-organised monolith, then grow from there. Later, split out a service when one team needs to release alone. Also split it out when one part needs very different scaling. In both cases, the reason should be a real problem, not a trend.
Go Microservices Hands-On: Orders and Inventory
Now let’s build a small example. The inventory service answers stock questions, while the order service calls it before accepting an order. Both run in one program here, using httptest.NewServer, so you can test everything in a single file.
Step 1: The Inventory Service
First, the inventory service keeps a map of stock and answers GET /stock/{sku}. It returns 404 when the product is unknown.
func inventoryHandler() http.Handler {
stock := map[string]int{"GO-BOOK": 12, "GO-MUG": 0}
mux := http.NewServeMux()
mux.HandleFunc("GET /stock/{sku}", func(w http.ResponseWriter, r *http.Request) {
qty, ok := stock[r.PathValue("sku")]
if !ok {
http.Error(w, "unknown sku", http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(map[string]int{"quantity": qty})
})
return mux
}
Step 2: The Order Service Client
Next, the order service calls inventory. It sends the caller’s context along, so a cancelled request stops the whole chain. It also wraps errors with %w, which keeps the cause for later checks.
type Orders struct {
inventoryURL string
client *http.Client
}
func (o *Orders) Place(ctx context.Context, sku string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, o.inventoryURL+"/stock/"+sku, nil)
if err != nil {
return "", err
}
resp, err := o.client.Do(req)
if err != nil {
return "", fmt.Errorf("inventory unreachable: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("inventory returned %d", resp.StatusCode)
}
var out struct{ Quantity int }
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return "", err
}
if out.Quantity == 0 {
return "out of stock", nil
}
return fmt.Sprintf("order placed, %d left", out.Quantity-1), nil
}
Let’s look at the key lines. NewRequestWithContext ties the call to the caller’s context, so a cancelled request stops early. The check on StatusCode turns a bad reply into a clear error. This step is the heart of safe Go microservices code. Finally, the stock check is business logic that stays inside the order service.
Step 3: Run Both Services
Then we start the inventory service, create the order service with a 200 millisecond timeout and place three orders. After that, we shut inventory down and try again.
func main() {
inv := httptest.NewServer(inventoryHandler())
orders := &Orders{inventoryURL: inv.URL, client: &http.Client{Timeout: 200 * time.Millisecond}}
for _, sku := range []string{"GO-BOOK", "GO-MUG", "GO-PEN"} {
res, err := orders.Place(context.Background(), sku)
fmt.Printf("%-8s -> %q err=%v\n", sku, res, err)
}
inv.Close() // the inventory service goes down
_, err := orders.Place(context.Background(), "GO-BOOK")
fmt.Println("service down ->", err != nil)
fmt.Println(err)
}
Here is the real output from our run. The port number changes on every run, because the test server picks a free port.
GO-BOOK -> "order placed, 11 left" err=<nil>
GO-MUG -> "out of stock" err=<nil>
GO-PEN -> "" err=inventory returned 404
service down -> true
inventory unreachable: Get "http://127.0.0.1:40905/stock/GO-BOOK": dial tcp 127.0.0.1:40905: connect: connection refused
As you can see, each case produces a different, clear result. The service did not hang or crash when inventory went away. Instead, it returned a useful error that the caller can show or retry. Also, the 404 case is not a network failure, so the code treats it as a normal answer. This difference matters, because you retry network failures but not bad requests.
Common Mistakes with Go Microservices
- Splitting too early: many small services add work before you have the users to justify it. So start with a monolith, and split later when the pain is real.
- No timeouts: the default HTTP client waits forever. Therefore, always set
Timeoutor use a context deadline. - Shared databases: two services that write to one database are tightly coupled. Instead, give each service its own data.
- Chatty calls: ten network calls to build one page are slow. So design APIs that return what the caller needs.
- No tracing or logs: a request that crosses three services is hard to follow. Therefore, pass a request ID through every call.
Best Practices for Go Microservices
- Keep each service small and focused, because one clear job is easier to own and test.
- Version your APIs, since callers upgrade at different times.
- Add health endpoints, so the platform can restart broken copies.
- Use structured logs with a request ID, which makes cross-service debugging possible.
- Shut down gracefully, so running requests finish before a copy stops.
- **Test with
httptest**, because it makes service tests fast and reliable. Also, it needs no real network setup. - Document the API for other teams, since a service is only useful when callers know how to use it.
Practice Task
To practise Go microservices, add a third service called pricing that returns the price of a SKU. Keep it as small as the inventory service. Then make the order service call both services and return a message such as “ordered GO-BOOK for 29.50”.
Hint: call the two services one after the other first, since that is the easiest version. After that, try calling them at the same time with two goroutines and a WaitGroup, and compare the total time.
Official Resources
These pages describe the packages and design ideas used in this lesson, and they are worth a bookmark.
- net/http package documentation
- net/http/httptest package documentation
- Go blog: Go Concurrency Patterns, Context
Quick Recap
- Go microservices are small programs that each do one job and talk over HTTP.
- Start with a monolith, and split a service only when you have a clear reason.
- Every network call can fail, so set timeouts and handle errors.
- Pass the caller’s context so cancellation travels through the chain.
- Keep data private to each service and share only through the API.
- Add health checks, logs with request IDs and graceful shutdown.
What’s Next?
By now, you can build two services that talk to each other, and you know how they fail. Still, a platform needs a way to ask each service if it is alive and ready. So next, we will add health check endpoints.
Next up: Go health checks with liveness and readiness probes


