Skip to the workspace
Pebellslearn by building
Queues  ›  Lesson

Rate Limiting — Let the Queue Set the Pace

Rate Limiting 15 minA queue absorbs bursts while consumer batch size, max concurrency and delayed retries with backoff keep calls to a rate-limited service under its limit.

cloudflare / Rate Limiting — Let the Queue Set the Pace

Explore each scene at your own pace.

01 · The rule

The rule

Rate Limiting — Let the Queue Set the Pace

Hoplink checks every new target URL against an outside link-safety service before the preview goes live. The service allows 20 requests per second and answers 429 Too Many Requests beyond that. On a quiet day that is plenty. Then a partner imports 30,000 links at once — and the safety service starts refusing almost every call. The queue is where you control the pace.

The rule

Size the batch, cap the consumers, back off on refusal.

A queue already absorbs bursts: producers can send 30,000 messages in a minute, and they simply wait. How fast they leave is set by three consumer controls:

{
  "queues": {
    "consumers": [{
      "queue": "safety-checks",
      "max_batch_size": 10,
      "max_concurrency": 2,
      "max_retries": 5
    }]
  }
}
  • max_batch_size — how many messages one consumer invocation receives.
  • max_concurrency — how many consumer invocations may run at the same time. By default the platform scales consumers up automatically when the backlog grows; setting a cap stops it from overwhelming whatever sits downstream.
  • Backing off — when the service answers 429, do not hammer it. Retry the message later with a delay:
async queue(batch, env) {
  for (const msg of batch.messages) {
    const res = await fetch("https://safety.example/check", {
      method: "POST", body: JSON.stringify({ url: msg.body.url }),
    });
    if (res.status === 429) {
      msg.retry({ delaySeconds: 30 * msg.attempts });   // wait longer each time
    } else {
      await saveVerdict(env, msg.body.code, await res.json());
      msg.ack();
    }
  }
}

msg.attempts counts deliveries, so the wait grows with each refusal — a simple form of backoff.

The worst-case rate is roughly concurrency × batch size ÷ time per batch. Two consumers, each handling ten checks one after another at about a second per check, send around two requests per second, comfortably below the limit. Raise the numbers step by step while watching for 429s.

(For limiting incoming traffic — say, one visitor creating hundreds of links a minute — Workers offer a separate Rate Limiting binding, or you can count requests in a Durable Object. That protects you; the queue settings protect services you call.)

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.