Vendors publish rate limits. Your code ignores them by default.
So the integration works fine in dev, then production traffic spikes, your app bursts past the quota, and the vendor answers with a wall of 429s. Your retry policy (transient error, right?) hammers the same wall, the vendor's abuse detection notices, and now your key is throttled harder or temporarily banned. A limiter on your side of the wire would have prevented the whole failure.
Server-side rate limiting in ASP.NET Core protects you from your callers. This article is the mirror image: protecting a vendor's quota from you.
Which Rate Limiter Fits a Vendor Quota?
.NET ships a rate limiting library with four algorithms: concurrency, fixed window, sliding window, and token bucket.
dotnet add package System.Threading.RateLimiting
For outbound quotas, token bucket is usually the right fit because it's how most vendors think: a sustained rate plus a burst allowance. "100 requests per second with bursts up to 200" translates directly:
using System.Threading.RateLimiting;
var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions
{
TokenLimit = 200, // burst capacity
TokensPerPeriod = 100, // sustained rate
ReplenishmentPeriod = TimeSpan.FromSeconds(1),
QueueLimit = 500, // callers allowed to wait
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
AutoReplenishment = true
});
If the vendor enforces a strict window instead ("1,000 per minute, resets on the minute"), use SlidingWindowRateLimiter so you don't burst 1,000 at 11:59:59 and another 1,000 at 12:00:01.
The API is one method: AcquireAsync waits (up to the queue limit) for a permit, and the returned lease tells you whether you got one.
Enforcing It: A DelegatingHandler
The cleanest enforcement point is a delegating handler, so every request through the client passes the limiter and no call site can forget:
using System.Net;
using System.Threading.RateLimiting;
public class ClientSideRateLimitedHandler(RateLimiter limiter)
: DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
using RateLimitLease lease = await limiter.AcquireAsync(
permitCount: 1, cancellationToken);
if (lease.IsAcquired)
{
return await base.SendAsync(request, cancellationToken);
}
// Queue full: fail fast locally instead of hitting the vendor.
var response = new HttpResponseMessage(HttpStatusCode.TooManyRequests)
{
RequestMessage = request
};
if (lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
response.Headers.Add("Retry-After",
((int)retryAfter.TotalSeconds).ToString());
}
return response;
}
}
Wire it up with IHttpClientFactory, one limiter per vendor:
builder.Services.AddSingleton(new TokenBucketRateLimiter(
new TokenBucketRateLimiterOptions
{
TokenLimit = 200,
TokensPerPeriod = 100,
ReplenishmentPeriod = TimeSpan.FromSeconds(1),
QueueLimit = 500,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
AutoReplenishment = true
}));
builder.Services.AddTransient<ClientSideRateLimitedHandler>(sp =>
new ClientSideRateLimitedHandler(
sp.GetRequiredService<TokenBucketRateLimiter>()));
builder.Services.AddHttpClient("vendor", client =>
{
client.BaseAddress = new Uri("https://api.vendor.com");
})
.AddHttpMessageHandler<ClientSideRateLimitedHandler>();
Below the quota, requests flow through with microseconds of overhead. At the quota, requests queue briefly and smooth out the burst. Past the queue limit, they fail locally with a synthetic 429, which costs you nothing with the vendor and gives your own callers a backpressure signal.
The limiter is registered as a singleton on purpose. A per-request or per-handler-instance limiter limits nothing.
Honoring Retry-After: The Other Half
Even with a local limiter, you'll still see occasional 429s: quotas get recalculated, other systems share the key, vendors have global incidents.
A 429 with a Retry-After header is the vendor telling you exactly when capacity returns.
Retrying sooner wastes the request, and many vendors extend the penalty when you do.
I covered the header semantics in detail in rate limit headers and 429 handling.
Here's the enforcement with Polly v8, where DelayGenerator can read the delay straight off the response.
This registration replaces the AddHttpClient("vendor") call above; keep the limiter and handler registrations:
dotnet add package Microsoft.Extensions.Http.Resilience
using System.Net;
using Polly;
using Polly.Retry;
IHttpClientBuilder vendor = builder.Services.AddHttpClient("vendor", client =>
{
client.BaseAddress = new Uri("https://api.vendor.com");
});
// Added first, so the retry is the outer handler.
vendor.AddResilienceHandler("vendor-retry", pipeline =>
{
pipeline.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
{
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
.HandleResult(r => r.StatusCode == HttpStatusCode.TooManyRequests)
.Handle<HttpRequestException>(),
MaxRetryAttempts = 3,
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
DelayGenerator = args =>
{
// Prefer the vendor's Retry-After over our own backoff.
if (args.Outcome.Result?.Headers.RetryAfter?.Delta
is TimeSpan retryAfter)
{
return ValueTask.FromResult<TimeSpan?>(retryAfter);
}
return ValueTask.FromResult<TimeSpan?>(null); // use default backoff
}
});
});
// Added second, so every retried attempt acquires its own permit.
vendor.AddHttpMessageHandler<ClientSideRateLimitedHandler>();
Returning null from DelayGenerator falls back to the configured exponential backoff with jitter, so the vendor's hint wins when present and sane defaults apply when it isn't.
Order matters in this stack.
IHttpClientFactory makes the first handler you add the outermost, so the resilience handler goes first and the rate limiting handler sits inside the retry.
Every retried attempt then passes the limiter again, which is the behavior you want, because a retry that bypasses the limiter can still push you past the quota.
Chain AddHttpMessageHandler before AddResilienceHandler and the limiter wraps the retry instead: one permit covers the first attempt and all three retries.
With this order, a local 429 from a full queue also goes through the retry, which waits for the limiter's Retry-After, so your callers see it only after the retries run out.
Does It Work Across Multiple Instances?
System.Threading.RateLimiting is in-process.
Run 5 replicas, each limiting to 100 requests per second, and the vendor sees 500.
You have three options:
- Divide the quota. Give each instance
quota / N. This works when the replica count is static and wastes quota when traffic is uneven across instances. - Coordinate through Redis. A shared token bucket in Redis gives you a true global limit at the cost of a network hop per acquisition. I walk through the implementation in distributed rate limiting with Redis.
- Under-provision and rely on Retry-After. Set local limits to a conservative fraction, and let the 429 handling absorb the overflow. It's the least precise option, but it needs no extra infrastructure.
A practical default is to divide the quota when instance counts are stable and move to Redis when autoscaling makes N a moving target.
The queue is one more caveat.
A generous QueueLimit smooths bursts, but every queued request is a caller waiting.
If your callers have a 2-second timeout budget and the queue represents 10 seconds of backlog, you're queueing requests whose callers already gave up.
Size the queue against latency tolerance, not against burst size, and pass the caller's CancellationToken into AcquireAsync so abandoned requests leave the queue.
Summary
Treat a vendor's quota as part of its API contract:
- Encode the vendor's published limit as a
TokenBucketRateLimiter(or sliding window for strict windows) and enforce it in aDelegatingHandlerso no call path can bypass it. - Add that handler after
AddResilienceHandler, so it sits inside the retry and retried attempts need a permit too. - One singleton limiter per vendor, wired through
IHttpClientFactory. - Honor
Retry-Afteron 429s via Polly'sDelayGenerator, with jittered exponential backoff as the fallback. - Remember the limiter is per-process: divide the quota across instances or coordinate through Redis.
Your app then runs at the vendor's limit, never meaningfully past it, and a burst above the quota waits in a local queue instead of becoming an incident.
Frequently Asked Questions
How do I throttle outgoing API calls in C#?
Use System.Threading.RateLimiting with a DelegatingHandler on HttpClient. The handler acquires a permit from a rate limiter before each request is sent, so calls queue or fail locally instead of hitting the vendor above your quota. Register it after AddResilienceHandler so it sits inside the retry and every retried attempt also needs a permit. TokenBucketRateLimiter matches the burst-plus-sustained-rate model most vendors use.
Which rate limiter algorithm should I use for outbound calls?
Match the vendor. Most third-party APIs describe their limit as a sustained rate with some burst allowance, which is a token bucket. If the vendor enforces a strict fixed window, like 1,000 requests per minute reset on the minute, a sliding window limiter tracks it more closely and avoids edge-of-window bursts.
What should I do when a third-party API returns 429?
Read the Retry-After header and wait at least that long before retrying. Retrying sooner is pointless and can extend the penalty. In Polly v8 the retry strategy can compute its delay from the response via DelayGenerator, which makes honoring Retry-After automatic.
Does client-side rate limiting work across multiple application instances?
Not by itself. System.Threading.RateLimiting is in-process, so five instances each limiting to 100 requests per second produce 500 against the vendor. Either divide the quota per instance or coordinate through a shared store like Redis when instance counts change dynamically.

