Prerequisites and platform: automation, observability, sidecars and meshes
Check the operational prerequisites before a split, see how discovery, sidecars and ambassadors take network concerns out of application code, run a small sidecar that retries and times out calls, and decide between libraries, a sidecar mesh and an ambient mesh.
Contentsand lesson path
On this page
- Why it matters
- Prerequisites before the first split
- Discovery, sidecars and ambassadors
- Service meshes: sidecar and ambient data planes
- Library, sidecar or mesh: choosing a home
- Check your understanding
- Apply it
- Review prompt
Lessons of Microservices Architecture
- What microservices buy and what they cost Concept · 20 min
- Prerequisites and platform: automation, observability, sidecars and meshes Concept · 20 min
- Decomposing a retailer by capability and bounded context Worked example · 30 min
- Database per service and querying across services Concept · 25 min
- Sync versus async calls, gateways, BFFs and micro-frontends Concept · 25 min
- Service decomposition check Knowledge check · 10 questions
What you will learn
- Decide whether microservices are justified for a context, using team structure, deployment-independence needs and operational prerequisites.
- Decide where cross-cutting service-to-service concerns (discovery, retries, mTLS, telemetry) live, in libraries, sidecars or a service mesh, and when a mesh's operational cost is justified.
Prerequisites: Strategic Domain-Driven Design
01. Why it matters
Suppose a shop has just split into fourteen services. At 1 a.m., 2% of checkouts start failing. Each service writes its own log on its own machine, with no shared request ID, two services were deployed by hand that evening, and nobody is sure which team owns the payment adapter. Finding the cause means guessing across fourteen sets of logs.
Nothing here is a bug in one service. The split multiplied the operational work, and every incident now crosses service boundaries. This lesson covers what must exist before the split, and where cross-cutting network concerns should live: retries, timeouts, encryption between services, telemetry and finding other services.
02. Prerequisites before the first split
The price of distribution listed this operational maturity as one input to choosing a style. Martin Fowler's 2014 baseline turns it into a gate before the first split, and the reason for each item is the multiplier per service.
- Rapid provisioning and automated deployment. Each service needs somewhere to run, provisioned in hours, and a pipeline that tests, deploys and rolls it back. Ten services released weekly by hand means about forty manual releases a month, and manual steps drift.
- Monitoring and tracing. Technical signals such as error counts and availability per service, and business signals such as a sudden drop in orders. Beyond a handful of services you also need to follow one business transaction through every service it touches, which is what one ID across all three signals and distributed tracing provide.
- Ownership and on-call. Each service has one owning team that is paged when it breaks and can deploy a fix. Fowler frames this as close collaboration between development and operations; without it, incidents wait for hand-offs.
With one deployable you can survive a manual step or a missing dashboard; with twenty services the same gap appears twenty times, at 1 a.m.
03. Discovery, sidecars and ambassadors
Instances start, stop and move, so callers cannot keep fixed addresses. Service discovery keeps a current list of healthy instances behind a stable name: on Kubernetes, a Service gives a group of Pods one name and the platform updates its endpoints as Pods change (desired state and Services). Where the lookup happens is covered in discovery and health checks; for most teams it is a platform feature, not their code.
Retries, timeouts, encryption and telemetry need code on every call. The first home is a library in each service: simple and fast, but needed for every language, and a policy change means redeploying every service.
The sidecar pattern moves that code into a helper process deployed next to each instance, sharing its life cycle. The application talks plain HTTP to its sidecar and the sidecar applies the policy, so one implementation serves every language. On Kubernetes a native sidecar is an init container with restartPolicy: Always, which starts before the app and keeps running (on by default since v1.29, stable since v1.33). Before that, a proxy was an ordinary second container, so a Job's pod could not complete while its proxy kept running; Kubernetes documents that a native sidecar does not stop a Job from completing once the main container has finished. An ambassador is a sidecar specialised for outbound calls, useful when you cannot change an old application. Both add a hop per call and resources per instance.
The script below plays all three roles on one machine with Python 3.12 and the standard library: a flaky inventory service, a sidecar with a POLICY (300 ms timeout, one retry for GET only), and an app with no retry or timeout code of its own. It uses ports 18611 and 18612.
"""sidecar_demo.py: an app, its sidecar proxy and a flaky inventory service.
The app has no retry, timeout or tracing code. It sends plain HTTP to the
sidecar on localhost; the sidecar applies POLICY to every call it forwards.
"""
import itertools
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
INVENTORY, SIDECAR = 18611, 18612
POLICY = {"timeout_s": 0.3, "retries": 1, "retry_methods": {"GET"}}
calls = itertools.count(1) # every request that reaches the inventory service
request_ids = itertools.count(1)
FLAKY = {"/stock/lamp", "/reserve/tent"} # these fail once per request id
seen: set[str] = set()
direct = urllib.request.build_opener(urllib.request.ProxyHandler({})) # no proxy
class Quiet(BaseHTTPRequestHandler):
def log_message(self, *args) -> None:
pass
def send(self, status: int, body: bytes) -> None:
try:
self.send_response(status)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError):
pass # the caller gave up waiting: nobody is left to read the reply
class Inventory(Quiet):
def answer(self) -> None:
n, rid = next(calls), self.headers.get("x-request-id", "none")
if self.path.startswith("/slow"):
time.sleep(1.0) # a stuck dependency
status = 200
if self.path in FLAKY and rid not in seen: # a brief, one-off failure
seen.add(rid)
status = 503
self.send(status, f"call {n} saw {rid}".encode())
do_GET = do_POST = answer
class Sidecar(Quiet):
def forward(self) -> None:
rid = self.headers.get("x-request-id") or f"req-{next(request_ids)}"
retries = POLICY["retries"] if self.command in POLICY["retry_methods"] else 0
for attempt in range(1, retries + 2):
url = f"http://127.0.0.1:{INVENTORY}{self.path}"
req = urllib.request.Request(url, method=self.command, data=b"",
headers={"x-request-id": rid})
try:
with direct.open(req, timeout=POLICY["timeout_s"]) as resp:
status, body = resp.status, resp.read()
except urllib.error.HTTPError as err:
status, body = err.code, err.read()
except (TimeoutError, urllib.error.URLError):
status, body = 504, b"sidecar: upstream timed out"
if status < 500:
break
print(f" sidecar {rid} {self.command:4} {self.path:13} {status} "
f"after {attempt} attempt(s)")
self.send(status, body)
do_GET = do_POST = forward
servers = [ThreadingHTTPServer(("127.0.0.1", port), handler)
for port, handler in [(INVENTORY, Inventory), (SIDECAR, Sidecar)]]
for server in servers:
threading.Thread(target=server.serve_forever, daemon=True).start()
for method, path in [("GET", "/stock/tent"), ("GET", "/stock/stove"),
("GET", "/stock/lamp"), ("POST", "/reserve/lamp"),
("POST", "/reserve/tent"), ("GET", "/slow/report")]:
req = urllib.request.Request(f"http://127.0.0.1:{SIDECAR}{path}",
method=method, data=b"")
try:
with direct.open(req, timeout=5) as resp:
status, body = resp.status, resp.read()
except urllib.error.HTTPError as err:
status, body = err.code, err.read()
print(f"app got {status}: {body.decode()}")
for server in servers:
server.shutdown()python3 sidecar_demo.py sidecar req-1 GET /stock/tent 200 after 1 attempt(s)
app got 200: call 1 saw req-1
sidecar req-2 GET /stock/stove 200 after 1 attempt(s)
app got 200: call 2 saw req-2
sidecar req-3 GET /stock/lamp 200 after 2 attempt(s)
app got 200: call 4 saw req-3
sidecar req-4 POST /reserve/lamp 200 after 1 attempt(s)
app got 200: call 5 saw req-4
sidecar req-5 POST /reserve/tent 503 after 1 attempt(s)
app got 503: call 6 saw req-5
sidecar req-6 GET /slow/report 504 after 2 attempt(s)
app got 504: sidecar: upstream timed outThe app asked six times and never retried anything. The sidecar retried the GET for the lamp after its brief failure, with the same request ID, so the inventory service could tell that call 4 was a repeat of call 3. It did not retry the failed POST, because the policy cannot know whether reserving stock twice is harmless. And it gave up on the stuck report after two 300 ms attempts and answered 504 itself. Because it handles only the app's outgoing calls, this sidecar is playing the ambassador role.
Now predict: set "retries": 0 in POLICY and run again. Which calls does the app now see fail?
sidecar req-1 GET /stock/tent 200 after 1 attempt(s)
app got 200: call 1 saw req-1
sidecar req-2 GET /stock/stove 200 after 1 attempt(s)
app got 200: call 2 saw req-2
sidecar req-3 GET /stock/lamp 503 after 1 attempt(s)
app got 503: call 3 saw req-3
sidecar req-4 POST /reserve/lamp 200 after 1 attempt(s)
app got 200: call 4 saw req-4
sidecar req-5 POST /reserve/tent 503 after 1 attempt(s)
app got 503: call 5 saw req-5
sidecar req-6 GET /slow/report 504 after 1 attempt(s)
app got 504: sidecar: upstream timed outThe lamp lookup now fails as well, and the policy changed without touching the app. This is a simplified sidecar: in a real pod it is a separate container sharing the network namespace, a mesh usually redirects traffic through it with network rules, and mTLS can encrypt the traffic between proxies; here everything runs unencrypted in one process.
04. Service meshes: sidecar and ambient data planes
A service mesh is a fleet of such proxies, the data plane, plus a control plane that configures them all. Typical features are mutual TLS (mTLS), where both sides of every call present certificates, giving encryption and a verified workload identity, though not user authorisation (private CA and mTLS); retries and timeouts per route; traffic shifting, such as sending 5% of requests to a new version during a canary (rollout strategies); and request telemetry.
In sidecar mode every pod gets its own proxy: Envoy in Istio, and in Linkerd its own Rust micro-proxy, a native sidecar by default since Linkerd 2.20 (June 2026). In Istio's ambient mode, a per-node proxy called ztunnel handles mTLS, layer-4 authorisation and connection telemetry for every pod on its node, and optional Envoy waypoint proxies add HTTP-level features such as retries, routing and request metrics. Ambient mode became generally available in Istio 1.24 (November 2024).
Istio's comparison page (v1.32 documentation, read in November 2026) states the trade-offs. Sidecars cost resources per pod, and joining the mesh means restarting pods to inject them; ambient needs no restart. Sidecars give each workload its own keys, while a ztunnel holds the keys of every pod on its node. The page lists ambient as stable for single-cluster use. We did not run a mesh for this lesson; check current release notes before choosing.
A mesh does not remove all code from the application.
- Trace headers. A proxy sees an inbound request and, later, outbound calls, but cannot tell which belong together. Istio's documentation asks every application to copy tracing headers from each incoming request onto the calls it triggers, and Envoy's documentation says it cannot forward
x-request-idby itself. A thin library is still needed. - Retry safety. Only the owning team knows whether an operation is safe to repeat. The demo's POST rule is that knowledge written down.
- Defaults that stack. Istio's documented default for HTTP routes with no retry policy is two retries on connection failures and a few similar errors. If client libraries also retry, attempts multiply at every hop, so give each concern one home, as timeouts and retries explains.
05. Library, sidecar or mesh: choosing a home
Choose by the conditions, not by fashion:
- One or two languages, a few services, a small platform team: platform discovery plus one shared library per language for retries, timeouts and telemetry. It is cheap, debuggable and fast; the cost is a coordinated library upgrade when policy changes.
- Many languages, policy owned by a platform team, uniform mTLS required: a mesh pays off, because one configuration reaches every service. If you mostly need encryption and layer-4 policy, an ambient data plane avoids a proxy per pod.
- Frequent canaries and per-route traffic rules: a mesh or a programmable gateway, with layer-7 proxies where those rules apply.
A mesh is not worth it when nobody can own its upgrades, certificates and debugging: it adds a control plane, a hop per call and new failure modes. What if the company grows from one language to four and auditors start requiring encrypted service-to-service traffic? The library approach then needs four implementations kept in step, and the analysis tips towards a mesh.
06. Check your understanding
07. Apply it
For your online grocery (or your own context), write the library-versus-mesh paragraph of the practice deliverable.
- List the languages, the expected number of services and who would run the platform.
- For retries, timeouts, mTLS, telemetry and discovery, name the home of each and why it lives there; give each concern exactly one home.
- Name one change, such as a new language or an audit requirement, that would make you revisit the decision.
08. Review prompt
Without looking back: name the three prerequisites and what goes wrong without each. Explain how a sidecar applies a retry policy without changes to the application, and why it did not retry the POST in the demo. Compare sidecar and ambient data planes by where the proxies run, what each layer handles and one trade-off. Name two things a mesh cannot do for the application.
References
- Microservice Prerequisites (Martin Fowler, 2014)
- Sidecar pattern (Azure Architecture Center)
- Ambassador pattern (Azure Architecture Center)
- Sidecar containers (Kubernetes documentation)
- Service (Kubernetes documentation)
- Ambient mode overview (Istio documentation)
- Sidecar or ambient? (Istio documentation)
- Istio's ambient mode reaches general availability in v1.24 (Istio blog, 2024)
- Virtual Service: HTTP retry defaults (Istio documentation)
- Distributed tracing overview: header propagation (Istio documentation)
- HTTP header manipulation: x-request-id (Envoy documentation)
- Architecture (Linkerd documentation)
- Microservices pattern: service mesh (microservices.io)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.