Lesson 35 — Beginner

Robustness — Retries, Timeouts & Fallbacks

API hamesha nahi chalti — 429 aati hai, 500 aati hai, network kat jaata hai, kabhi-kabhi jawab hi tootta hai. Is lesson mein hum kaunse errors retry karne hain, kaunse fail-fast, exponential backoff + jitter, timeouts, fallback models aur reliability logic kahan likhni hai — sab Python code ke saath dekhenge.

⏱ 20 min• Beginner• Async, Concurrency & Batching

Aam API failures aur pehla rule

WHAT

Robustness matlab failures ko plan karna: kaunsa error transient hai (dobara try karo), kaunsa permanent (rok do), kitna wait karo aur last resort kya ho. Yeh soch tumhare app layer mein banti hai.

WHEN

Har production call par. Dev mein ek call chal gaya toh lagta hai sab theek — traffic aane par hi pata chalta hai ki retry/timeout nahi tha.

WHERE

API wrappers, tool execution, background jobs, agent loops — jahan bhi tum bahri service par depend karte ho, wahan yeh layer compulsory hai.

401 / 403  auth        : KEY GALAT — retry MAT karo, fauran fail + alert
400 / 422  bad request : payload hi galat hai — retry se fix nahi hoga
429        rate limit  : transient — wait + backoff + retry
500/502/503 server     : transient — limited retry
timeout / network      : transient — retry (par naya timeout de kar)
context length error   : prompt hi bada hai — history trim karo, retry nahi
malformed output       : parse/repair step (M2.4), retry with fix instruction
Pehla rule: Auth aur validation errors = fail-fast. Rate limit aur 5xx = retry with backoff. Yehi do lage toh aadhi production problems shuru se hi solve ho jaati hain.

Retry policy — backoff, jitter, max tries

import random, time

RETRYABLE = {429, 500, 502, 503, 504}
MAX_TRIES = 4

def call_with_retry(fn, timeout=20):
    for attempt in range(MAX_TRIES):
        try:
            return fn(timeout=timeout)
        except Exception as e:
            status = getattr(e, "status_code", None)
            if status not in RETRYABLE or attempt == MAX_TRIES - 1:
                raise                              # fail fast ya aakhri try
            wait = min(2 ** attempt, 8) + random.uniform(0, 1)   # backoff + jitter
            print(f"retry {attempt + 1} in {wait:.1f}s ({status})")
            time.sleep(wait)
Trap: Timeout ke baad request server par pahunch chuki ho sakti hai — blind retry se wo dobara chal sakti hai. Side-effect calls ke liye idempotency key ya pehle status-check pattern use karo.

Timeouts aur fallback chain

def ask_with_fallback(messages):
    chain = [
        ("primary",  PRIMARY_MODEL, 15),
        ("fallback", FALLBACK_MODEL, 30),   # alag model/provider bhi ho sakta hai
    ]
    last_err = None
    for name, model, tmo in chain:
        try:
            return client.chat.completions.create(
                model=model, messages=messages, timeout=tmo, max_retries=0)
        except Exception as e:
            last_err = e
            print(f"{name} down: {type(e).__name__} — agla try")
    raise RuntimeError(f"poora chain fail: {last_err}")   # degradation last
Log every level: Chain ka har level logged ho — kitni baar backup chala, kitna extra time laga. Warna quality drop kab hua pata hi nahi chalega.

Reliability logic kahan likhni hai

Layer 1 — Provider SDK   : built-in max_retries, HTTP-level retry (basic)
Layer 2 — Orchestration  : chain-level retries, callbacks, framework fallback
Layer 3 — YOUR APP       : business rules — kaunsa error retry, idempotency,
                           degradation, alerts, user-facing message

Rule: har layer apne level ka error handle kare — ek jagah sab mat rakho.
Placement rule: Jo cheez kisi bhi provider/API par lagu ho (backoff, timeout) — wrapper mein. Jo cheez business par lagu ho (refund retry nahi karega) — app code mein.

Exercise

Question: Rate limit (429) aane par sahi reaction kya hai — fail fast ya retry with backoff?

Question: 401 auth error ke liye sahi reaction kya hai — retry ya fail fast?

Question: Exponential backoff mein wait har retry par kaisa badhta hai? (ek word: linear/double)

Question: Thoda random wait add karne ko kya kehte hain jo thundering herd rokta hai?

Common mistakes

Desi example: Telephone ka busy tone

Exchange busy ho toh koi ek second par das baar dial nahi karta — thoda ruk kar, alag-alag time par try karta hai, aur nahi lage toh message chhod jaata hai. Yehi teen cheezein hain backoff, jitter aur degradation:

text
try 1 : wait 1s (+0.4s jitter)   busy
try 2 : wait 2s (+0.7s jitter)   busy
try 3 : wait 4s (+0.2s jitter)   LAG GAYI

fallback: nahi lage -> SMS chhod do (canned message)
App kabhi crash nahi honi chahiye — user ko ek saaf line mile.
Interview angle — yahan se sawaal aate hain
  • Q: Kaunse errors retry karte hain? — 429 aur 5xx/network/timeouts; 400/401 jaise client errors fail-fast.
  • Q: Exponential backoff + jitter ka logic? — Wait doogna (server ko space) + random offset (clients ek saath na laut aayein).
  • Q: Timeout kyun mandatory hai? — Nahi toh request hang kar ke worker block rakhti hai; budget user experience ke hisaab se set karo.
  • Q: Fallback ka risk kya hai? — Backup model ki quality/behaviour alag ho sakti hai; contract tolerant rakho aur fallback hits log karo.
Lesson complete?

Retries, timeouts aur fallbacks ready. Agla lesson — Cost, Usage & Observability — mein dekhenge har request ko kaise track karte hain.

Popular courses: Data Science Course in Lucknow · AI Course in Lucknow · Python Course in Lucknow · Power BI Course · Data Analytics Course