FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
rate_limiter.hpp
Go to the documentation of this file.
1#pragma once
2// RateLimiter (6.4/6.5): client-side accounting of venue rate limits so we refuse to send
3// before the venue does. Two kinds of buckets:
4// * weight buckets - Binance REQUEST_WEIGHT per interval (X-MBX-USED-WEIGHT-1M),
5// Bybit per-endpoint X-Bapi-Limit / X-Bapi-Limit-Status;
6// * order-count buckets - Binance ORDERS per 10 s / per day (X-MBX-ORDER-COUNT-10S),
7// Bybit create/cancel per second per UID.
8// The venue's own counts (response headers, WS API rateLimits) correct the local estimate
9// (on_headers): raised to the venue's count, and lowered to it plus what was sent in the last
10// kHeaderLagNs, which the count may not include yet. Windows roll where the venue's do, on its
11// clock (set_clock_offset: Binance's minute and 10 s windows start on the UTC minute and second).
12// A cooldown (429 Retry-After, -1003, 10006) blocks every send until it expires, and a second one
13// soon after the first waits longer each time; a hard stop (418 IP ban) blocks until explicitly
14// cleared. Bulk requests (depth snapshots, history queries and order lookups, start-up queries one
15// per symbol: can_send with kBulkShare, then on_bulk_sent) check against kBulkShare of the weight,
16// and the bulk weight this limiter sent in the window (every account of the process, on a shared
17// IP) against that share paced over it (kBulkPaceFloor), so the rest of the window stays with the
18// orders and the bulk does not pile up at the start of each window. The pace counts bulk requests
19// only: orders and cancels are held by the total alone. Counted in the pace, a market maker's
20// orders early in a minute (540 weight of Binance's 6000 at the minute's start) held its own depth
21// snapshots, execution replays and the reconciliations waiting for them until late in the minute.
22// Nor does the pace count what other processes on the IP spent: a second process early in a
23// minute (a warm standby, a restart) would otherwise find the paced share spent by the first and
24// wait seconds for its first depth snapshot. Several accounts behind one IP (an account pool)
25// share the IP's weight: share_ip() points the weight buckets, the cooldown and the hard stop at
26// one SharedRate per host (shared_rate()), so a 429 seen by one account pauses them all; the
27// order-count buckets stay the account's.
28#include "fastmm/core/spin_mutex.hpp"
29
30#include <algorithm>
31#include <array>
32#include <cmath>
33#include <cstddef>
34#include <cstdint>
35#include <functional>
36#include <map>
37#include <memory>
38#include <mutex>
39#include <optional>
40#include <string>
41#include <string_view>
42
43namespace fastmm::venues {
44
45struct SharedRate;
46
47struct RateBucket {
48 std::uint32_t limit = 0; // 0 = unlimited
49 std::int64_t window_ns = 0; // fixed window length
50 std::uint32_t used = 0; // consumed in the current window
51 std::int64_t window_start = 0; // ns; the window rolls when now - window_start >= window_ns
52 bool active = false;
53 // The venue's clock minus the local one (RateLimiter::set_clock_offset): windows start where
54 // now + offset is a multiple of window_ns, as the venue's do.
55 std::int64_t offset = 0;
56 // What this limiter sent in the current window as bulk requests (RateLimiter::on_bulk_sent),
57 // which `used` includes: the venue's counts (calibrate) move `used` to the IP's, other
58 // processes' requests too, and leave this alone.
59 std::uint32_t bulk = 0;
60
61 // The start of the venue's window that holds `now`.
62 [[nodiscard]] std::int64_t aligned_start(std::int64_t now) const noexcept {
63 const std::int64_t r = (now + offset) % window_ns;
64 return now - (r < 0 ? r + window_ns : r);
65 }
66 void roll(std::int64_t now) noexcept {
67 if (window_ns > 0 && now - window_start >= window_ns) {
69 used = 0;
70 bulk = 0;
71 }
72 }
73 // A new clock offset: the window holding `now` starts where the venue's does. The count stays
74 // (the orders in it were sent within one window length of now either way).
75 void realign(std::int64_t off, std::int64_t now) noexcept {
76 offset = off;
77 if (window_ns <= 0) return;
78 if (now - window_start >= window_ns) {
79 roll(now);
80 } else {
82 }
83 }
84 [[nodiscard]] bool would_exceed(std::uint32_t add, double threshold) const noexcept {
85 if (limit == 0) return false;
86 return static_cast<double>(used + add) > static_cast<double>(limit) * threshold;
87 }
88 // The same for this limiter's own bulk weight in the window.
89 [[nodiscard]] bool bulk_would_exceed(std::uint32_t add, double threshold) const noexcept {
90 if (limit == 0) return false;
91 return static_cast<double>(bulk + add) > static_cast<double>(limit) * threshold;
92 }
93 // The venue's count `count` for this window, `recent` sent in the last kHeaderLagNs: raised to
94 // the count, lowered to count + recent. Ignored within `lag` of the window's start, where it may
95 // be the previous window's.
96 void calibrate(std::uint32_t count,
97 std::uint32_t recent,
98 std::int64_t now,
99 std::int64_t lag) noexcept {
100 roll(now);
101 if (window_ns > 0 && now - window_start < lag) return;
102 used = std::clamp(used, count, count + recent);
103 }
104};
105
106// What was sent in the last couple of seconds (RateLimiter::kHeaderLagNs), in 125 ms slots.
107class RecentSpend {
108 public:
109 static constexpr std::size_t kSlots = 32;
110 static constexpr std::int64_t kSlotNs = 125'000'000;
111 void add(std::uint32_t n, std::int64_t now) noexcept {
112 const std::int64_t t = now / kSlotNs;
113 Slot& s = slots_[static_cast<std::size_t>(t) % kSlots];
114 if (s.t != t) s = Slot{t, 0};
115 s.n += n;
116 }
117 // Sent from `now - lag` on (whole slots: a little more, never less).
118 [[nodiscard]] std::uint32_t since(std::int64_t now, std::int64_t lag) const noexcept {
119 const std::int64_t from = (now - lag) / kSlotNs - 1;
120 std::uint32_t sum = 0;
121 for (const Slot& s : slots_) {
122 if (s.t >= from && s.t <= now / kSlotNs) sum += s.n;
123 }
124 return sum;
125 }
126
127 private:
128 struct Slot {
129 std::int64_t t = -1;
130 std::uint32_t n = 0;
131 };
132 std::array<Slot, kSlots> slots_{};
133};
134
135// Why can_send refused (RateLimiter::check): the IP or account is paused (429 cooldown, 418), a
136// weight window is at its share, or an order-count window is (RateCheck::window_ns says which).
137enum class RateRefusal : std::uint8_t { None, Paused, Weight, Orders };
138struct RateCheck {
140 std::int64_t window_ns = 0; // Orders: the window at its threshold
141 [[nodiscard]] bool ok() const noexcept { return refusal == RateRefusal::None; }
144class RateLimiter {
145 public:
146 static constexpr std::size_t kMaxBuckets = 4;
147 // The part of each weight window a bulk request may fill (can_send's `share`): with 170
148 // symbols' snapshots and history queries sent as fast as they fit, the other half of the window
149 // still takes a cancel or a REST order.
150 static constexpr double kBulkShare = 0.5;
151 // A pause asked (429) within this long after the last one ended is the same incident going on:
152 // each such pause waits kBackoffBaseNs << n on top of Retry-After, up to kBackoffMaxNs. The
153 // venue's Retry-After names a second; a client back at once earns the next 429, then the ban.
154 static constexpr std::int64_t kStreakWindowNs = 60'000'000'000;
155 static constexpr std::int64_t kBackoffBaseNs = 1'000'000'000;
156 static constexpr std::int64_t kBackoffMaxNs = 120'000'000'000;
157 // The part of kBulkShare this limiter's own bulk weight in a window may fill before a bulk
158 // request grows with the time into the window, from this part at its start to all of it at its
159 // end: a backlog of history queries waiting for room no longer spends the share the moment the
160 // window opens, while the orders are busiest there.
161 static constexpr double kBulkPaceFloor = 0.2;
162 // How late a venue's count (on_headers) may be: what was sent in this long before it arrived
163 // may be missing from it.
164 static constexpr std::int64_t kHeaderLagNs = 2'000'000'000;
165
166 explicit RateLimiter(double threshold = 0.9) noexcept
167 : threshold_(threshold), order_threshold_(threshold) {}
169 // The IP's weight, cooldown and hard stop live in `ip` from now on (null: this limiter's own).
170 void share_ip(std::shared_ptr<SharedRate> ip) noexcept;
171
172 // Buckets are added at startup from exchangeInfo.rateLimits / the Bybit rate limit table.
173 bool add_weight_bucket(std::uint32_t limit, std::int64_t window_ns) noexcept {
174 if (ip_) return ip_add_weight_bucket(limit, window_ns);
175 return add(weight_, limit, window_ns, offset_);
176 }
177 bool add_order_bucket(std::uint32_t limit, std::int64_t window_ns) noexcept {
178 return add(orders_, limit, window_ns, offset_);
180 // The account's own limit on the order-count window of `window_ns` (Binance raises it per
181 // account, which exchangeInfo does not show): the bucket of that length takes it and keeps its
182 // count, or one is added. False when the bucket already had that limit, or there is no room.
183 bool set_order_limit(std::uint32_t limit, std::int64_t window_ns) noexcept {
184 for (RateBucket& b : orders_) {
185 if (!b.active || b.window_ns != window_ns) continue;
186 if (b.limit == limit) return false;
187 b.limit = limit;
188 return true;
189 }
190 return add(orders_, limit, window_ns, offset_);
191 }
192 // The venue's clock minus the local (now) clock, ns: every window, the IP's included, rolls
193 // where the venue's does from now on. 0 (the default): windows of the local clock.
194 void set_clock_offset(std::int64_t venue_minus_local_ns, std::int64_t now) noexcept;
195 void set_threshold(double t) noexcept { threshold_ = std::clamp(t, 0.0, 1.0); }
196 // The share of each order-count limit (ORDERS buckets) can_send fills; the weight keeps
197 // threshold(). An order count past its limit costs a refused order, the weight a ban.
198 void set_order_threshold(double t) noexcept { order_threshold_ = std::clamp(t, 0.0, 1.0); }
199 [[nodiscard]] double order_threshold() const noexcept { return order_threshold_; }
200 // The share of each limit can_send fills before it refuses.
201 [[nodiscard]] double threshold() const noexcept { return threshold_; }
202 // The count a bucket of `limit` admits under that share: can_send refuses the order or request
203 // that would take `used` past it (RateBucket::would_exceed).
204 [[nodiscard]] std::int64_t cap_of(std::uint32_t limit) const noexcept {
205 return static_cast<std::int64_t>(std::floor(static_cast<double>(limit) * threshold_));
207 // cap_of for an order-count bucket.
208 [[nodiscard]] std::int64_t order_cap_of(std::uint32_t limit) const noexcept {
209 return static_cast<std::int64_t>(std::floor(static_cast<double>(limit) * order_threshold_));
211
212 // True if a request of `weight` (and one order if is_order) fits under threshold * limit
213 // in every bucket and no cooldown/hard stop is active. `share` < 1 (kBulkShare) leaves that
214 // part of each weight window to other requests.
215 [[nodiscard]] bool can_send(std::uint32_t weight,
216 std::int64_t now,
217 bool is_order = false,
218 double share = 1.0) noexcept {
219 return check(weight, now, is_order, share).ok();
220 }
221 // can_send, saying which limit refused.
222 [[nodiscard]] RateCheck check(std::uint32_t weight,
223 std::int64_t now,
224 bool is_order = false,
225 double share = 1.0) noexcept {
226 const RateRefusal w = ip_ ? ip_weight_fits(weight, now, share)
227 : weight_fits(weight, now, threshold_ * share, share < 1.0);
228 if (w != RateRefusal::None) return {w, 0};
229 if (is_order) {
230 for (RateBucket& b : orders_) {
231 if (!b.active) continue;
232 b.roll(now);
233 if (b.would_exceed(1, order_threshold_)) return {RateRefusal::Orders, b.window_ns};
234 }
235 }
236 return {};
237 }
238
239 // Local accounting after a send.
240 void on_sent(std::uint32_t weight, std::int64_t now, bool is_order = false) noexcept {
241 sent(weight, now, is_order, false);
243 // on_sent for a bulk request (one can_send checked against kBulkShare): its weight counts in the
244 // bulk pace as well as in the total.
245 void on_bulk_sent(std::uint32_t weight, std::int64_t now) noexcept {
246 sent(weight, now, false, true);
248
249 // The venue's counts from a response (RateBucket::calibrate). `bucket` selects the window
250 // (index in insertion order); negative values are ignored (header absent).
251 void on_headers(std::int64_t used_weight,
252 std::int64_t order_count,
253 std::int64_t now,
254 std::size_t weight_bucket = 0,
255 std::size_t order_bucket = 0) noexcept {
256 if (used_weight >= 0 && ip_) {
257 ip_on_headers(used_weight, now, weight_bucket);
258 } else if (used_weight >= 0 && weight_bucket < weight_.size() &&
259 weight_[weight_bucket].active) {
260 weight_[weight_bucket].calibrate(static_cast<std::uint32_t>(used_weight),
261 recent_weight_.since(now, kHeaderLagNs),
262 now,
264 }
265 if (order_count >= 0 && order_bucket < orders_.size() && orders_[order_bucket].active) {
266 orders_[order_bucket].calibrate(static_cast<std::uint32_t>(order_count),
267 recent_orders_.since(now, kHeaderLagNs),
268 now,
270 }
271 }
272 // The venue's order count on the window of `window_ns` (WS API rateLimits[], which name each
273 // window), calibrated as on_headers does; ignored when no bucket has that length.
274 void on_order_count(std::int64_t count, std::int64_t window_ns, std::int64_t now) noexcept {
275 if (count < 0) return;
276 for (RateBucket& b : orders_) {
277 if (!b.active || b.window_ns != window_ns) continue;
278 b.calibrate(static_cast<std::uint32_t>(count),
279 recent_orders_.since(now, kHeaderLagNs),
280 now,
282 return;
283 }
284 }
285 // Bybit style: remaining requests for this endpoint (X-Bapi-Limit-Status) and the limit.
286 void on_remaining(std::int64_t limit, std::int64_t remaining, std::int64_t now) noexcept {
287 if (limit < 0 || remaining < 0 || weight_.empty() || !weight_[0].active) return;
288 RateBucket& b = weight_[0];
289 b.roll(now);
290 b.limit = static_cast<std::uint32_t>(limit);
291 b.used = static_cast<std::uint32_t>(std::max<std::int64_t>(0, limit - remaining));
292 }
293
294 // 429 / -1003 / 10006: block sends until now + retry_after, or longer when the last pause
295 // ended less than kStreakWindowNs ago (the streak). A pause asked while one is on only extends
296 // it: the answers to the requests already in flight are one incident.
297 void cooldown(std::int64_t retry_after_ns, std::int64_t now) noexcept {
298 if (ip_) {
299 ++cooldowns_; // this account's count of the pauses it was asked for
300 return ip_cooldown(retry_after_ns, now);
301 }
302 if (now >= cooldown_until_) {
303 streak_ = cooldowns_ > 0 && now - cooldown_until_ <= kStreakWindowNs ? streak_ + 1 : 0;
304 }
305 const std::int64_t backoff =
306 streak_ == 0 ? 0 : std::min(kBackoffMaxNs, kBackoffBaseNs << std::min(streak_, 20U));
307 cooldown_until_ = std::max(cooldown_until_, now + std::max(retry_after_ns, backoff));
308 ++cooldowns_;
309 }
310 [[nodiscard]] std::int64_t cooldown_until() const noexcept;
311 // Pauses in the current streak after the first.
312 [[nodiscard]] std::uint32_t streak() const noexcept;
313 [[nodiscard]] bool in_cooldown(std::int64_t now) const noexcept { return now < cooldown_until(); }
314
315 // 418: the IP is banned; stop REST entirely until an operator clears it.
316 void hard_stop() noexcept;
317 void clear_hard_stop() noexcept;
318 [[nodiscard]] bool hard_stopped() const noexcept;
319
320 [[nodiscard]] std::uint64_t cooldowns() const noexcept { return cooldowns_; }
321 // Copies of the i-th bucket (insertion order), empty past the last; a shared IP's is copied
322 // under its lock, since the other accounts' threads write it.
323 [[nodiscard]] std::optional<RateBucket> weight_bucket(std::size_t i) const noexcept;
324 [[nodiscard]] std::optional<RateBucket> order_bucket(std::size_t i) const noexcept {
325 if (i < orders_.size() && orders_[i].active) return orders_[i];
326 return std::nullopt;
327 }
328
329 private:
330 static bool add(std::array<RateBucket, kMaxBuckets>& arr,
331 std::uint32_t limit,
332 std::int64_t window_ns,
333 std::int64_t offset) noexcept {
334 for (RateBucket& b : arr) {
335 if (b.active) continue;
336 b = RateBucket{limit, window_ns, 0, 0, true, offset, 0};
337 return true;
338 }
339 return false;
340 }
341
342 void sent(std::uint32_t weight, std::int64_t now, bool is_order, bool bulk) noexcept {
343 if (ip_) {
344 ip_on_sent(weight, now, bulk);
345 } else {
346 spend(weight_, weight, now, bulk);
347 recent_weight_.add(weight, now);
348 }
349 if (is_order) {
350 spend(orders_, 1, now, false);
351 recent_orders_.add(1, now);
352 }
353 }
354 static void spend(std::array<RateBucket, kMaxBuckets>& arr,
355 std::uint32_t n,
356 std::int64_t now,
357 bool bulk) noexcept {
358 for (RateBucket& b : arr) {
359 if (!b.active) continue;
360 b.roll(now);
361 b.used += n;
362 if (bulk) b.bulk += n;
363 }
364 }
365 // This limiter's own weight: no cooldown or hard stop, and `weight` under threshold * limit;
366 // `paced` (a bulk request): the bulk weight this limiter sent in the window, too, under the part
367 // of it the time into the window allows (kBulkPaceFloor). A shared IP calls it on SharedRate::r
368 // under the lock.
369 RateRefusal weight_fits(std::uint32_t weight,
370 std::int64_t now,
371 double threshold,
372 bool paced) noexcept {
373 if (hard_stopped_ || now < cooldown_until_) return RateRefusal::Paused;
374 for (RateBucket& b : weight_) {
375 if (!b.active) continue;
376 b.roll(now);
377 if (b.would_exceed(weight, threshold)) return RateRefusal::Weight;
378 if (paced && b.window_ns > 0) {
379 const double into =
380 static_cast<double>(now - b.window_start) / static_cast<double>(b.window_ns);
381 if (b.bulk_would_exceed(weight, threshold * std::clamp(into, kBulkPaceFloor, 1.0)))
382 return RateRefusal::Weight;
383 }
384 }
385 return RateRefusal::None;
386 }
387 // Adds a weight bucket unless one of the same limit and window is there: each account that
388 // shares an IP adds the same buckets, in the same order (on_headers' index).
389 bool add_weight_bucket_once(std::uint32_t limit, std::int64_t window_ns) noexcept {
390 for (const RateBucket& b : weight_) {
391 if (b.active && b.limit == limit && b.window_ns == window_ns) return true;
392 }
393 return add(weight_, limit, window_ns, offset_);
394 }
395
396 // The IP-wide parts, under SharedRate's lock (defined below).
397 RateRefusal ip_weight_fits(std::uint32_t weight, std::int64_t now, double share) noexcept;
398 void ip_on_sent(std::uint32_t weight, std::int64_t now, bool bulk) noexcept;
399 void ip_on_headers(std::int64_t used, std::int64_t now, std::size_t bucket) noexcept;
400 bool ip_add_weight_bucket(std::uint32_t limit, std::int64_t window_ns) noexcept;
401 void ip_cooldown(std::int64_t retry_after_ns, std::int64_t now) noexcept;
402
403 double threshold_;
404 double order_threshold_;
405 std::shared_ptr<SharedRate> ip_;
406 std::array<RateBucket, kMaxBuckets> weight_{};
407 std::array<RateBucket, kMaxBuckets> orders_{};
408 RecentSpend recent_weight_; // this limiter's own weight (a shared IP's lives in its limiter)
409 RecentSpend recent_orders_;
410 std::int64_t offset_ = 0; // set_clock_offset
411 std::int64_t cooldown_until_ = 0;
412 std::uint64_t cooldowns_ = 0;
413 std::uint32_t streak_ = 0;
414 bool hard_stopped_ = false;
415};
416
417// One IP's request weight, shared by every account that sends from it (RateLimiter::share_ip).
418struct SharedRate {
419 // Every order of every account on the IP takes it twice (ip_weight_fits, ip_on_sent), from
420 // their network threads at once when a requote spreads over the pool: a spinning lock, so a
421 // waiter does not sleep in the kernel for a section of a few dozen nanoseconds.
422 SpinMutex m;
423 RateLimiter r{1.0}; // its weight buckets, cooldown and hard stop; never shared itself
426// The key of one IP's weight at one venue: the connector kind, its REST host and the address its
427// connections leave from (net::source_label; empty: the host's default), so accounts sending
428// from different addresses count apart and those sending from the same one count together.
429[[nodiscard]] inline std::string ip_weight_key(std::string_view kind,
430 std::string_view rest_url,
431 std::string_view source) {
432 std::string key(kind);
433 key += ' ';
434 key += rest_url;
435 if (!source.empty()) {
436 key += " from ";
437 key += source;
438 }
439 return key;
440}
441
442// The SharedRate of `key` (ip_weight_key), made on first use; process-wide.
443inline std::shared_ptr<SharedRate> shared_rate(std::string_view key) {
444 static std::mutex m;
445 static std::map<std::string, std::shared_ptr<SharedRate>, std::less<>> by_key;
446 const std::lock_guard<std::mutex> lock(m);
447 auto it = by_key.find(key);
448 if (it == by_key.end())
449 it = by_key.emplace(std::string(key), std::make_shared<SharedRate>()).first;
450 return it->second;
451}
452
453inline void RateLimiter::share_ip(std::shared_ptr<SharedRate> ip) noexcept {
454 if (ip) {
455 const std::lock_guard<SpinMutex> lock(ip->m);
456 for (const RateBucket& b : weight_) {
457 if (b.active) static_cast<void>(ip->r.add_weight_bucket_once(b.limit, b.window_ns));
458 }
459 }
460 ip_ = std::move(ip);
461}
462inline RateRefusal RateLimiter::ip_weight_fits(std::uint32_t weight,
463 std::int64_t now,
464 double share) noexcept {
465 const std::lock_guard<SpinMutex> lock(ip_->m);
466 return ip_->r.weight_fits(weight, now, threshold_ * share, share < 1.0);
467}
468inline void RateLimiter::ip_on_sent(std::uint32_t weight, std::int64_t now, bool bulk) noexcept {
469 const std::lock_guard<SpinMutex> lock(ip_->m);
470 spend(ip_->r.weight_, weight, now, bulk);
471 ip_->r.recent_weight_.add(weight, now);
472}
473inline void RateLimiter::ip_on_headers(std::int64_t used,
474 std::int64_t now,
475 std::size_t bucket) noexcept {
476 // The IP's count when the venue answered one account: every account's requests of the last
477 // kHeaderLagNs may be missing from it, so it lowers the shared estimate only to the count plus
478 // those (an older answer lowering it further would let their concurrent burst through).
479 const std::lock_guard<SpinMutex> lock(ip_->m);
480 auto& w = ip_->r.weight_;
481 if (bucket >= w.size() || !w[bucket].active) return;
482 w[bucket].calibrate(static_cast<std::uint32_t>(used),
483 ip_->r.recent_weight_.since(now, kHeaderLagNs),
484 now,
485 kHeaderLagNs);
486}
487inline void RateLimiter::set_clock_offset(std::int64_t venue_minus_local_ns,
488 std::int64_t now) noexcept {
489 offset_ = venue_minus_local_ns;
490 for (RateBucket& b : orders_) {
491 if (b.active) b.realign(offset_, now);
492 }
493 if (!ip_) {
494 for (RateBucket& b : weight_) {
495 if (b.active) b.realign(offset_, now);
496 }
497 return;
498 }
499 const std::lock_guard<SpinMutex> lock(ip_->m);
500 ip_->r.offset_ = offset_;
501 for (RateBucket& b : ip_->r.weight_) {
502 if (b.active) b.realign(offset_, now);
503 }
504}
505inline bool RateLimiter::ip_add_weight_bucket(std::uint32_t limit,
506 std::int64_t window_ns) noexcept {
507 const std::lock_guard<SpinMutex> lock(ip_->m);
508 return ip_->r.add_weight_bucket_once(limit, window_ns);
509}
510inline void RateLimiter::ip_cooldown(std::int64_t retry_after_ns, std::int64_t now) noexcept {
511 const std::lock_guard<SpinMutex> lock(ip_->m);
512 ip_->r.cooldown(retry_after_ns, now);
513}
514inline std::int64_t RateLimiter::cooldown_until() const noexcept {
515 if (!ip_) return cooldown_until_;
516 const std::lock_guard<SpinMutex> lock(ip_->m);
517 return ip_->r.cooldown_until_;
518}
519inline void RateLimiter::hard_stop() noexcept {
520 if (!ip_) {
521 hard_stopped_ = true;
522 return;
523 }
524 const std::lock_guard<SpinMutex> lock(ip_->m);
525 ip_->r.hard_stopped_ = true;
526}
527inline void RateLimiter::clear_hard_stop() noexcept {
528 if (!ip_) {
529 hard_stopped_ = false;
530 return;
531 }
532 const std::lock_guard<SpinMutex> lock(ip_->m);
533 ip_->r.hard_stopped_ = false;
534}
535inline std::optional<RateBucket> RateLimiter::weight_bucket(std::size_t i) const noexcept {
536 if (!ip_) {
537 if (i < weight_.size() && weight_[i].active) return weight_[i];
538 return std::nullopt;
539 }
540 const std::lock_guard<SpinMutex> lock(ip_->m);
541 return ip_->r.weight_bucket(i);
542}
543inline std::uint32_t RateLimiter::streak() const noexcept {
544 if (!ip_) return streak_;
545 const std::lock_guard<SpinMutex> lock(ip_->m);
546 return ip_->r.streak_;
547}
548inline bool RateLimiter::hard_stopped() const noexcept {
549 if (!ip_) return hard_stopped_;
550 const std::lock_guard<SpinMutex> lock(ip_->m);
551 return ip_->r.hard_stopped_;
552}
553
554// A blocking start-up request (reference data, account settings, one per symbol) waits for its
555// weight to fit the bulk share instead of spending what the connections about to open will need;
556// at most `max_wait_ns`, since nothing trades yet and a window is a minute.
557template <class Sleep>
559 std::uint32_t weight,
560 std::int64_t now_ns,
561 std::int64_t max_wait_ns,
562 Sleep&& sleep_ns) noexcept {
563 const std::int64_t until = now_ns + max_wait_ns;
564 std::int64_t now = now_ns;
565 while (now < until && !r.can_send(weight, now, false, RateLimiter::kBulkShare)) {
566 constexpr std::int64_t kStep = 100'000'000;
567 sleep_ns(kStep);
568 now += kStep;
569 }
570}
571
572} // namespace fastmm::venues
Definition rate_limiter.hpp:146
static constexpr std::size_t kMaxBuckets
Definition rate_limiter.hpp:148
void hard_stop() noexcept
418: the IP is banned; stop REST entirely until an operator clears it.
Definition rate_limiter.hpp:521
bool add_weight_bucket(std::uint32_t limit, std::int64_t window_ns) noexcept
Buckets are added at startup from exchangeInfo.rateLimits / the Bybit rate limit table.
Definition rate_limiter.hpp:175
bool set_order_limit(std::uint32_t limit, std::int64_t window_ns) noexcept
The account's own limit on the order-count window of window_ns (Binance raises it per account,...
Definition rate_limiter.hpp:185
static constexpr std::int64_t kStreakWindowNs
A pause asked (429) within this long after the last one ended is the same incident going on: each suc...
Definition rate_limiter.hpp:156
static constexpr double kBulkShare
The part of each weight window a bulk request may fill (can_send's share): with 170 symbols' snapshot...
Definition rate_limiter.hpp:152
bool can_send(std::uint32_t weight, std::int64_t now, bool is_order=false, double share=1.0) noexcept
True if a request of weight (and one order if is_order) fits under threshold * limit in every bucket ...
Definition rate_limiter.hpp:217
bool add_order_bucket(std::uint32_t limit, std::int64_t window_ns) noexcept
Definition rate_limiter.hpp:179
bool in_cooldown(std::int64_t now) const noexcept
Definition rate_limiter.hpp:315
void clear_hard_stop() noexcept
Definition rate_limiter.hpp:529
std::uint64_t cooldowns() const noexcept
Definition rate_limiter.hpp:322
void set_threshold(double t) noexcept
Definition rate_limiter.hpp:197
void on_sent(std::uint32_t weight, std::int64_t now, bool is_order=false) noexcept
Local accounting after a send.
Definition rate_limiter.hpp:242
static constexpr double kBulkPaceFloor
The part of kBulkShare this limiter's own bulk weight in a window may fill before a bulk request grow...
Definition rate_limiter.hpp:163
void on_remaining(std::int64_t limit, std::int64_t remaining, std::int64_t now) noexcept
Bybit style: remaining requests for this endpoint (X-Bapi-Limit-Status) and the limit.
Definition rate_limiter.hpp:288
double threshold() const noexcept
The share of each limit can_send fills before it refuses.
Definition rate_limiter.hpp:203
std::int64_t cap_of(std::uint32_t limit) const noexcept
The count a bucket of limit admits under that share: can_send refuses the order or request that would...
Definition rate_limiter.hpp:206
std::optional< RateBucket > order_bucket(std::size_t i) const noexcept
Definition rate_limiter.hpp:326
void set_clock_offset(std::int64_t venue_minus_local_ns, std::int64_t now) noexcept
The venue's clock minus the local (now) clock, ns: every window, the IP's included,...
Definition rate_limiter.hpp:489
bool hard_stopped() const noexcept
Definition rate_limiter.hpp:550
void cooldown(std::int64_t retry_after_ns, std::int64_t now) noexcept
429 / -1003 / 10006: block sends until now + retry_after, or longer when the last pause ended less th...
Definition rate_limiter.hpp:299
std::uint32_t streak() const noexcept
Pauses in the current streak after the first.
Definition rate_limiter.hpp:545
void on_order_count(std::int64_t count, std::int64_t window_ns, std::int64_t now) noexcept
The venue's order count on the window of window_ns (WS API rateLimits[], which name each window),...
Definition rate_limiter.hpp:276
void on_bulk_sent(std::uint32_t weight, std::int64_t now) noexcept
on_sent for a bulk request (one can_send checked against kBulkShare): its weight counts in the bulk p...
Definition rate_limiter.hpp:247
RateCheck check(std::uint32_t weight, std::int64_t now, bool is_order=false, double share=1.0) noexcept
can_send, saying which limit refused.
Definition rate_limiter.hpp:224
static constexpr std::int64_t kBackoffBaseNs
Definition rate_limiter.hpp:157
static constexpr std::int64_t kBackoffMaxNs
Definition rate_limiter.hpp:158
std::optional< RateBucket > weight_bucket(std::size_t i) const noexcept
Copies of the i-th bucket (insertion order), empty past the last; a shared IP's is copied under its l...
Definition rate_limiter.hpp:537
static constexpr std::int64_t kHeaderLagNs
How late a venue's count (on_headers) may be: what was sent in this long before it arrived may be mis...
Definition rate_limiter.hpp:166
void on_headers(std::int64_t used_weight, std::int64_t order_count, std::int64_t now, std::size_t weight_bucket=0, std::size_t order_bucket=0) noexcept
The venue's counts from a response (RateBucket::calibrate).
Definition rate_limiter.hpp:253
void set_order_threshold(double t) noexcept
The share of each order-count limit (ORDERS buckets) can_send fills; the weight keeps threshold().
Definition rate_limiter.hpp:200
std::int64_t cooldown_until() const noexcept
Definition rate_limiter.hpp:516
double order_threshold() const noexcept
Definition rate_limiter.hpp:201
std::int64_t order_cap_of(std::uint32_t limit) const noexcept
cap_of for an order-count bucket.
Definition rate_limiter.hpp:210
void share_ip(std::shared_ptr< SharedRate > ip) noexcept
The IP's weight, cooldown and hard stop live in ip from now on (null: this limiter's own).
Definition rate_limiter.hpp:455
static constexpr std::int64_t kSlotNs
Definition rate_limiter.hpp:112
static constexpr std::size_t kSlots
Definition rate_limiter.hpp:111
std::uint32_t since(std::int64_t now, std::int64_t lag) const noexcept
Sent from now - lag on (whole slots: a little more, never less).
Definition rate_limiter.hpp:120
void add(std::uint32_t n, std::int64_t now) noexcept
Definition rate_limiter.hpp:113
Definition venue.hpp:39
std::string ip_weight_key(std::string_view kind, std::string_view rest_url, std::string_view source)
The key of one IP's weight at one venue: the connector kind, its REST host and the address its connec...
Definition rate_limiter.hpp:431
void wait_for_weight(RateLimiter &r, std::uint32_t weight, std::int64_t now_ns, std::int64_t max_wait_ns, Sleep &&sleep_ns) noexcept
A blocking start-up request (reference data, account settings, one per symbol) waits for its weight t...
Definition rate_limiter.hpp:560
RateRefusal
Why can_send refused (RateLimiter::check): the IP or account is paused (429 cooldown,...
Definition rate_limiter.hpp:139
@ None
not a multicast venue
std::shared_ptr< SharedRate > shared_rate(std::string_view key)
The SharedRate of key (ip_weight_key), made on first use; process-wide.
Definition rate_limiter.hpp:445
Definition rate_limiter.hpp:49
void calibrate(std::uint32_t count, std::uint32_t recent, std::int64_t now, std::int64_t lag) noexcept
The venue's count count for this window, recent sent in the last kHeaderLagNs: raised to the count,...
Definition rate_limiter.hpp:98
void roll(std::int64_t now) noexcept
Definition rate_limiter.hpp:68
bool would_exceed(std::uint32_t add, double threshold) const noexcept
Definition rate_limiter.hpp:86
std::int64_t offset
The venue's clock minus the local one (RateLimiter::set_clock_offset): windows start where now + offs...
Definition rate_limiter.hpp:57
bool active
Definition rate_limiter.hpp:54
std::int64_t window_start
ns; the window rolls when now - window_start >= window_ns
Definition rate_limiter.hpp:53
void realign(std::int64_t off, std::int64_t now) noexcept
A new clock offset: the window holding now starts where the venue's does.
Definition rate_limiter.hpp:77
std::uint32_t bulk
What this limiter sent in the current window as bulk requests (RateLimiter::on_bulk_sent),...
Definition rate_limiter.hpp:61
std::uint32_t used
consumed in the current window
Definition rate_limiter.hpp:52
std::int64_t aligned_start(std::int64_t now) const noexcept
The start of the venue's window that holds now.
Definition rate_limiter.hpp:64
bool bulk_would_exceed(std::uint32_t add, double threshold) const noexcept
The same for this limiter's own bulk weight in the window.
Definition rate_limiter.hpp:91
std::int64_t window_ns
fixed window length
Definition rate_limiter.hpp:51
std::uint32_t limit
0 = unlimited
Definition rate_limiter.hpp:50
Definition rate_limiter.hpp:140
bool ok() const noexcept
Definition rate_limiter.hpp:143
RateRefusal refusal
Definition rate_limiter.hpp:141
std::int64_t window_ns
Orders: the window at its threshold.
Definition rate_limiter.hpp:142
SpinMutex m
Every order of every account on the IP takes it twice (ip_weight_fits, ip_on_sent),...
Definition rate_limiter.hpp:424
RateLimiter r
its weight buckets, cooldown and hard stop; never shared itself
Definition rate_limiter.hpp:425