External API rate limits: queues, delays and fairness between clients

Separate provider limits from client budgets, preserve ordering and keep a waiting hint distinct from permission to repeat an unknown effect.

Two streams at a shared metering wheel suggest fair access to a limited resource.
Two streams at a shared metering wheel suggest fair access to a limited resource.

One client has queued several thousand messages. Another adds a single short notification and waits behind them, although its own budget is barely used. The external service then reports a rate limit, the worker sleeps inside the send operation, and the queue keeps growing. Reducing requests per second is not enough: we must also decide who receives the next opportunity and how much work we accept in the first place.

Consider a fictional delivery service, two clients named amber and blue, and one shared provider account. The conditions and numbers below belong to the teaching model. They are not current Telegram limits or the commercial limits of another platform. The PHP example has been tested as a single-process model using logical time.

Three different reasons to wait

A provider limit constrains a shared external resource: an account, method, recipient, or another service-defined scope. A client budget is our rule for distributing that resource. A job-specific pause follows a temporary refusal, a deferred start, or another condition.

These reasons can apply together. A client may already be entitled to its next attempt while the shared provider remains unavailable until a later instant. The send still waits. When only one client is limited, another may proceed. We cannot choose the scope of a pause to suit ourselves: it comes from the adapter contract and the known account context.

HTTP 429 indicates excessive request frequency; the response may include Retry-After. The status alone defines neither our fairness policy nor the distribution of queued work among clients.

Model constraint Key Consequence
Overall pacing One provider account At most one attempt per simulated second
Client pacing amber or blue At most one attempt per client every two seconds
Provider pause Shared account Both clients wait
Client pause One known client The other may receive the next slot
Job notBefore Job identifier This job cannot start yet

One instance of the example serves one provider scope. Creating an independent instance for every client would lose the shared limit. In a multiprocess application, that scope must also see shared state rather than a separate variable in each worker.

Rate limits do not determine order

A single FIFO queue faithfully preserves arrival order but lets one client occupy its entire front. In our model, each client has its own FIFO queue. The scheduler visits them in a circle and considers only the first job in each. After an actual attempt, the next search starts with the other client.

The head of amber may have to wait until second four. That does not prevent the scheduler from considering blue. However, the second amber job cannot pass the first: we deliberately preserve order within a client. Independent message types could have separate subqueues, but that would establish a different ordering promise.

Eligibility can be expressed as one condition:

eligible_at = max(provider_next, provider_pause,
                  client_next, client_pause, job_not_before)

The comparison itself reserves nothing. In the single-process teaching step, selection, budget spending, and attempt recording happen sequentially. A real shared queue requires an atomic claim or another coordinated transition. Two workers must not both observe a free slot and spend it twice.

Symfony provides fixed-window, sliding-window, and token-bucket policies; state and locking are described in the Rate Limiter documentation. Selecting such a policy does not automatically create client queues or a fair scheduling order. Our example uses simple minimum intervals so the ordering can be checked by hand.

Fairness has specific conditions

Suppose amber has a1, a2, and a3, while blue has b1 and b2. Both clients are eligible, the provider is available, and every job costs one attempt. The expected sequence is:

Simulated second Selected job Reason
0 a1 First eligible client
1 b1 Next client in the rotation
2 a2 The local amber interval has elapsed
3 b2 The local blue interval has elapsed
4 a3 The other queue is now empty

This is a predefined test expectation, not a throughput measurement. Under these conditions, one eligible queue cannot indefinitely bypass the other. If the provider pauses the whole account, neither has external slots available. If a client's own budget is exhausted, treating its wait relative to an eligible client as unfairness would also be misleading.

One attempt does not always have equal cost. A heavy request and a short read may consume different resources. That situation needs weights, a cost estimate, and a separate fairness criterion. Simple alternation should not be credited with guaranteeing equal latency or equal computational shares.

A waiting hint is not permission to repeat

After a failed attempt, two questions need answers: whether the operation can safely be repeated, and when the next attempt is allowed. A lost response may leave a message already created at the provider. Adding a delay before retrying does not remove the duplication risk.

The teaching provider explicitly returns kind=throttle, status=429, and accepted=false. Only that consistent response counts as a temporary refusal before acceptance. Missing evidence, contradictory fields, or an exception from the fake client produce unknown. Such a job leaves the automatic queue and requires reconciliation; a timer does not put it back into service.

Safely retrying a non-idempotent request requires a separate basis; RFC 9110 on idempotency does not allow that property to be inferred merely from a failed response. A real adapter must follow the contract of its particular method.

Every retry spends the local budgets again. The first refused request already contacted the provider. Free retries would silently bypass the very limit we are trying to respect.

Store the pause as an eligibility deadline

Retry-After may be a number of seconds or an HTTP date, as specified by RFC 9110. The teaching parser accepts seconds only in its fake protocol. HTTP-date conversion, clock differences, and multiple header values belong to a separate HTTP adapter.

In the example, 0 becomes a minimum local delay of one second. A missing hint uses our bounded backoff: two seconds, four seconds, then eight. This is a model choice, not an HTTP requirement. A negative number, fraction, exponent, or unsupported format does not turn into zero through an implicit type conversion.

An excessively long hint matters particularly. If our system is willing to wait automatically for at most a day, a larger interval must not be shortened to a minute and retried early. The model places the provider scope on a manual hold. This is a conservative choice; production could retain a longer deadline in suitable storage if the product supports that behaviour.

After a client pause until second 4, another client may attempt at second 1. After a shared provider pause until second 4, both wait. The model treats an unknown limiting scope as provider-wide to avoid bypassing it through another client.

The worker itself does not call sleep(): it records notBefore and returns control. The product scheduler must wake the work no earlier than that deadline. Model time is passed explicitly and cannot move backwards. The example implements neither a broker, durable timers, nor worker recovery.

The queue must accommodate what it promises

The model accepts at most six jobs in total and three per client. A fourth amber job receives an explicit admission refusal even when the shared queue is not full. This preserves room for blue. A retry retains the already accepted job's existing slot; it does not insert a new entry.

Job identifiers in this example are globally unique within one provider scope: the same value from another client also counts as a duplicate.

Every job has an expiry time. At that boundary it can no longer be sent, even if a slot has just become available. This matters for a notification that is useful only before an event begins. Stale work can finish as expired without being disguised as delivered.

After three confirmed temporary refusals, the model finishes the job as exhausted. Attempt budgets and expiry solve different problems: the former bounds requests, while the latter bounds the duration of the obligation. A retry counter does not replace a queue-capacity limit.

History also needs a retention policy. The teaching arrays of completed identifiers and attempts live until the end of a short run. Bounding the pending queue does not make those arrays indefinitely suitable for production. A real ledger needs an agreed retention period, a size limit, and a way to return the result of a person's request.

Check ordering and the reason for waiting

The PHP run executed 39 native cases within one PHPUnit test with 46 assertions; that test is included in the overall suite of 723 tests and 4,489 assertions. The cases cover round-robin selection among eligible clients, client and provider pauses, expiry boundaries, overflow, and retaining a slot during a retry. They also cover unknown effects, exhausted attempts, strict delay parsing, and backward time. The fake client records every call, making an early or extra attempt visible.

The example consists of FairQueue.php and tests.php. From the example directory, the prepared suite is invoked with:

php tests.php

These are deterministic checks of a single-process model, not a real-time benchmark or an HTTP test. Integration must cover shared budget storage, atomic job claims, concurrent workers, and recovery. Without that verification, the table must not be presented as the behaviour of a live queue or as proof of global fairness under concurrency.

Useful production observations include the oldest job's age for each client, the reason for notBefore, actual attempt counts, admission refusals, and unresolved deliveries. A single total queue length hides situations where most work is fast while one client keeps waiting. A well-defined policy makes that wait explainable: which resource is unavailable, until when, and which rule will select the next job.

  1. API API quota: accounting for concurrent requests without duplicate charges
  2. Platform Engineering Timeout after an external request: when the outcome is unknown
  3. Platform Engineering Importer backpressure: why a faster producer can make the system worse

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast