What is Capacity Reservation?
Capacity reservation allows you to “book” rate limit capacity for future use. When you reserve capacity, you receive aretryAfter 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:The Solution: Reserve Capacity
With thereserve parameter, you can guarantee future execution:
How Reservations Work
- Check available capacity: The rate limiter checks if there’s enough capacity now or in the future
- Reserve tokens: If not immediately available, it reserves capacity at a future time
- Return retryAfter: You receive the exact time when your operation can run
- Execute without re-checking: At that time, skip the rate limit check
Complete Pattern with Scheduler
Here’s the recommended pattern for using reservations withctx.scheduler:
The skipCheck Pattern
TheskipCheck parameter is crucial:
Preventing Starvation
Reservations ensure fairness by queueing operations:Maximum Reservations
You can limit how far ahead capacity can be reserved:maxReserved is exceeded, ok will be false:
Use Cases
1. Large Batch Operations
2. Fair Queueing
3. LLM API Rate Limiting
Best Practices
- Always use skipCheck: When executing reserved capacity, always pass
skipCheck: true - Estimate conservatively: Reserve slightly more capacity than you think you’ll need
- Set maxReserved: Prevent unbounded queueing with
maxReserved - Handle scheduling failures: Check if scheduling succeeded and handle errors
- Use with actions: Reservations work best with
internalActionfor async operations
Reservations are particularly useful for preventing thundering herd problems. See the Jitter guide for more techniques to handle burst traffic.