Real LLM applications need more than invoke. Chat UIs stream tokens, data pipelines process many records, and APIs must avoid blocking workers for long-running model calls. LangChain runnables support async, streaming, and batch-style execution so you can match the runtime behavior to the product.
Performance work should be deliberate. Streaming improves perceived latency. Batch execution improves throughput. Async prevents the web server from waiting wastefully. Concurrency limits protect your budget and provider rate limits.
Streaming is useful when answers are long or users need immediate feedback. Your frontend should handle partial text, cancellation, errors after partial output, and final metadata such as sources.
Batch calls are useful for classification, extraction, evaluation, and offline enrichment. Add concurrency limits so a batch job does not overwhelm rate limits or create surprise costs.
Async invocation fits web APIs that need to keep workers responsive.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
chain = build_rag_chain()
class Question(BaseModel):
question: str
@app.post("/ask")
async def ask(payload: Question):
answer = await chain.ainvoke(payload.question)
return {"answer": answer}
Batch execution is useful for regression tests and offline jobs.
questions = [
"How do I configure SSO?",
"What is the refund window?",
"Can I delete audit logs?",
]
answers = chain.batch(
questions,
config={"max_concurrency": 3},
)
for question, answer in zip(questions, answers):
print("\nQUESTION:", question)
print("ANSWER:", answer[:500])
Total generation time may be similar, but users see the first tokens sooner, so the interface feels faster.
No. Use async when it fits your server and dependencies. A simple synchronous endpoint can be easier to operate for small apps.
Send a clear terminal error event so the interface does not leave a response looking permanently unfinished.
Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.
Explore 500+ free tutorials across 20+ languages and frameworks.
Fresh tutorials, interview guides, and coding practice in your inbox.