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.
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 timefrom langchain.chat_models import init_chat_modelfrom langchain_core.rate_limiters import InMemoryRateLimiterlimiter = 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
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.
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.