Index of every page on this site: llms.txt
All skills
jeremylongshore avatar

/langchain-performance-tuning

@0d57af8
Run it yourself

Tune LangChain 1.0 / LangGraph 1.0 Python chains and agents for throughput, latency, and cost — streaming modes, explicit batch concurrency, semantic plus exact caches, persistent message history, and async-safe retriever patterns. Use when p95 latency exceeds target, batching "does not work", cost grows linearly with traffic, or a process restart wipes chat history. Trigger with "langchain performance", "langchain slow batch", "langchain throughput", "langchain p95 latency", "semantic cache hit rate".

Use this Skill: https://skilld.dev/gh/jeremylongshore/tons-of-skills-marketplace/langchain-performance-tuning

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesbatch-concurrency-per-provider.md

≈776 tokens on demand. Your agent reads this file only when SKILL.md points to it.

Batch Concurrency Per Provider

The P08 Trap

Runnable.batch(inputs) and .abatch(inputs) in LangChain 1.0 default to max_concurrency=1. They loop inputs sequentially with extra bookkeeping — sometimes slower than a plain for loop.

# WRONG — this is serial plus overhead
results = await chain.abatch(inputs)

# RIGHT — explicit parallelism
results = await chain.abatch(
    inputs,
    config={"max_concurrency": 10},
)

LangChain docs: https://python.langchain.com/docs/how_to/streaming/#batching.

Per-Provider Safe Concurrency Table

Baseline values. Always confirm against your account's posted RPM/TPM and then load-test.

Provider Tier assumption Safe max_concurrency starting point Ceiling signal
Anthropic (claude-sonnet-4.5 / 4.6) Tier 2-3 10-20 429 rate_limit_error or rising retry-after headers
OpenAI (gpt-4o / 4o-mini) Tier 3-4 20-50 429 + TPM exhaustion in header
OpenAI (o1 / reasoning) Any 2-5 Cost + latency, not rate limits
Azure OpenAI PTU From deployment quota Quota saturation in metrics
Google Gemini 1.5/2.5 Paid 10-30 429 or quota exceeded
Cohere Production 20-40 429
Local vLLM / TGI GPU-bound 100-500 (batch sweet spot ~N=32-64 on A100) GPU KV-cache OOM
Self-hosted Ollama Consumer GPU 1-4 Process queue backpressure

Measuring Saturation

  1. Sweep max_concurrency at 1, 5, 10, 20, 40 against a fixed 200-input workload.
  2. Record p50, p95 total latency and total cost.
  3. Plot throughput vs concurrency. The curve flattens — pick the knee, not the peak.
  4. Subtract 20% headroom for traffic spikes.
import asyncio, time

async def sweep(chain, inputs, levels=(1, 5, 10, 20, 40)):
    for n in levels:
        t0 = time.perf_counter()
        await chain.abatch(inputs, config={"max_concurrency": n})
        dt = time.perf_counter() - t0
        print(f"concurrency={n:3d}  wall={dt:6.2f}s  rps={len(inputs)/dt:5.1f}")

Multi-Worker Semaphore Pattern

max_concurrency is per-process. With N gunicorn workers you multiply the effective concurrency by N. Protect the account-wide limit with a shared semaphore (Redis) or a global gateway (LiteLLM proxy, Anthropic Bedrock, Portkey).

# Per-process semaphore guarding cross-request calls inside one worker
sem = asyncio.Semaphore(20)

async def guarded_invoke(chain, input):
    async with sem:
        return await chain.ainvoke(input)

For cross-worker limits, prefer a proxy (LiteLLM, Portkey, OpenRouter) that enforces the ceiling centrally. Application-level Redis semaphores add latency and drift out of sync under restart storms.

Checklist

  • Every .batch / .abatch call has an explicit max_concurrency in config.
  • Concurrency is capped below the provider RPM with 20% headroom.
  • Multi-worker deploys use a proxy or Redis semaphore for account-wide limits.
  • Sweep results are recorded in the runbook (update quarterly).

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts2mo3 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    The skill provides comprehensive guidance on performance tuning for LangChain 1.0 and LangGraph applications. It includes best practices for asynchronous programming, batching, caching, and persistent chat history. No security risks, obfuscation, or malicious patterns were identified in the instructions or reference materials.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

Signed by skilld at 0d57af8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub yesterday.

Activeupdated 2 months ago
What it can do
Reads files Edits files Runs commands
version
2.7.0
author
Jeremy Longshore <jeremy@intentsolutions.io>
compatibility
Designed for Claude Code
All 5 allowed tools
ReadWriteEditBash(python:*)Bash(redis-cli:*)
Other metadata
tags
[
  "saas",
  "langchain",
  "langgraph",
  "python",
  "langchain-1.0",
  "performance",
  "caching",
  "async"
]

README badge

README badge for jeremylongshore/tons-of-skills-marketplace/langchain-performance-tuning