The Application Layer and Microservices (System Design #9)
The monolith deployed fine for two years. Now forty engineers commit to one repository, every deploy is a coordinated event, and one team’s memory leak takes down checkout. The instinct is to split it into microservices. But splitting is easy; operating a distributed set of services is what actually costs you — network calls that can fail, data that no longer joins, and debugging that now spans ten logs.
This chapter is about the application layer: what runs behind the load balancer, how monoliths and microservices differ, and how services find each other in a system where instances appear and disappear by the second.
What the application layer does
Everything between the load balancer and the data stores: request validation, authentication, business logic, orchestration of other services, and response shaping. It should be stateless (Chapter 2) so any instance can handle any request, and horizontally scalable so you add instances under load.
Two organizing styles dominate.
- Monolith. One deployable, one codebase, in-process calls. Simple to build, test, and reason about; joins are local; deploys are atomic. It strains when the codebase and team grow — the whole thing deploys together, scales together, and fails together.
- Microservices. Many small deployables, each owning a business capability and its data. Independent deploys and scaling, technology freedom, fault isolation. The costs: network calls, distributed data, eventual consistency, and a lot of operational machinery.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.6cm, minimum height=0.66cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
% monolith
\node[b, fill=blue!10] (m) at (-3.0,0) {one deployable};
\node[font=\small, anchor=north] at (-3.0,-0.65) {monolith};
% microservices
\node[b, fill=green!12] (s1) at (1.0,1.0) {users};
\node[b, fill=green!12] (s2) at (1.0,0) {orders};
\node[b, fill=green!12] (s3) at (1.0,-1.0) {payments};
\node[font=\small, anchor=north] at (1.0,-1.65) {microservices};
\draw[a, <->] (s1) -- (s2); \draw[a, <->] (s2) -- (s3);
\end{tikzpicture}
The decision: when to split
Microservices are an organizational and scaling tool, not a default. Split when you have a reason:
| Signal | Suggests |
|---|---|
| Teams block each other on one deploy pipeline | independent services |
| One capability needs very different scaling | separate the hot path |
| Different data/consistency needs | separate stores and services |
| Compliance boundary (PCI, health data) | isolate the sensitive part |
| A small team, unclear domain | keep the monolith |
The classic mistake is premature decomposition: splitting a young product into a dozen services before the domain is understood. Every boundary you draw wrong is expensive to move. Start with a modular monolith — clear internal boundaries, one deploy — and extract services when a boundary proves stable and the pressure is real.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=2.0cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=green!12] (mono) at (-2.6,0) {modular monolith};
\node[b, fill=orange!16] (extract) at (0,0) {extract hot/odd parts};
\node[b, fill=blue!10] (micro) at (2.8,0) {services where the pressure is};
\draw[a] (mono) -- (extract); \draw[a] (extract) -- (micro);
\end{tikzpicture}
Service discovery: how instances find each other
In a dynamic system, instance IPs change constantly (autoscaling, restarts, deployments). Hard-coding addresses does not work. Service discovery is a registry that answers “which healthy instances of payments exist right now?”
- Client-side discovery. The client asks a registry (Consul, etcd, Eureka) for instances and load-balances itself. Fewer hops, client owns the logic.
- Server-side discovery. The client calls a stable name; a proxy or the platform’s DNS resolves it to an instance (Kubernetes Services, a service mesh). Simpler clients.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.9cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=green!12] (orders) at (-3.2,0) {orders svc};
\node[b, fill=yellow!22] (reg) at (0,0) {registry};
\node[b, fill=orange!16] (p1) at (3.0,1.0) {payments:1};
\node[b, fill=orange!16] (p2) at (3.0,0) {payments:2};
\node[b, fill=gray!12, dashed] (p3) at (3.0,-1.0) {payments:3 (down)};
\draw[a] (orders) -- (reg); \draw[a] (reg) -- (p1); \draw[a] (reg) -- (p2);
\node[font=\rmfamily\small, text=black!60] at (0,-1.1) {register + heartbeat};
\end{tikzpicture}
Instances register on startup and heartbeat; the registry drops ones that stop reporting. Health checks (Chapter 8) ensure only healthy instances are returned. This is the machinery that makes autoscaling invisible to callers.
The API gateway
Rather than expose every service, most systems put an API gateway at the edge. It handles cross-cutting concerns once: authentication, rate limiting, TLS, request routing, response aggregation, and protocol translation. Clients talk to one address; the gateway fans out.
This is the L7 proxy from Chapter 8 taken further. It also becomes a place to enforce policy (quotas, auth) centrally instead of in every service — and a potential bottleneck and single point of failure, so it must be scaled and made redundant like everything else at the edge.
Data across services: the hard part
The moment you split services, you lose database joins. Each service owns its data, and a request that needs data from three services must make three calls (or one aggregated call). This creates the problems that dominate microservice design:
- Distributed transactions. You cannot wrap two services’ writes in one ACID transaction. Use a saga: a sequence of local transactions with compensating actions to undo earlier steps if a later one fails.
- Eventual consistency. Other services read stale copies. Design for it (Chapter 4).
- Partial failure. A network call can time out with unknown outcome. Retries must be idempotent (Chapter 14), and cascading failures require circuit breakers and bulkheads (Chapter 17).
# saga sketch: reserve -> charge -> confirm, with compensation on failure
def place_order(order, inventory, payments):
if not inventory.reserve(order): # step 1
return "out_of_stock"
try:
payments.charge(order) # step 2
except Exception:
inventory.release(order) # compensate step 1
return "payment_failed"
return "confirmed"
The saga pattern trades atomicity for availability: the system is briefly inconsistent between steps, and compensation handles failure. This is the CAP choice from Chapter 3 expressed in code.
Pitfalls
- Premature microservices. Splitting before the domain is understood multiplies operational cost and freezes bad boundaries. Start modular, extract later.
- A shared database across services. It recouples what you just decoupled; a schema change becomes a cross-team event. One owner per datastore.
- Ignoring partial failure. Synchronous service-to-service calls fail and can cascade. Add timeouts, retries with backoff, idempotency, and circuit breakers.
- No service discovery. Hard-coded IPs break the moment autoscaling or a deploy changes addresses. Use a registry or platform DNS.
- Distributed transactions by default. They are slow and fragile across services. Prefer sagas and idempotent steps.
Why is a shared database between microservices an anti-pattern, and what replaces ACID transactions across services?
ASolution
A shared database couples services at the schema level, so any change requires coordinated deploys and every service can break the others’ invariants — undoing the decoupling. Across services, use sagas: a chain of local transactions with compensating actions for rollback, accepting temporary inconsistency.
Next: SQL vs NoSQL and the Data-Store Zoo (System Design #10) — choosing where the bytes actually live.