Client-Side Rate Limiting: Respecting Third-Party API Limits

dotnethttpclientrate-limitingresilience
Client-Side Rate Limiting: Respecting Third-Party API Limits

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.

Each outgoing request passes through the rate-limited delegating handler, which acquires a permit; if a permit is available the call reaches the vendor API, otherwise the handler returns a local 429 with Retry-After and never touches the vendor

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 a DelegatingHandler so 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-After on 429s via Polly's DelayGenerator, 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.

  • A single "timeout" setting hides three different things: how long one attempt may take, how long the whole retry sequence may take, and how long the inbound request may take. Set them independently and they stack, which can turn a 30-second timeout into a multi-minute wait. Here is the layered model, a request-budget approach that stops the stacking, and the .NET code for each layer.

  • One slow downstream service can take out your entire application without returning a single error, by tying up the connections, memory, and blocked threads every other request needs. The bulkhead pattern caps how much of your capacity any single dependency can use. Here is how to build bulkheads in .NET with semaphores, Polly concurrency limiters, and partitioned HttpClients.

  • You have retries, circuit breakers, and timeouts configured. Have you ever seen them fire? Simmy injects faults, latency, and bad responses into your Polly pipelines so you can prove your resilience policies work before a real outage tests them. Fault injection often turns up a policy that was a misconfigured no-op.

Browse all Resilience guides →
Loading comments...

Go deeper

Whenever you're ready, there are 5 ways I can help you:

  1. Learn to deploy and run your apps on a VPS with Dokploy and Tailscale. Keep administration private, automate releases, and practice restoring backups, with source code and a runbook you can reuse.

  2. Join 5,000+ students in this comprehensive course that will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture.

  3. Join 2,800+ engineers in this in-depth course that will transform the way you build modern systems. You will learn the best practices for applying the Modular Monolith architecture in a real-world scenario.

  4. Join 1,900+ students in this course that will teach you how to build production-ready REST APIs using the latest ASP.NET Core features and best practices. It includes a fully functional UI application that we'll integrate with the REST API.

  5. Join a community of 5,000+ engineers and software architects. You will also unlock access to the source code I use in my YouTube videos, early access to future videos, and exclusive discounts for my courses.

The .NET Weekly

One practical .NET tip, every Saturday.

Join 66,000+ engineers who read it. Free, and you can unsubscribe any time.