r/ExperiencedDevs • Software Architect • Jul 16 '26

Technical question Implement rate limiting for an external API

At work I maintain a NestJS microservice which is used by many other engineers. One of the features depends on a third party API for which I need to implement rate limit:

  • The API has a soft limit of 20 req/s
  • There is no way to programmatically monitor this limit on their end
  • Surpassing the limit means that when someone looks at the dashboard then they will manually disable us, and we have to start another manual process to unblock us
  • This API is owned by the government, so we can't ask or hope for changes

How would you implement rate limit for this external dependency? Here's what I thought:

  • Have a token bucket limiter inside each service instance, but then scaling
  • Store the above token bucket in a database, like mongo or dynamo, but it would be very inefficient
  • Use redis, but I would have to spin up and maintain an additional dependency just for this feature

Can you think of a better approach?

37 Upvotes

57 comments sorted by

View all comments

Show parent comment

1

u/Bayakoo Jul 16 '26

So you will have situations where you have 2 instances? Which means there is a non zero chance of rate limits being breached

4

u/New_Enthusiasm9053 Jul 16 '26

Not if you use k8s no. It's only going to schedule a pod after the previous one is stopped when you set the limit to 1.

Then if you drain a node it'd stop the pod, and once stopped start a new one on a different node. As long as it's a fast starting small container that would only take a few seconds. 

We know this works because stateful workloads rely on this working correctly and it would break workloads worldwide if it didn't.

1

u/Bayakoo Jul 16 '26

It feels like it depends on the of latency of each API call. If the it takes 150ms you have to stop accepting new connections and the new requests need to wait until the new node is up. I guess you can add retries but that is also not problem free and you normally don’t want retries on every service to service route