Skip to content
derpx06.dev
WritingExplainersNotesAbout
works on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisationworks on my machineit's always DNSship itLGTMTODO: sleepoff by oneread the docsgit push --force-with-lease404: sleep not foundhave you tried turning it off and on againrubber duck says: explain itpremature optimisation

Learning in public.

A student's notebook on system design, distributed systems and databases. Shared as I learn.

ReadWritingExplainersNotesAbout
ElsewhereGitHubLinkedInHugging FaceLeetCode
Say hellomanaskhairnar1511@gmail.com
derpx06
NORMALmain© 2026 Derpx06Pune, Indiatop ↑
Learn/LangChain Mastery/Part 3 · 2. LCEL & Prompt Architecture
Lesson 20 of 68

Streaming Tokens & Async Chains

Making your AI app feel fast. Sync vs Async.

Derpx0610 Jan · 1 min read
LangChain Mastery
Your First Chatbot: Talking to an LLMLCEL: Why LangChain Is a Composition EngineThe Runnable Protocol (invoke, batch, stream)Pipe Operator & Data FlowRunnableLambda & Custom LogicRunnableParallel & BranchingPromptTemplate vs ChatPromptTemplateSystem, Human, AI MessagesPrompt Architecture & ReusabilityStructured Output with JSON ModePydanticOutputParserOutputFixingParserStreaming Tokens & Async Chains
Contents
1. The Latency Problem2. Sync vs Async3. Streaming (The UX Fix)4. Cancellation5. Summary
0% read · 1 min leftBack to top ↑
Course outline & contents0%
LangChain Mastery
Your First Chatbot: Talking to an LLMLCEL: Why LangChain Is a Composition EngineThe Runnable Protocol (invoke, batch, stream)Pipe Operator & Data FlowRunnableLambda & Custom LogicRunnableParallel & BranchingPromptTemplate vs ChatPromptTemplateSystem, Human, AI MessagesPrompt Architecture & ReusabilityStructured Output with JSON ModePydanticOutputParserOutputFixingParserStreaming Tokens & Async Chains
Contents
1. The Latency Problem2. Sync vs Async3. Streaming (The UX Fix)4. Cancellation5. Summary

1. The Latency Problem

GPT-4 is slow. Generating a paragraph can take 10 seconds. If you use standard invoke(), your user stares at a spinner for 10 seconds. They assume your app is broken.

2. Sync vs Async

In a web server (like FastAPI), blocking the thread for 10 seconds kills your throughput. You can only handle 1 user per thread. You must use async/await.

async_invoke.py
import asyncio

async def main():
  # .ainvoke() is the async version
  response = await chain.ainvoke({"topic": "bears"})
  print(response)

# Run it
asyncio.run(main())

3. Streaming (The UX Fix)

To fix the "Spinner of Death," we stream tokens. LangChain objects support .astream().

async_stream.py
async def stream_chat():
  async for chunk in chain.astream({"topic": "bears"}):
      # In a real web app, you would send this via WebSocket/SSE
      print(chunk.content, end="", flush=True)

4. Cancellation

One hidden benefit of Async is Cancellation. If the user clicks "Stop Generating" or closes the tab, an async chain can be cancelled instantly, saving you money. A synchronous request would keep running on the server until it finishes.

5. Summary

Production AI requires Async for scale and Streaming for UX. LangChain supports both out of the box with the a- prefix methods (ainvoke, astream, abatch).

Key Intuition: "Speed is part of intelligence."

Track your progressSign in and your progress follows you across devices.
Sign in to track progress Next lesson
← Previous lessonOutputFixingParserNext lesson →The Document Object & Metadata