Service Communication: Making Distributed Calls Survivable

Service Communication: Making Distributed Calls Survivable in Python: Splitting a monolith into services replaces function calls with network calls, and those…

Concept Explanation

Splitting a monolith into services replaces function calls with network calls, and those are not the same thing. A function call either returns or raises. A network call can also hang for thirty seconds, succeed on the server but fail on the way back, or succeed twice.

Every technique in this lesson exists to handle that gap.

Synchronous or Asynchronous?

The first design decision, and the one with the biggest consequences.

Synchronous (HTTP/gRPC)Asynchronous (queue/events)
Caller waitsYesNo
CouplingTight — callee must be upLoose — broker holds the message
FailureImmediate and visibleRetried later, invisibly
Best forReads, anything needing an answer nowEmails, reports, anything slow

A practical rule: if the user is staring at a spinner waiting for the answer, use HTTP. If the work can finish in the next few seconds without anyone watching, use a queue. Sending a welcome email inside the signup request means a slow mail server makes signup slow — and a broken mail server makes signup fail.

The Timeout Is Not Optional

The default timeout in most HTTP clients is none. A hung downstream service will hold your thread forever, and under load that exhausts your connection pool: one slow service takes down every service that calls it. This is a cascading failure, and it is the most common way distributed systems die.

httpx.get(url, timeout=httpx.Timeout(connect=2.0, read=5.0, write=5.0, pool=2.0))

Set a timeout on every single outbound call. Always. There is no exception.

Retries, and When They Are Dangerous

Networks fail transiently, so retrying is right — but only for idempotent operations.

Safe to retryDangerous to retry
GET, PUT, DELETEPOST without an idempotency key
502, 503, 504, connection errors400, 401, 403, 404, 422
Timeouts on readsTimeouts on writes (did it succeed?)

Retry with exponential backoff and jitter. Fixed-interval retries from a thousand clients synchronise into a thundering herd that keeps the recovering service down:

delay = min(base * 2 ** attempt, cap) * random.uniform(0.5, 1.5)

Never retry a 4xx. The request was wrong; sending it again will not make it right.

The Circuit Breaker

Retrying a service that is genuinely down just adds load to something already struggling. A circuit breaker tracks failures and, past a threshold, stops trying:

StateBehaviour
ClosedNormal — requests flow, failures counted
OpenFail instantly without calling. Gives the service room to recover
Half-openAfter a cooldown, let one request through to test

Failing fast is a feature. A 50-millisecond error beats a 30-second timeout, both for the user and for your thread pool.

Message Queues

For async work, a broker (Redis, RabbitMQ, Kafka) holds the message until a worker takes it.

Producer -> [ queue ] -> Consumer

The producer returns immediately. If the consumer is down, messages wait. If it crashes mid-job, the message is redelivered — which means your consumer must be idempotent, because at-least-once delivery is what nearly all brokers actually provide. "Exactly once" is mostly marketing.

Messages that fail repeatedly go to a dead letter queue rather than looping forever.

Correlation IDs

One user request may touch six services. Without a shared id, debugging means grepping six log streams and guessing. Generate an id at the edge, pass it in a header, log it everywhere:

headers = {"X-Request-ID": request_id}

This is the cheapest observability win in distributed systems, and the one most often skipped.


Code Example #1 (Basic)

A resilient HTTP client: timeouts, selective retries, backoff with jitter.

import random
import time
import httpx

RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}


def call_service(
    client: httpx.Client,
    method: str,
    url: str,
    *,
    request_id: str,
    max_attempts: int = 4,
    base_delay: float = 0.4,
    **kwargs,
) -> httpx.Response:
    """One outbound call, with timeouts and backoff. Raises on final failure."""
    headers = {**kwargs.pop("headers", {}), "X-Request-ID": request_id}
    idempotent = method.upper() in {"GET", "HEAD", "PUT", "DELETE"}

    last_error = None
    for attempt in range(max_attempts):
        try:
            response = client.request(method, url, headers=headers, **kwargs)

            if response.status_code < 400:
                return response

            # 4xx (except 408/429) means WE were wrong -- retrying cannot help
            if response.status_code not in RETRYABLE_STATUS:
                response.raise_for_status()

            last_error = httpx.HTTPStatusError(
                f"HTTP {response.status_code}", request=response.request,
                response=response)

            # The server told us how long to wait -- honour it
            retry_after = response.headers.get("Retry-After")
            if retry_after and retry_after.isdigit():
                time.sleep(min(int(retry_after), 30))
                continue

        except (httpx.ConnectError, httpx.ReadTimeout, httpx.PoolTimeout) as exc:
            if not idempotent and isinstance(exc, httpx.ReadTimeout):
                # A write may have SUCCEEDED before the timeout. Retrying could
                # duplicate it -- only safe with an idempotency key.
                raise
            last_error = exc

        if attempt < max_attempts - 1:
            # Exponential backoff with jitter, so clients do not synchronise
            delay = min(base_delay * (2 ** attempt), 8.0) * random.uniform(0.5, 1.5)
            print(f"  attempt {attempt + 1} failed ({type(last_error).__name__}), "
                  f"retrying in {delay:.2f}s")
            time.sleep(delay)

    raise RuntimeError(f"{method} {url} failed after {max_attempts} attempts") from last_error


# --- A shared client: connection pooling and one place for defaults ---
timeout = httpx.Timeout(connect=2.0, read=5.0, write=5.0, pool=2.0)
limits = httpx.Limits(max_connections=100, max_keepalive_connections=20)

with httpx.Client(timeout=timeout, limits=limits,
                  base_url="https://httpbin.org") as client:
    rid = f"req-{random.randint(10000, 99999)}"

    resp = call_service(client, "GET", "/json", request_id=rid)
    print(f"ok: {resp.status_code}, {len(resp.content)} bytes, request_id={rid}")

    try:
        call_service(client, "GET", "/status/404", request_id=rid, max_attempts=3)
    except httpx.HTTPStatusError as exc:
        print(f"404 raised immediately, no retries: {exc.response.status_code}")

The ReadTimeout branch on a non-idempotent request is the subtle one. When a POST times out you genuinely do not know whether the server processed it. Retrying might create a second order. The honest options are to fail, or to send an idempotency key so the retry is safe — never to retry blindly.

Code Example #2 (Intermediate)

A circuit breaker, an async fan-out, and an idempotent queue consumer.

import asyncio
import hashlib
import json
import random
import time
from dataclasses import dataclass, field
from enum import Enum

import httpx


# ==================== CIRCUIT BREAKER ====================
class State(Enum):
    CLOSED = "closed"
    OPEN = "open"
    HALF_OPEN = "half_open"


@dataclass
class CircuitBreaker:
    failure_threshold: int = 5
    recovery_timeout: float = 10.0
    name: str = "downstream"

    state: State = State.CLOSED
    failures: int = 0
    opened_at: float = 0.0

    def _now(self) -> float:
        return time.monotonic()

    def allows_request(self) -> bool:
        if self.state is State.CLOSED:
            return True
        if self.state is State.OPEN:
            if self._now() - self.opened_at >= self.recovery_timeout:
                self.state = State.HALF_OPEN       # let ONE request test the water
                print(f"  [{self.name}] circuit half-open, probing")
                return True
            return False
        return True                                # HALF_OPEN: allow the probe

    def record_success(self) -> None:
        if self.state is State.HALF_OPEN:
            print(f"  [{self.name}] probe succeeded, circuit closed")
        self.state, self.failures = State.CLOSED, 0

    def record_failure(self) -> None:
        self.failures += 1
        if self.state is State.HALF_OPEN or self.failures >= self.failure_threshold:
            self.state, self.opened_at = State.OPEN, self._now()
            print(f"  [{self.name}] circuit OPEN after {self.failures} failures "
                  f"-- failing fast for {self.recovery_timeout}s")


class CircuitOpenError(RuntimeError):
    pass


async def guarded_call(breaker: CircuitBreaker, coro_factory):
    if not breaker.allows_request():
        raise CircuitOpenError(f"{breaker.name} circuit is open")
    try:
        result = await coro_factory()
    except Exception:
        breaker.record_failure()
        raise
    breaker.record_success()
    return result


# ==================== ASYNC FAN-OUT ====================
async def fetch_profile(client, user_id, rid):
    await asyncio.sleep(0.15)
    return {"id": user_id, "name": f"User {user_id}"}


async def fetch_orders(client, user_id, rid):
    await asyncio.sleep(0.30)
    return [{"id": 1, "total": 42.0}, {"id": 2, "total": 19.5}]


async def fetch_recommendations(client, user_id, rid):
    await asyncio.sleep(0.90)                      # the slow, optional one
    raise httpx.ReadTimeout("recommendation service is slow")


async def build_dashboard(user_id: int, request_id: str) -> dict:
    """Three downstream calls in parallel; degrade rather than fail."""
    breakers = {name: CircuitBreaker(name=name)
                for name in ("profile", "orders", "recs")}

    async with httpx.AsyncClient(timeout=httpx.Timeout(2.0)) as client:
        started = time.perf_counter()

        results = await asyncio.gather(
            guarded_call(breakers["profile"],
                         lambda: fetch_profile(client, user_id, request_id)),
            guarded_call(breakers["orders"],
                         lambda: fetch_orders(client, user_id, request_id)),
            guarded_call(breakers["recs"],
                         lambda: fetch_recommendations(client, user_id, request_id)),
            return_exceptions=True,                # one failure must not kill the rest
        )
        elapsed = time.perf_counter() - started

    profile, orders, recs = results

    # Essential data failing is fatal; optional data failing is not
    if isinstance(profile, Exception):
        raise RuntimeError("profile service unavailable") from profile

    return {
        "profile": profile,
        "orders": orders if not isinstance(orders, Exception) else [],
        "recommendations": [] if isinstance(recs, Exception) else recs,
        "degraded": [n for n, r in zip(("profile", "orders", "recs"), results)
                     if isinstance(r, Exception)],
        "elapsed_ms": round(elapsed * 1000),
    }


# ==================== IDEMPOTENT CONSUMER ====================
@dataclass
class Queue:
    """A toy broker with at-least-once delivery and a dead letter queue."""
    messages: list = field(default_factory=list)
    dead_letters: list = field(default_factory=list)

    def publish(self, body: dict) -> None:
        self.messages.append({"body": body, "attempts": 0})

    def consume(self, handler, max_attempts: int = 3) -> None:
        while self.messages:
            msg = self.messages.pop(0)
            msg["attempts"] += 1
            try:
                handler(msg["body"])
            except Exception as exc:
                if msg["attempts"] >= max_attempts:
                    print(f"  -> dead letter after {msg['attempts']} attempts: {exc}")
                    self.dead_letters.append(msg)
                else:
                    print(f"  -> retry {msg['attempts']}/{max_attempts}: {exc}")
                    self.messages.append(msg)      # requeue


_processed: set[str] = set()          # in production: Redis or a database table


def message_key(body: dict) -> str:
    return hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()[:12]


def send_welcome_email(body: dict) -> None:
    """At-least-once delivery means this WILL be called twice. Handle it."""
    key = message_key(body)
    if key in _processed:
        print(f"  already sent {key} -- skipping duplicate")
        return

    if random.random() < 0.4:                      # simulate a flaky mail server
        raise RuntimeError("SMTP connection refused")

    print(f"  sent welcome email to {body['email']} (key {key})")
    _processed.add(key)                            # mark AFTER success, not before


async def main():
    rid = "req-a91f3c"
    print("=== Async fan-out with graceful degradation ===")
    dashboard = await build_dashboard(user_id=42, request_id=rid)
    print(f"  orders: {len(dashboard['orders'])}, "
          f"recs: {len(dashboard['recommendations'])}")
    print(f"  degraded services: {dashboard['degraded']}")
    print(f"  total {dashboard['elapsed_ms']}ms "
          f"(sequential would have been ~1350ms)\n")

    print("=== Circuit breaker under sustained failure ===")
    breaker = CircuitBreaker(failure_threshold=3, recovery_timeout=1.0, name="payments")

    async def always_fails():
        raise httpx.ConnectError("connection refused")

    for i in range(6):
        try:
            await guarded_call(breaker, always_fails)
        except CircuitOpenError:
            print(f"  call {i + 1}: rejected instantly, no network attempt")
        except httpx.ConnectError:
            print(f"  call {i + 1}: attempted and failed")
    print()

    print("=== Idempotent consumer with retries and a dead letter queue ===")
    random.seed(3)
    queue = Queue()
    for email in ("ada@example.com", "grace@example.com"):
        queue.publish({"type": "user.created", "email": email})
        queue.publish({"type": "user.created", "email": email})   # duplicate!

    queue.consume(send_welcome_email)
    print(f"  unique emails sent: {len(_processed)} (4 messages, 2 recipients)")
    print(f"  dead letters: {len(queue.dead_letters)}")


asyncio.run(main())

Three ideas here carry the lesson. return_exceptions=True turns asyncio.gather from all-or-nothing into partial success — a dashboard missing its recommendations is far better than a 500. The circuit breaker's later calls cost nothing because no network attempt is made at all. And send_welcome_email marking the key after success, not before, is what makes at-least-once delivery safe: crash mid-send and the message is redelivered and actually retried, rather than being marked done and silently lost.


Common Mistakes

  1. No timeout on an HTTP call: the default is infinite. One hung dependency exhausts your thread pool and takes down your service.
  2. Retrying a non-idempotent POST: creates duplicate orders and double charges. Use an idempotency key or do not retry.
  3. Retrying 4xx responses: the request was malformed or unauthorised. Repeating it changes nothing and wastes the downstream service's capacity.
  4. Fixed-interval retries: a thousand clients retrying every second in lockstep is a denial-of-service attack on your own infrastructure. Add jitter.
  5. Creating a new HTTP client per request: throws away connection pooling and TLS session reuse. Create one client and share it.
  6. Assuming exactly-once delivery: brokers give at-least-once. Every consumer must be idempotent.
  7. No dead letter queue: a poison message loops forever, blocking everything behind it.
  8. Synchronous calls for slow work: sending email inside the signup request couples signup's latency and availability to your mail provider's.
  9. No correlation id: debugging a request across six services becomes guesswork.
  10. Sequential awaits when calls are independent: three 300 ms calls in a row is 900 ms; asyncio.gather makes it 300 ms.
  11. Letting one optional dependency fail the whole response: use return_exceptions=True and degrade.
  12. Marking a message processed before doing the work: a crash then loses it permanently. Mark after success.

Best Practices

  • Set an explicit timeout on every outbound call — connect, read, write, and pool separately.
  • Retry only idempotent operations, with exponential backoff and jitter, and honour Retry-After.
  • Wrap every downstream dependency in a circuit breaker so failure is fast rather than slow.
  • Reuse one httpx.Client for connection pooling; create it once at startup.
  • Generate a correlation id at the edge and propagate it in X-Request-ID through every hop.
  • Prefer async messaging for anything the user is not waiting on: email, reports, webhooks, indexing.
  • Make every consumer idempotent with a deduplication key, and mark completion only after success.
  • Configure a dead letter queue with a retry cap on every subscription.
  • Degrade gracefully: classify each dependency as essential or optional, and return partial data when an optional one fails.
  • Use asyncio.gather for independent calls and return_exceptions=True so one failure does not cancel the rest.
  • Log every retry, circuit state change, and dead letter — these are the signals that tell you a dependency is degrading before users notice.
  • Test the failure paths: kill a dependency in staging and confirm your service degrades instead of hanging.

Practice Exercises

  1. The Timeout Proof: Write a client that calls a deliberately slow endpoint (https://httpbin.org/delay/10) with no timeout, then with a 2-second read timeout. Time both and explain what the first one would do to a server under load.
  2. The Breaker: Implement a circuit breaker with a threshold of 3 and a 5-second recovery, point it at a function that always fails, and print the state before each of ten calls. Confirm the calls after opening return instantly.
  3. The Duplicate Handler: Build a queue consumer that receives the same message three times. Add a deduplication key so the side effect happens exactly once, then move the "mark as processed" line to before the work and describe what breaks.