Skip to content

Microservices, gateways and service discovery

Phase 6 · Distributed systems · 14 min read · 4 Atlas cases linked

What you'll be able to do

  • Decide whether a modular monolith or separate services fit a team's actual needs.
  • Draw service boundaries around data ownership and choose how services communicate.
  • Explain how a gateway, discovery, contracts, and tracing keep a distributed request working.

Start with one deployable system

A monolith is one application deployed as a unit. It can still have clean modules: orders, catalog, and billing can expose narrow interfaces. In a modular monolith, their calls stay in-process and one database transaction can protect changes across modules. This is a sensible default for a small team learning the domain.

A microservice is independently deployed and owns a business capability. Splitting can let teams release separately, scale a hot part, choose suitable technology, and isolate some failures. If every release requires coordinated changes to five services, you have a distributed monolith: the coupling remains, but calls cross a network.

Network calls add latency and partial failure: a remote call can time out after the other service completed the work. Each service needs deployment, configuration, monitoring, and a compatible API; cross-service data changes lose one local transaction. Three sequential calls taking 20 ms each add 60 ms before other work. Splitting is an organizational and operational trade-off, not a quality ranking.

Split when team boundaries, scaling hot spots, or release cadences justify that cost. Measure bottlenecks first. Services owned by one small team can multiply on-call work without creating autonomy.

Draw boundaries around ownership

A bounded context is where business words and rules have one meaning. An Order in checkout concerns payment; an Order in fulfillment concerns delivery. These may become separate services if teams and workflows change independently. Splitting by technical layer, such as queries versus validation, makes almost every request cross a boundary.

Each service owns its data and rules. Others use its API or events, never edit its tables. A shared database lets one team silently break another's assumptions. Separate schemas with enforced access can suffice; separate database servers are not mandatory.

Aim for high cohesion within a service and low coupling between services. Chatty traffic is a warning: ten catalog calls to show one checkout page suggest the boundary or API shape is wrong. One operation returning product summaries may work better.

A dependency cycle is another warning. Orders calls billing, and billing calls orders to finish the same work: following the arrows brings you back to the start. Such a loop increases coupling and makes failures and changes harder to isolate, even if compatible contracts still let each side deploy on its own. Longer loops through three or more services have the same problem and are harder to spot.

Choose communication and consistency

Use synchronous HTTP or gRPC when the caller needs an answer now, such as confirming a price. Budget a timeout, handle unavailability, and decide whether retrying is safe. In a six-service chain, one slow leaf can delay the whole request. See timeouts and retries.

Use asynchronous events when work can happen later: OrderPlaced can trigger analytics. After payment succeeds, OrderPaid can trigger fulfillment. Events avoid waiting but introduce delivery, ordering, and replay concerns; see queues, pub/sub and streams. Event-carried state includes fields consumers need, such as order ID, total, and version, avoiding immediate callbacks. Consumers must handle old or duplicate events.

There is no automatic distributed ACID transaction across owned databases. A saga runs the work as a series of local transactions. If payment fails after checkout recorded an order, mark the order failed or run a compensating cancellation. Meanwhile services may disagree. Eventual consistency means they are expected to converge, which does not happen by itself: retry or reconcile failed compensations. Show a pending state until the payment outcome is known. See distributed transactions and sagas.

Put one entry point at the edge

An API gateway routes external requests, applies authentication and rate limits, and can aggregate responses. Keep business rules in their owning services; a gateway full of domain decisions creates new coupling.

A gateway routes browser requests to the right service, and each service runs several instances.

A backend for frontend (BFF) tailors an edge API to one client, such as a mobile app. An aggregator can return partial results when an optional backend is slow, with an explicit error for that part.

A load balancer distributes traffic among instances. A gateway chooses the destination API and may also balance. A service mesh handles service-to-service traffic policy and telemetry, often through sidecars.

With longest-prefix routing, /api/orders/7 chooses /api/orders rather than /api:

routes = {"/api": "general", "/api/orders": "orders"}
path = "/api/orders/7"
match = max((p for p in routes if path == p or path.startswith(p + "/")), key=len)
print(routes[match], path[len(match):] or "/")  # orders /7

Find healthy instances

Hard-coded IPs fail when instances change. Service discovery maps a stable name to current addresses. In one registry design, instances register and renew leases with heartbeats, deregister on shutdown, and expire when renewals are missed. In orchestrated systems, a controller can update the available endpoints based on instance and readiness state. Health checks can catch a process that is alive but unable to serve, but only for failures their probes cover.

In client-side discovery, the caller looks up instances and picks one. In server-side discovery, a proxy or load balancer picks for it. DNS-based discovery resolves a service name to addresses, but caching affects update speed. A Kubernetes Service is one example of a stable name in front of changing instances; see the Kubernetes documentation.

The registry itself is a dependency. If its copies disagree, callers may see different addresses. Bound client cache age, use timeouts, and refresh after a failed choice. A recent address may work during a registry outage; a cached dead address will not. The lab simulates expiry with an injected clock.

Keep contracts and operations explicit

Each boundary needs a contract for fields, errors, and compatibility. Adding a field is usually easier than removing one a consumer needs. Version incompatible APIs and model endpoints. Consumer-driven contract tests check a provider against consumer expectations before deployment. See API design.

Pass a correlation ID through logs to find one request across processes. A distributed trace records each hop and its latency; see observability. Configure service names and timeouts per environment. Shared libraries can standardize protocol details, but lockstep releases recreate coupling. Sidecars or a mesh move traffic concerns from application code while adding infrastructure.

For AI engineers

For AI engineers

A RAG product may have orchestration/API, model serving, retrieval, and ingestion. Inference may need GPUs while the others often need CPUs; ingestion can run outside the request path. Model weights can change on a different schedule from product code. These are possible boundaries, not a reason to start with twelve services.

If model serving is down, return a controlled failure or limited response without crashing unrelated features. Define model input/output contracts, errors, and versioned endpoints. Trace requests through retrieval and inference; give each hop a timeout so a slow model does not consume the whole budget.

Common mistakes

  • Splitting by technical layer instead of business capability, creating a remote call for every small operation.
  • Letting services share and edit one database schema, so ownership and deployment independence disappear.
  • Building synchronous chains six calls deep without timeouts, circuit breakers, or a plan for partial failure.
  • Starting many services for a three-person team before distinct ownership or scaling needs exist.
  • Changing a response field without versioning or contract tests and assuming every consumer deploys at once.
  • Adding a mesh or gateway while ignoring the cost of operating and observing the services behind it.

Check yourself

A three-person team has one RAG app and no measured scaling hot spot. Should it split retrieval, orchestration, and serving into services now?

Start with a modular monolith unless a distinct workload or release schedule already justifies a boundary. Keep interfaces clear so a later split is possible. Separate GPU serving when its scaling or deployment needs actually differ enough to pay for network and operational costs.

Checkout writes an order and payment later fails. Why is one ordinary database transaction not enough, and what must the product show?

The services own separate data, so one local transaction cannot atomically commit both. A saga can compensate by canceling the order, and a failed compensation must be retried or reconciled. The UI shows pending until the payment outcome is known, then an honest result.

A gateway has /api and /api/orders routes. Where does /api/orders/7 go, and what path reaches the service?

The longer matching prefix wins: the orders service receives /7 after the gateway strips /api/orders. /apix must not match /api because route prefixes end at a path boundary.

A client cached two instance addresses. One instance dies while its registry entry remains visible. What should the client and registry do?

The client should stop selecting the failed address and refresh its cache; the registry should eventually remove the entry through health checks or TTL expiry. A timeout protects the current call while those updates propagate.

Lab

In code/microservices/, start with longest-prefix gateway routing, path rewriting, and clear 404/502 results. Simulate a BFF fan-out that returns partial results when a backend misses its deadline. Then build a tiny service registry with TTL leases and client-side discovery on top of it. Detect dependency cycles that can increase coupling and make failures or changes harder to isolate. Run: cd code/microservices && PYTHONPATH=starter python -m pytest tests -q

Go deeper

See it in the wild

Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.