# Rate Limiting

**Parent**: [/python/opendeviationbar/CLAUDE.md](/python/opendeviationbar/CLAUDE.md) | **Hub**: [/CLAUDE.md](/CLAUDE.md)

File-based cross-process rate limit coordinator for Binance REST API weight budgets (D-11, D-13). Enables sidecar, kintsugi, and seeder to share the IP-wide 6000 weight/min limit without exceeding it.

---

## Files

| File                  | LOC  | Purpose                                                                                          |
| --------------------- | ---- | ------------------------------------------------------------------------------------------------ |
| `__init__.py`         | ~22  | Re-exports `RateLimitCoordinator` and budget constants                                           |
| `file_coordinator.py` | ~155 | `RateLimitCoordinator` class: atomic JSON state file, per-consumer weight tracking, stale expiry |

## Mechanism

Three concurrent processes (sidecar, kintsugi, seeder) share Binance's IP-wide 6000 weight/min REST API limit. Coordination uses an atomic JSON state file at `/tmp/opendeviationbar-ratelimit.json`:

1. **Report**: After each REST call, consumer calls `report_usage(consumer_id, weight_used)` to record weight consumed in the current 60-second window.
2. **Check**: Before acquiring budget, consumer calls `can_acquire(consumer_id, weight, budget)` to verify aggregate usage across all consumers won't exceed the limit.
3. **Atomicity**: State file is written via `tempfile + os.fsync + os.rename` (POSIX atomic rename) to prevent partial reads from concurrent processes.
4. **Stale expiry**: Entries older than `WINDOW_SECONDS + STALE_GRACE_SECONDS` (65 seconds) are ignored, so a crashed consumer doesn't permanently block others.

## Budget Allocation

| Consumer  | Budget (weight/min) | Constant          |
| --------- | ------------------- | ----------------- |
| Sidecar   | 2,400               | `BUDGET_SIDECAR`  |
| Kintsugi  | 2,000               | `BUDGET_KINTSUGI` |
| Seeder    | 800                 | `BUDGET_SEEDER`   |
| Reserve   | 800                 | `BUDGET_RESERVE`  |
| **Total** | **6,000**           |                   |

## Related

- [/python/opendeviationbar/CLAUDE.md](/python/opendeviationbar/CLAUDE.md) -- Parent spoke (Python API layer)
- [/CLAUDE.md](/CLAUDE.md) -- Project hub
- [/scripts/CLAUDE.md](/scripts/CLAUDE.md) -- Seeder and kintsugi scripts that consume rate limit budgets
