Architecture

Building Scalable Microservices APIs: Architecture Patterns and Best Practices

How to split a system into services that scale independently: boundaries, stateless design, a database per service, sagas and distributed tracing.

By the APIStack team··Updated ·9 min read

Server racks with bundles of network cables in a data centre

A microservices architecture splits an application into small services that are deployed and scaled separately. Done well, it lets the busy parts of a system grow without the rest and lets teams release without waiting on each other. Done badly, it produces a monolith's coupling with a network in the middle.

This article covers the decisions that determine which outcome you get: where to draw service boundaries, how to keep services horizontally scalable, how to manage data that no longer lives in one database, and how to see what a request did across services. It is for developers who are planning a split or already operating one. How services call each other and handle failed calls is a subject of its own, covered in Microservices communication patterns.

Decide whether microservices fit the problem

Microservices solve two scaling problems. One is load: if search receives a hundred times the traffic of checkout, running them as separate services lets you add capacity to search alone. The other is organisation: when many teams work in one codebase and one release train, separate services let each team ship on its own schedule.

They are paid for with operational complexity. Calls that were function calls become network requests that can fail. A transaction that touched three tables now spans three services. Debugging needs tracing, and every service needs a pipeline, monitoring and an owner. A team that has neither problem is usually better served by a well-structured monolith, which can be scaled by running more copies behind a load balancer. Extracting a service later, when a real bottleneck or ownership problem appears, is easier than merging services that were split too early.

Find service boundaries in the business domain

A service should own one business capability and all of the data behind it. Domain-driven design calls these areas bounded contexts: parts of the business with their own language, rules and data. For an online shop a first division might look like this.

ServiceResponsible forData it owns
AccountsRegistration, sign-in, profiles and preferencesUsers, profiles, sessions
CatalogProduct information, categories, searchProducts, categories, search index
OrdersCreating and tracking orders, coordinating payment and stock reservationOrders, order items, order status

Three checks help test a proposed boundary. Data that changes together in one transaction belongs in one service; if two services must always be updated together, they are one service. A service should have a single owning team, since systems tend to mirror the communication structure of the organisation that builds them, an observation known as Conway's law. And a typical feature should be deliverable by changing one service. A feature that regularly needs coordinated releases across several is a sign of a distributed monolith.

Teams can choose their own languages and tools inside a boundary, but a few things are worth standardising across all services: how they authenticate callers, how they log and trace, and how they are deployed. Without that, each new service multiplies the operational work.

Keep services stateless so they scale horizontally

Scaling a service horizontally means running more identical instances behind a load balancer. That only works if any instance can handle any request, so instances must not keep state in memory or on local disk between requests. Session data goes in a shared store such as Redis or in a signed token, uploaded files go to object storage, and scheduled jobs use a lock or a queue so that ten instances do not each run the nightly task.

With stateless instances, the database usually becomes the limit before the service does. The common remedies, roughly in order of cost, are to cache read-heavy data with an explicit expiry, to send read queries to replicas while accepting that replicas lag slightly behind, and to partition data by a key such as tenant or region. Each one trades some consistency or simplicity for capacity, so apply them to the service that has measured the need.

Work that does not have to finish before the response should leave the request path. Accepting an order and putting "send confirmation", "update analytics" and "generate invoice" on a queue keeps the endpoint fast and lets the queue absorb bursts, with consumers scaled on queue depth. The load is evened out instead of being provisioned for at its peak.

Clients reach the services through an API gateway, which routes each path to the owning service and applies authentication and rate limits once. This keeps the internal layout private: services can be split, merged or moved without clients changing a URL. Gateway design is discussed in Enterprise API architecture.

Give each service its own data

Each service has a private database, or at least a private schema, that no other service reads or writes. Other services get the data through the owning service's API or from events it publishes.

This rule is what makes independent scaling and deployment real. If two services share tables, neither can change its schema without the other, a heavy query from one slows both, and the boundary exists only on a diagram. Private data also lets each service pick a suitable store, for example a relational database for orders and a search engine for the catalog.

The cost is that two things a single database gave you for free now need design. The first is queries that join across services. For a screen that shows an order with product names, the simplest answer is composition: fetch the order, then fetch the products it references in one batched call, and combine them in the caller. When that becomes too slow or too chatty, a service can keep its own read-only copy of the fields it needs from another service, kept current by subscribing to that service's events. The copy is slightly stale, and the owning service remains the source of truth.

The second is transactions that span services, which the next section covers.

Coordinate multi-service changes with sagas

Placing an order may need to create the order, reserve stock and take payment, each in a different service. A database transaction cannot span them, and two-phase commit across services is slow and makes every participant a point of failure. The usual approach is a saga: a sequence of local transactions, each with a compensating action that undoes it if a later step fails.

The function below is an orchestrated saga, in which one service drives the steps. It records a compensation after each step succeeds and, on failure, runs them in reverse.

JavaScript
async function placeOrder(input) {
  const order = await orders.create({ ...input, status: 'pending' })
  const compensations = [() => orders.cancel(order.id)]

  try {
    await inventory.reserve(order.id, order.items)
    compensations.push(() => inventory.release(order.id))

    const payment = await payments.charge(order.id, order.total)
    compensations.push(() => payments.refund(payment.id))

    await orders.confirm(order.id)
    return order
  } catch (err) {
    for (const undo of compensations.reverse()) {
      await undo()
    }
    throw err
  }
}

The example shows the logic, but it keeps the list of compensations in memory. If the process crashes after charging the customer, nothing remembers to refund them. A production saga persists its state after every step, so that it can resume or compensate after a restart, either in a saga table that a recovery job scans or in a workflow engine such as Temporal. A compensation can itself fail, so it must be retried until it succeeds.

Three properties make a saga dependable. Every step and every compensation is idempotent, which is why each call above passes the order ID: a repeated reserve for the same order must not reserve twice. Intermediate states are visible to other requests, since there is no isolation, so the order stays pending until the end and the interface presents it that way. And some steps cannot be undone, such as sending an email or shipping a parcel, so they go last, after everything that can fail.

The alternative to orchestration is choreography, in which there is no coordinator: each service reacts to the previous service's event and publishes its own. It avoids a central component and works for two or three steps. Beyond that the flow is spread across services and hard to follow, and an orchestrator is easier to reason about.

Trace requests across services

When one request passes through several services, the logs of any single service show only a fragment. Three kinds of telemetry together make the system diagnosable. Metrics, meaning request rate, error rate and latency per endpoint along with resource use, show that something is wrong and drive autoscaling and alerts. Structured logs carrying a request or trace ID show what happened inside one service. Traces show the whole path of a request and where its time went.

OpenTelemetry is the vendor-neutral standard for all three. In Node.js, the SDK is started in a file loaded before the application so that it can instrument HTTP, database and messaging libraries automatically. It exports over OTLP, the OpenTelemetry protocol, which collectors and tracing backends including Jaeger accept directly.

JavaScript
// tracing.js: start the service with `node --require ./tracing.js server.js`
const { NodeSDK } = require('@opentelemetry/sdk-node')
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node')
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http')

const sdk = new NodeSDK({
  serviceName: 'order-service',
  traceExporter: new OTLPTraceExporter({ url: 'http://otel-collector:4318/v1/traces' }),
  instrumentations: [getNodeAutoInstrumentations()],
})

sdk.start()
process.on('SIGTERM', () => sdk.shutdown())

Automatic instrumentation creates a span for each incoming and outgoing request and passes the trace context between services in the traceparent header. Add spans of your own around significant business operations so that they appear in the trace with useful attributes.

JavaScript
const { trace, SpanStatusCode } = require('@opentelemetry/api')

const tracer = trace.getTracer('order-service')

function processOrder(order) {
  return tracer.startActiveSpan('process_order', async (span) => {
    span.setAttribute('order.id', order.id)
    span.setAttribute('order.item_count', order.items.length)
    try {
      return await orderProcessor.process(order)
    } catch (err) {
      span.recordException(err)
      span.setStatus({ code: SpanStatusCode.ERROR, message: err.message })
      throw err
    } finally {
      span.end()
    }
  })
}

Keep personal data such as email addresses out of span attributes and logs. Trace a sample of requests in high-traffic services to control cost, but keep the traces of failed and slow requests, since those are the ones that get read.

Summary

  • Adopt microservices to solve a measured load or team-ownership problem; otherwise a well-structured monolith scales further with less effort.
  • Draw boundaries around business capabilities so that a service owns its data, has one team and can deliver most features alone.
  • Keep instances stateless, move deferrable work onto queues, and scale the data layer with caching, replicas and partitioning where measurements call for it.
  • Give each service private data; answer cross-service queries by composition or event-fed read copies, and cross-service changes with sagas whose state is persisted and whose steps are idempotent.
  • Instrument every service with metrics, structured logs and OpenTelemetry traces before you need them.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading