Sub topic 15
Logging and Measuring Retries and Errors
This chapter assumes you can write the retry loop from earlier chapters and know basic Python logging. Retries hide failures from callers. Without logs and metrics, you cannot tell whether a "working" system is retrying every call three times.
What to Record
Record one event per attempt, not only per request. Each event needs enough fields to answer a later question.
| Field | Why it helps |
|---|---|
| `request_id` | Groups all attempts for one logical call |
| `attempt` | Shows how many tries a call needed |
| `status` or `error_type` | Separates 429s, 5xx errors, and timeouts |
| `delay` | Shows how long you waited before the next try |
| `retry_after` | Shows whether the provider asked for the wait |
| `latency` | Shows slow calls before they become timeouts |
| `model` | Lets you compare models |
Never log prompts, responses, or API keys at the default level. They may contain private data. Log sizes or token counts instead.
Logging Each Attempt
Use structured logs, with key-value fields instead of free text. They are easy to filter and count.
import json
import logging
import random
import time
import uuid
import httpx
logger = logging.getLogger("llm.retry")
logging.basicConfig(level=logging.INFO, format="%(message)s")
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
def log_event(**fields):
logger.info(json.dumps(fields))
def post_logged(client, url, payload, max_attempts=4, base=0.5, cap=30.0):
request_id = str(uuid.uuid4())
for attempt in range(1, max_attempts + 1):
start = time.monotonic()
status, error = None, None
try:
resp = client.post(url, json=payload, timeout=30.0)
status = resp.status_code
if status < 400:
log_event(request_id=request_id, attempt=attempt, status=status,
latency=round(time.monotonic() - start, 3), outcome="ok")
return resp
except httpx.TransportError as exc:
error = type(exc).__name__
latency = round(time.monotonic() - start, 3)
retryable = error is not None or status in RETRYABLE_STATUS
last = attempt == max_attempts
delay = 0.0 if (last or not retryable) else random.uniform(
0, min(cap, base * 2 ** (attempt - 1)))
log_event(request_id=request_id, attempt=attempt, status=status,
error=error, latency=latency, delay=round(delay, 3),
outcome="retry" if delay else "fail")
if not retryable or last:
if error:
raise httpx.TransportError(error)
resp.raise_for_status()
time.sleep(delay)Every attempt writes one line. The final line has outcome set to ok or fail, so you can find calls that ran out of attempts.
Metrics to Track
Logs explain single calls. Metrics show trends. Track these counters and distributions:
- Requests by final outcome (success, failure).
- Attempts per request. A rising average means the provider is degrading, even if few calls fail.
- Errors by status code or exception type.
- Total time spent sleeping in backoff.
- Latency percentiles (p50, p95, p99), not only the average.
The retry rate is the most useful single number. Compute it as retried attempts divided by total attempts.
from collections import Counter
attempts = Counter()
def record(status):
attempts["total"] += 1
if status is None or status in RETRYABLE_STATUS:
attempts["retryable_failures"] += 1
for s in (200, 429, 200, 503, None, 200):
record(s)
rate = attempts["retryable_failures"] / attempts["total"]
print(f"retryable failure rate: {rate:.0%}")In production, send these values to a metrics system such as Prometheus or CloudWatch instead of an in-memory counter.
Alerting
Alert on symptoms, not on single errors. A few 429s are normal. Useful alerts include:
- Retry rate above a threshold, such as 10%, for five minutes.
- Final failure rate above a threshold.
- p95 latency, including backoff time, above your deadline.
Exercise
Your dashboard shows a final failure rate of 0.5%, but your provider bill and latency are both rising. Which metric would you check first, and why?
Show answer
Check attempts per request (or the retry rate). Retries can recover almost every call, so final failures stay low while each call uses several attempts. That raises latency, and token-based billing or rate-limit use can rise too.