Sub topic 15
Logging and Measuring Retries and Errors
Retries hide failures. A call that succeeds on the third attempt looks the same to your users as one that succeeds on the first, so a service can be degrading for hours with no visible symptom. This chapter shows how to record each attempt, which numbers to track, and how to tell a healthy retry rate from a warning sign.
This chapter assumes you have a working retry loop like the one built in the earlier chapters on backoff, jitter, and retry limits. You should also know basic Python logging and what a counter and a percentile are.
What to record for each attempt
Log every attempt, not only the final result. A single log line per call cannot show that the first two attempts returned 503 and the third succeeded.
Each attempt record should answer four questions: which call, which attempt, what happened, and what the client did next.
| Field | Why it helps |
|---|---|
| `call_id` | Groups all attempts that belong to one logical call. |
| `attempt` | Shows how deep into the retry sequence the failure happened. |
| `outcome` | A short class such as `ok`, `http_429`, `http_503`, or `ReadTimeout`. |
| `latency_ms` | Separates slow failures (timeouts) from fast ones (rate limits). |
| `will_retry` | Distinguishes a retried failure from a surfaced one. |
| `delay_s` | The sleep chosen, after jitter and any Retry-After override. |
| `retry_after` | The server's requested wait, so you can check you honored it. |
| `provider_request_id` | Lets the provider's support trace the call. The header name varies, for example `x-request-id`. |
| `model` | Failure rates often differ per model. |
Use structured logs, with one JSON object per line. Plain-text messages such as "retrying..." are hard to filter and aggregate later.
An instrumented retry loop
The script below adds logging and counters to the retry loop from the earlier chapter. It uses httpx.MockTransport to return scripted responses, so it runs offline.
import json
import logging
import random
import time
import uuid
from collections import Counter
import httpx
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
logger = logging.getLogger("llm.retries")
logging.basicConfig(level=logging.INFO, format="%(message)s")
metrics = Counter()
def log_event(**fields):
logger.info(json.dumps(fields, sort_keys=True))
def classify(resp, error):
if error is not None:
return type(error).__name__
if resp.status_code < 400:
return "ok"
return f"http_{resp.status_code}"
def parse_retry_after(value):
try:
return max(0.0, float(value)) if value is not None else None
except ValueError:
return None
def post_with_retries(client, url, payload, max_attempts=5, base=0.5, cap=30.0):
call_id = uuid.uuid4().hex[:8]
call_start = time.monotonic()
for attempt in range(1, max_attempts + 1):
resp, error = None, None
t0 = time.monotonic()
try:
resp = client.post(url, json=payload, timeout=30.0)
except httpx.TransportError as exc:
error = exc
latency_ms = round((time.monotonic() - t0) * 1000)
outcome = classify(resp, error)
metrics[f"attempts.{outcome}"] += 1
request_id = resp.headers.get("x-request-id") if resp is not None else None
if resp is not None and resp.status_code < 400:
metrics["calls.success"] += 1
log_event(event="attempt", call_id=call_id, attempt=attempt,
outcome=outcome, latency_ms=latency_ms, will_retry=False,
request_id=request_id)
return resp
retryable = error is not None or resp.status_code in RETRYABLE_STATUS
will_retry = retryable and attempt < max_attempts
if not will_retry:
metrics["calls.failed"] += 1
reason = "permanent" if not retryable else "exhausted"
log_event(event="attempt", call_id=call_id, attempt=attempt,
outcome=outcome, latency_ms=latency_ms, will_retry=False,
final_reason=reason, request_id=request_id,
total_ms=round((time.monotonic() - call_start) * 1000))
if error is not None:
raise error
resp.raise_for_status()
delay = random.uniform(0, min(cap, base * 2 ** (attempt - 1)))
retry_after = None
if resp is not None:
retry_after = parse_retry_after(resp.headers.get("retry-after"))
if retry_after is not None:
delay = max(delay, min(retry_after, cap))
metrics["retries.total"] += 1
metrics["retry_wait_ms"] += round(delay * 1000)
log_event(event="attempt", call_id=call_id, attempt=attempt,
outcome=outcome, latency_ms=latency_ms, will_retry=True,
delay_s=round(delay, 3), retry_after=retry_after,
request_id=request_id)
time.sleep(delay)
scripted = iter([
httpx.Response(503),
httpx.Response(429, headers={"retry-after": "0.1"}),
httpx.Response(200, json={"ok": True}),
])
client = httpx.Client(transport=httpx.MockTransport(lambda request: next(scripted)))
post_with_retries(client, "https://api.example.test/v1/chat", {"x": 1}, base=0.01)
print(dict(metrics))The output has three JSON lines for one call_id: a 503 with a short delay, a 429 whose delay is at least 0.1 seconds, and a success. The final counter dictionary shows two retries and one successful call.
Notice what the loop records at the end of a failed call. The final_reason field separates permanent failures, which are usually bugs in your request, from exhausted failures, which suggest the provider is unhealthy. These two causes need different responses, so they should not share a single "failed" bucket.
Metrics worth tracking
Logs explain individual calls. Metrics tell you whether the system as a whole is healthy. Start with a small set.
- Attempts by outcome. A count labeled with
ok,http_429,http_503,ReadTimeout, and so on. A rising share of 429s points to a throttling problem on your side. A rising share of 5xx points to the provider. - Calls by final result. Success, permanent failure, and exhausted failure. This is the number your users feel.
- Retry amplification. Total attempts divided by total calls. A value of 1.02 means almost every call works the first time. A value of 2.5 means you are sending more than double the traffic you intended, which can make a rate-limit problem worse.
- Call latency and attempt latency, as separate percentiles. Attempt latency shows how fast the provider answers. Call latency includes backoff sleeps and is what your users wait for. Track p50, p95, and p99, because averages hide the slow tail that retries create.
- Time spent waiting. The sum of backoff delays. It shows how much latency retries add.
- Rate-limit headroom. Many providers return headers with remaining request and token counts. Names differ by provider, so check the documentation. Logging them lets you see a limit approaching before the first 429.
- Circuit breaker state and fallback use. If you use them, count the times the breaker opens and how many answers come from a fallback.
A short function turns the counters into the headline ratios:
from collections import Counter
def summarize(m: Counter) -> dict:
calls = m["calls.success"] + m["calls.failed"]
attempts = sum(v for k, v in m.items() if k.startswith("attempts."))
rate_limited = m["attempts.http_429"]
return {
"calls": calls,
"failure_rate": round(m["calls.failed"] / calls, 3) if calls else 0.0,
"amplification": round(attempts / calls, 2) if calls else 0.0,
"rate_limited_share": round(rate_limited / attempts, 3) if attempts else 0.0,
}
sample = Counter({
"calls.success": 96,
"calls.failed": 4,
"attempts.ok": 96,
"attempts.http_429": 18,
"attempts.http_503": 6,
"attempts.http_400": 2,
})
print(summarize(sample))With the sample data this prints a 4% failure rate, an amplification of 1.22, and a rate-limited share of about 15% of attempts.
Alerting on the right signal
A retry that succeeds is the system working as designed. Paging someone for every retry produces noise, and people learn to ignore it. Use these rules instead.
- Alert on the final failure rate over a window, such as 5 minutes. This is the user-visible problem.
- Warn on retry amplification crossing a threshold, for example above 1.3 for 10 minutes. This is the early signal that you are depending on retries more than usual.
- Alert on permanent errors (400, 401, 403, 404) separately. A sudden spike of 401s is usually an expired or rotated key, and retries will never fix it.
- Compare against a baseline. Some retry rate is normal for your provider and traffic level, so alert on change, not on an absolute number you guessed.
Pitfalls
- Unbounded label values. Use
modelandoutcomeas metric labels. Never usecall_id, user IDs, or full error messages. Each distinct value creates a new time series, which can overwhelm the metrics backend. - Logging only the exception text. Message strings change between library versions. Log a stable
outcomeclass and keep the message as an extra field. - Measuring only the final latency. If you record only total call time, you cannot tell whether slowness came from the provider or from your own backoff sleeps.
- Dropping the request ID. When you open a support ticket, the provider's request ID is the fastest way to get an answer.
- Wall-clock timing. Use
time.monotonic()for durations, as the code above does. The system clock can jump.
Practical checklist
- One structured log line per attempt, sharing a
call_id. - A stable
outcomefield and afinal_reasonon the last attempt. - Counters for attempts by outcome, calls by result, and retries.
- Separate attempt and call latency percentiles.
- Alerts on final failures, with retry amplification as a warning.
- No prompt content or secrets in logs.
Exercise
Your dashboard shows a final failure rate of 0.1%, but retry amplification has climbed from 1.05 to 1.8 over two days, and most extra attempts are http_429. Users have not complained. What does this tell you, and what would you check next?
Show answer
The system is still masking the problem with retries, but it is sending nearly twice the intended traffic, mostly into rate limits. The retries themselves add load and latency, and the 0.1% failure rate will likely rise once retries run out. Check whether request volume or concurrency grew, whether tokens per minute (not only requests per minute) are the binding limit, and whether the client-side throttle is configured below the provider's limits. Also check p95 call latency, which probably increased because of backoff sleeps. Adding or tuning client-side throttling should bring amplification back toward 1.