Library

Volume 1 · Microservices, APIs & Event-Driven Architecture

Notebook
Sign in

Section 10

Service Mesh & Communication Patterns

1,108 words · about 5 min

10.1 What a Service Mesh Solves

Without a service mesh, every service has to implement mTLS, retries, circuit breaking, distributed tracing propagation, and load balancing itself — usually inconsistently, often in application code that has nothing to do with business logic.

Service A [Envoy Sidecar] ──mTLS──► [Envoy Sidecar] Service B

Sidecar (data plane) handles:
- Mutual TLS (service-to-service encryption, cert rotation)
- Load balancing (intelligent, L7-aware — retries, timeouts, outlier detection)
- Circuit breaking and automatic retries
- Distributed tracing (auto-injects/propagates trace headers)
- Traffic policy (canary rollout, shadow/mirrored traffic, fault injection)
- Observability (metrics exported to Prometheus automatically)

Control plane (Istio) configures every sidecar's behavior centrally via CRDs
(VirtualService, DestinationRule, PeerAuthentication, etc.) — application code
never has to know the mesh exists.

Sidecar Pattern (Kubernetes)

┌─────────────────────── Pod ───────────────────────┐
│  ┌─────────────────┐  ┌───────────────────────┐  │
│  │  Main Container  │  │  Sidecar Container    │  │
│  │  (Order API)     │◀→│  (Envoy proxy /       │  │
│  │                   │  │   log collector /     │  │
│  │                   │  │   config refresher)   │  │
│  └─────────────────┘  └───────────────────────┘  │
│           Shared: network namespace, volumes       │
└──────────────────────────────────────────────────┘

The sidecar shares the pod’s network namespace, so it can transparently intercept every inbound/outbound call the main container makes (via iptables redirect in Istio’s case) without any code change in the application.

Istio Architecture

┌────────────────────── Control Plane (istiod) ──────────────────────┐
│  Pilot (config/service discovery) │ Citadel (certs) │ Galley (config)│
└───────────────────────────┬──────────────────────────────────────┘
                             │ pushes config (xDS API)
        ┌────────────────────┼────────────────────┐
        ▼                    ▼                    ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│ Envoy sidecar │   │ Envoy sidecar │   │ Envoy sidecar │
│ + Order svc    │   │ + Payment svc │   │ + Shipping svc │
└───────────────┘   └───────────────┘   └───────────────┘
        Data plane — actual traffic flows here, mTLS between all sidecars

When to use a service mesh:

✅ Use When ❌ Don’t Use When
20+ microservices needing consistent mTLS, retries, circuit breaking Fewer than ~10 services — overhead isn’t justified
Fine-grained traffic management needed (canary, A/B, traffic mirroring) Team lacks Kubernetes/networking expertise to operate it
Distributed tracing needed across all services with zero code change App-level libraries (e.g., Polly) can already cover retry/circuit-breaker needs
Compliance mandates mTLS between all services Latency budget can’t absorb the extra sidecar hop

10.2 Synchronous vs Asynchronous Communication — Tradeoffs

┌─────────────────────────────────────────────────────┐
│                  Synchronous                          │
│  ┌──────────┐  REST/gRPC  ┌──────────┐               │
│  │ Service A │────────────▶│ Service B │               │
│  └──────────┘             └──────────┘                │
│  Pros: simple, immediate response, easy error handling │
│  Cons: temporal coupling, cascading failures,          │
│        B's downtime directly degrades A                │
├─────────────────────────────────────────────────────┤
│                  Asynchronous                         │
│  ┌──────────┐  ┌─────────┐  ┌──────────┐              │
│  │ Service A │─▶│ Message  │─▶│ Service B │              │
│  └──────────┘  │  Broker  │  └──────────┘               │
│                └─────────┘                             │
│  Pros: loose coupling, resilient, scalable, replayable │
│  Cons: eventual consistency, harder debugging,          │
│        more infrastructure to run and monitor           │
└─────────────────────────────────────────────────────┘
Dimension Synchronous (REST/gRPC) Asynchronous (Events/Queue)
Coupling Temporal — caller blocked on callee’s availability None — publisher and consumer decoupled in time
Failure blast radius Cascades (A fails if B is down/slow) Contained — a down consumer just falls behind, doesn’t break the producer
Latency Immediate response Eventual — consumer processes on its own schedule
Consistency model Can be made strongly consistent within the call Eventually consistent by nature
Debugging Straightforward — one request, one trace Requires distributed tracing / correlation IDs across async hops
Best for Queries needing an answer now, validation gates Commands/events where eventual consistency is acceptable

Resilience patterns needed regardless of sync/async choice: circuit breaker, bulkhead, timeout + retry with backoff and jitter.

// Circuit breaker + retry + timeout with Microsoft.Extensions.Http.Resilience (.NET 8+)
builder.Services.AddHttpClient<IOrderApiClient, OrderApiClient>(client =>
{
    client.BaseAddress = new Uri("https://orders-api.internal");
})
.AddStandardResilienceHandler(options =>
{
    options.Retry.MaxRetryAttempts = 3;
    options.Retry.BackoffType = DelayBackoffType.Exponential;
    options.CircuitBreaker.FailureRatio = 0.5;
    options.CircuitBreaker.MinimumThroughput = 5;
    options.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(30);
    options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(10);
});
# Circuit breaker in Python (pybreaker) around an outbound call
import pybreaker
import requests

payment_breaker = pybreaker.CircuitBreaker(fail_max=5, reset_timeout=30)

@payment_breaker
def charge_customer(customer_id, amount):
    resp = requests.post("https://payments.internal/charge",
                          json={"customer_id": customer_id, "amount": amount}, timeout=5)
    resp.raise_for_status()
    return resp.json()

try:
    charge_customer(cust_id, total)
except pybreaker.CircuitBreakerError:
    # Circuit is open — fail fast, return a "payment pending" response instead of hanging
    queue_for_retry(cust_id, total)

Circuit Breaker State Machine

     ┌─────────┐    Failures exceed   ┌────────┐
     │ CLOSED  │───    threshold  ────▶│  OPEN   │
     │(normal) │                       │(reject) │
     └────┬────┘                       └───┬────┘
          ▲                                │
     All good                         Timer expires
          │                                │
     ┌────┴──────────┐                     │
     │  HALF-OPEN    │◀────────────────────┘
     │ (test request)│
     └───────────────┘
       Success → CLOSED
       Failure → OPEN

10.3 Interview Q&A

Q1: Explain the circuit breaker pattern with a real example.

In a payment processing system integrated with a third-party gateway that had occasional 5–30 minute outages, without a circuit breaker the order service kept hanging waiting for a 30-second timeout on every call, saturating the thread pool. I implemented a circuit breaker: closed (normal, tracking failure rate) → after 5 failures in 60 seconds it opens and immediately returns a fallback (“payment pending”) instead of calling the gateway → after a cooldown it half-opens and sends one test request to check recovery. Thread pool saturation dropped from ~100% to under 5% during outages, and order placement stayed functional throughout — users saw a graceful “pending” message instead of timeouts.

Q2: When would you introduce a service mesh, and what’s the tradeoff?

Once the service count crosses roughly 20 and I need consistent mTLS, retries, and circuit breaking applied uniformly without every team reimplementing them, plus fine-grained traffic control (canary rollouts, traffic mirroring) and zero-code-change distributed tracing. The tradeoff is real operational complexity — an extra sidecar hop on every call, a control plane to run and upgrade, and a team that needs genuine Kubernetes/networking depth to operate it safely. Below ~10 services, or without that operational maturity, application-level libraries (Polly, resilience handlers) usually cover the same resilience needs at a fraction of the complexity.

Q3: How do you decide between synchronous and asynchronous communication for a given service interaction?

The deciding question is whether the caller needs the answer to proceed right now. If it’s a user-facing query or a validation gate, synchronous REST/gRPC is simpler and gives immediate feedback — accept the temporal coupling. If the caller can proceed without the side effect being visible everywhere immediately (notifications, downstream processing, analytics, cross-service workflow steps), asynchronous messaging removes the cascading-failure risk and lets each side scale and fail independently. I still add circuit breakers and bulkheads on synchronous paths regardless, since even a “necessary” synchronous call shouldn’t be allowed to take the whole system down when the callee misbehaves.