Skip to main content

What is Capacity Reservation?

Capacity reservation allows you to “book” rate limit capacity for future use. When you reserve capacity, you receive a retryAfter time at which you can execute your operation without re-checking the rate limit. This prevents starvation on larger requests and enables fair queueing of operations.

The Problem: Starvation

Without reservations, large requests can be repeatedly blocked:
Smaller requests can continuously consume available capacity, preventing large requests from ever succeeding.

The Solution: Reserve Capacity

With the reserve parameter, you can guarantee future execution:

How Reservations Work

  1. Check available capacity: The rate limiter checks if there’s enough capacity now or in the future
  2. Reserve tokens: If not immediately available, it reserves capacity at a future time
  3. Return retryAfter: You receive the exact time when your operation can run
  4. Execute without re-checking: At that time, skip the rate limit check

Complete Pattern with Scheduler

Here’s the recommended pattern for using reservations with ctx.scheduler:

The skipCheck Pattern

The skipCheck parameter is crucial:
Important: Always use skipCheck for scheduled executions after reserving capacity. Otherwise, you’ll check the rate limit twice and consume double the tokens.

Preventing Starvation

Reservations ensure fairness by queueing operations:
Each request gets a guaranteed execution time, preventing starvation.

Maximum Reservations

You can limit how far ahead capacity can be reserved:
When maxReserved is exceeded, ok will be false:

Use Cases

1. Large Batch Operations

2. Fair Queueing

3. LLM API Rate Limiting

Best Practices

  1. Always use skipCheck: When executing reserved capacity, always pass skipCheck: true
  2. Estimate conservatively: Reserve slightly more capacity than you think you’ll need
  3. Set maxReserved: Prevent unbounded queueing with maxReserved
  4. Handle scheduling failures: Check if scheduling succeeded and handle errors
  5. Use with actions: Reservations work best with internalAction for async operations
Reservations are particularly useful for preventing thundering herd problems. See the Jitter guide for more techniques to handle burst traffic.