AI Hints
Home›LangChain Tutorial›Cache, Limits and Timeouts
LangChain · Lesson 83 of 120

Rate Limiting

Staying under limits.

⏱ 2 min read▶ Video at 1:34:10🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Model providers limit how many requests you can send per minute. Send too many, too fast, and your requests start failing. A rate limiter spaces your calls out, so you stay under the limit.

Rate Limiting
From the video: Rate Limiting
  • Providers limit requests
  • Too fast means errors
  • Space calls out

A rate limiter

In memory rate limiter allows a set number of requests per second. Here, one request every two seconds. We pass it to the model with the rate limiter argument. Then we make three calls, and print the time of each. Run it. The calls are spread out, about two seconds apart, instead of firing all at once.

rate_limit.pypython
import time
from langchain.chat_models import init_chat_model
from langchain_core.rate_limiters import InMemoryRateLimiter

limiter = InMemoryRateLimiter(requests_per_second=0.5, check_every_n_seconds=0.1)
model = init_chat_model("google_genai:gemini-flash-lite-latest", rate_limiter=limiter)

start = time.perf_counter()
for i in range(3):
    model.invoke("Say hi in one word.")
    print(f"call {i + 1} done at {time.perf_counter() - start:.1f}s")
Output
call 1 done at 2.9s
call 2 done at 4.6s
call 3 done at 6.7s

Limits in practice

Set the limiter a little below your provider's real limit. Share one limiter between all the models that use the same account. And remember, it only limits one program. If you run several servers, they each need their share.

keyvalue
Set itbelow the real limit
Shareone limiter per account
Per processeach server needs its share
Alsoretries for 429 errors

Summary

A rate limiter spaces out calls so you stay under the provider's limit. Pass it to the model with rate limiter. Next, making sure a call never hangs forever.

Key takeaways
  • InMemoryRateLimiter
  • requests_per_second
  • rate_limiter=...
Next up: Timeouts — never wait forever