Lesson 34 — Beginner

Async, Concurrency & Batching

Ek-ek karke 100 calls lagana = minutes. Parallel chala diya = seconds — lekin rate limit aur quota pe chhuri. Is lesson mein hum sync vs async, semaphore se bounded concurrency, rate limits aur throughput–cost trade-off dekhenge, provider SDK aur orchestration layer dono ke angle se.

⏱ 10 min• Beginner• Multi-step LLM Workflows

Concurrency kab madad karta hai

WHAT

Concurrency matlab kayi requests ek saath pending rakhna — jab tak ek ka jawab aata hai, doosri chal rahi hai. LLM calls I/O waiting hain, isliye CPU nahi, network wait hi asli bottleneck hai.

WHEN

Jab independent requests hon — 500 documents classify, N users ke summaries, parallel enrichment. Ek hi request ko speed karne ke liye nahi (wo model ki speed hai).

WHERE

Data pipelines, backfill jobs, web request handlers (tumhare apne API ke andar), parallel research agents — kahin bhi batch kaam ho.

Do words ka farq: parallelism = ek waqt mein kaafi kaam chal rahe hain; throughput = unit time mein kitne kaam poore hue. Streaming (M2.2) latency ka ehsaas badlati hai — concurrency throughput badlati hai.

Asyncio se bounded concurrent calls

import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI()
sem = asyncio.Semaphore(8)          # ek saath max 8 — bounded

async def one_call(text):
    async with sem:
        resp = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": text}],
        )
        return resp.choices[0].message.content

async def main(texts):
    tasks = [one_call(t) for t in texts]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    ok = [r for r in results if not isinstance(r, Exception)]
    failed = [r for r in results if isinstance(r, Exception)]
    print(f"done: {len(ok)} ok, {len(failed)} failed")

asyncio.run(main(texts))
Bounded rakho: Semaphore ke bina 1000 tasks ek saath uchhal padenge — 429 aayegi, kuch fail honge, aur tum retry se load aur badha doge. Concurrency limit tumhara pehla defence hai.

Rate limits aur bounded throughput

Concurrency badhao          : throughput up, per-request latency usually same
Limit paar (429 / TPM)      : failures up, retries up, effective throughput DOWN
Limit ke andar rehna         : steady throughput, kam errors, aasaan debugging

Rules of thumb:
- Concurrency limit = tumhara semaphore + provider ke rate limit ka beech
- 429 aaye toh concurrency THODO karo, badhao nahi
- Chhote calls vs bade prompts — token limit alag-alag pe lagti hai
- Provider docs mein apne tier ke limits dekho — numbers badalte rehte hain
Trap: Pehli 429 par aur tez mat ho jao. Backoff + concurrency kam = throughput wapas aata hai. 429 ke baad bhi blind retry = throttling ka cycle.

Throughput, latency aur cost ka trade-off

Decision rule: Independent kaam hai → bounded parallel chalao. Dependent steps hain → concurrency bekaar. Real-time zaroorat nahi → provider ka batch endpoint docs se check karo.

Exercise

Question: Ek waqt mein kitni requests chal rahi hain — is limit ko enforce karne wala Python primitive kaunsa hai?

Question: asyncio.gather tasks ko sequential chalata hai ya parallel?

Question: Rate limit exceed hone par provider commonly kaunsa HTTP status code deta hai?

Question: Dependent (ek-doosre ka input) steps ko parallel chalana theek hai ya nahi?

Common mistakes

Desi example: Chai counter ki line

Ek chaiwale ke paas das order — ek-ek banaye toh sab baithein. Chaar chaiwale laga do (bounded), stove utna hi (limits):

text
1 chaiwale  : 10 order x 3 min = 30 min      (sequential)
4 chaiwale  : 10 order, ek waqt 4 = ~9 min   (gather)
40 chaiwale : stove hi nahi = 429 jaisa       (overload, rate limit)

Semaphore(4) = "ek waqt 4 hi order lo" — line sambhali rehti hai.
Interview angle — yahan se sawaal aate hain
  • Q: Sync aur async call ka farq? — Sync ruk kar wait karta hai; async await se beech ka kaam ho sakta hai. Model ka total time dono mein same.
  • Q: Bounded concurrency kyun chahiye? — Rate limits (429, TPM) ko respect rakhne ke liye; semaphore se ek waqt mein fixed in-flight requests.
  • Q: Parallelism ki cost kya hai? — Tokens wahi, lekin quota jaldi burn, retries/errors zyada, logs messy — aur dependent steps parallel ho hi nahi sakte.
  • Q: Real-time nahi chahiye toh kya option hai? — Provider ka batch/queue endpoint — offline processing, standard rate, aastaane cost.
Lesson complete?

Concurrency ka balance clear. Agla lesson — Robustness — mein dekhenge retries, timeouts aur fallbacks kaise likhte hain.

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