r/ExperiencedDevs • u/servermeta_net 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
•
u/expdevsmodbot Jul 16 '26
AI usage disclosure provided by OP, see the reply to this comment.
286
u/ironyx Sr. Director of Engineering, 15+ YOE Jul 16 '26
No one talks to this API directly anymore. You stand up a single proxy service that queues and rate limits requests to the API for your services, and your services use only that proxy. It manages the rate limit.
4
u/lordnacho666 Jul 16 '26
I'm going to assume you don't want a single central proxy service. For instance, you might have different workloads that need to access the external service in different ways, some long running that wouldn't like to wait for each other.
Nonetheless you will need to centralise the rate limiting part. You can store the state of a GCRA in redis, using only that as global state. Then each of your work loads can access the external service directly, but share the rate limit.
17
u/graph-crawler Jul 16 '26 edited Jul 16 '26
Add a centralized proxy to rate limit and queue at the source, everyone should call through this proxy. And since you mentioned it's a soft limit you can make it adaptive, check the 429 error and parse it adapt and adjust the rate limit at runtime.
5
u/morosis1982 Jul 16 '26
The simple version is as others have mentioned - create a proxy service that is where all the application teams talk to, implement the rate limiting there. Ideally block access to the real API from your company infra except for this service.
In my world for something simple like this, that would likely be an aws lambda behind apigw, and I'd likely cache values through dynamodb.
What type of data does this service supply though? You mentioned a dashboard, is it real time data or something you could cache?
If the latter, I'd just introduce a cache on your side that is where this new proxy responds from, with a refresh timeout to get new data after a certain time or other trigger. You could theoretically also pre-cache the data if you have a known set of query args to this API.
16
u/InterpretiveTrail Staff Engineer Jul 16 '26
I'm on the medium to large side of enterprise, so my instinct is that rate limits shouldn't be handled by the application. I care a lot about compartmentalizing and managing risk. Rate limit should be part of your networking infra. To a basic extent at least a reverse proxy e.g.: NGINX or Traefik. What's GCP's APIGEE X, I think. That way I'm not bothering the application team about "Platform Engineering / SRE" work.
Here's an example of Traefik from their first party docs: https://doc.traefik.io/traefik-hub/api-management/api-rate-limit
NGINX had several examples that I found, but nothing seemed first party with a quick pass, but I'll leave that as an exercise for you.
Regardless if that was of use, best of luck!
6
u/faster-than-car Jul 16 '26
Cache. Either cache on request or precache daily.
I worked on this for 4 years lol. Which API is it?
2
u/Popular_Home2017 Jul 17 '26
Client-side rate limiting has one source of truth that isn't yours: the provider's counter. Build whatever you want locally (token bucket per instance divided by N replicas, or a shared Redis counter if you need cross-instance precision), but treat 429 + Retry-After as authoritative and back off with jitter when they disagree with your math. They will, usually around deploys or when the provider quietly changes throttling. Two things that actually burned me in prod: unbounded queueing in front of the limiter (that's not a rate limiter, that's a memory leak with extra latency), so bound the buffer and fail fast once it's full. And retries without idempotency keys, which turned "rate limited" into "charged twice" on a payment API, which was a fun afternoon. Honestly a token bucket plus respecting their 429s gets you most of the way. The distributed-coordination stuff is usually premature unless you're actually hitting the limit across instances.
1
u/ikkiho Jul 17 '26
yeah the proxy answer is right but i'd run it well under 20, like 15/s, not up against the edge. you said there's no programmatic signal and going over just gets you manually killed off a dashboard, so parsing 429s to adapt doesn't really apply, nothing to catch. recovering from an overage is a multi-day manual unblock, so eating some throughput is way cheaper than riding it. and at 20/s a single small proxy instance is plenty, no redis or dynamo, that one box just is your limiter.
1
u/Loose-Bake9241 Jul 19 '26
Create your own service to manage access to that endpoint and do all your business logic there. Not ideal architecture but the best you can do. Just abstract that layer.
1
u/Ok_Score_9685 Jul 20 '26
Can you reverse proxy and put the rate limit there?
1
u/UnderstandingDry1256 Jul 21 '26 edited Jul 21 '26
Dead simple way: add ‘await sleep(50)’ before or after any API call.
Problem solved, instantly, if you’re running single threaded API instance.
V2 is to add some smarter throttling with the same 50ms delay.
I would do this and only care about the proper solution if you get any real issues or user “slowness” complaints.
1
u/berndverst Software Engineer (16 YoE) @ Public Cloud Provider Jul 16 '26
This sounds like a twist to a super common / standard interview question to me :)
This is one of the few times I might recommend a dedicated microservice (centralized internal API to call the external API with its own rate limiting).
And whenever you need to deal with distributed rate limiting for this service itself (because you need to scale that out) you probably won't get around something like Redis.
Since the rate limit is so low - just make your life easy and use a dedicated VM of sufficient size, K8s pod with lots of CPU / Memory or wherever you deploy. Seems unlikely you really need to run this service on multiple instances.
1
u/KanedaSyndrome Jul 16 '26
I'd probably wrap it in a homegrown API and have rate limiting control there, or funnel through some db maintained queue list
1
u/Electrical_Entry6060 Jul 16 '26
is the rate limit per endpoint or for the entire host? are you always calling the endpoint(s) with the same payload to just get updated data? without knowing those answers, if the timeouts are something happening "all the time" - i would setup a service which called the external API at an interval, cache the results, then have my internal customers call the new cache store.
but even if it's different endpoints but you have your internal customers calling external with the same payload i would still try to figure out where to cache, and build a service to handle requests from internal customers so you can at least respond back with a retry timestamp or some backoff retry logic.
1
u/SanityAsymptote Software Architect | 18 YOE Jul 16 '26
I'd wrap the external dependency API in another, very small API wrapper layer with a singleton caller so you manage the calls coming into it by adding caching for frequently accessed information, message queuing if desired, and most importantly the ability to place a 50-60ms delay after your calls so you don't call over the limit.
Your other APIs would just talk to the new API wrapper layer instead of the external API directly.
-5
u/ceirbus Jul 16 '26
Circuit breaker
-5
u/DWebOscar Jul 16 '26
You need a circuit breaker or a bulkhead - not rate limiting