Skip to main content

df_hyperliquid_core/client/http/
limit.rs

1//! Request weights against Hyperliquid's rate limit (the docs' "Rate limits
2//! and user limits"), the last minute's spend, and the gate a 429 closes. No
3//! clock and no I/O: every call is handed the time.
4
5use std::collections::VecDeque;
6
7/// Weight a minute per IP, reads and actions together.
8pub const LIMIT: u32 = 1_200;
9
10/// What reads may spend of [`LIMIT`] a minute before they wait. The last fifth
11/// is left to actions, which never wait, and to other clients on the same IP.
12pub const SOFT: u32 = LIMIT / 5 * 4;
13
14/// The window every figure here is over.
15pub const WINDOW_MS: u64 = 60_000;
16
17/// The first cooldown a 429 closes the gate for; each strike doubles it.
18pub const BASE_COOLDOWN_MS: u64 = 2_000;
19
20/// The longest cooldown a strike sets, though a `Retry-After` may ask longer.
21pub const MAX_COOLDOWN_MS: u64 = 60_000;
22
23const MAX_STRIKES: u32 = 6;
24
25/// An `/info` read's weight before counting what it returns.
26#[must_use]
27pub fn base_weight(kind: &str) -> u32 {
28    match kind {
29        "l2Book" | "allMids" | "clearinghouseState" | "orderStatus" | "spotClearinghouseState" | "exchangeStatus" => 2,
30        "userRole" => 60,
31        _ => 20,
32    }
33}
34
35/// For the reads that charge for what they return: how many items add one
36/// unit of weight.
37#[must_use]
38pub fn per_items(kind: &str) -> Option<usize> {
39    match kind {
40        "recentTrades"
41        | "historicalOrders"
42        | "userFills"
43        | "userFillsByTime"
44        | "fundingHistory"
45        | "userFunding"
46        | "nonUserFundingUpdates"
47        | "twapHistory"
48        | "userTwapSliceFills"
49        | "userTwapSliceFillsByTime"
50        | "delegatorHistory"
51        | "delegatorRewards"
52        | "validatorStats" => Some(20),
53        "candleSnapshot" => Some(60),
54        _ => None,
55    }
56}
57
58/// A read of `kind` that returned `items`.
59#[must_use]
60pub fn read_weight(kind: &str, items: usize) -> u32 {
61    let extra = per_items(kind).map_or(0, |per| items / per);
62    base_weight(kind).saturating_add(u32::try_from(extra).unwrap_or(u32::MAX))
63}
64
65/// An action batching `batched` orders, cancels or modifies: 1, plus 1 per 40.
66#[must_use]
67pub fn action_weight(batched: usize) -> u32 {
68    1u32.saturating_add(u32::try_from(batched / 40).unwrap_or(u32::MAX))
69}
70
71/// What went out over the last minute.
72#[derive(Debug, Clone, PartialEq, Eq)]
73#[non_exhaustive]
74pub struct Spent {
75    /// The weight allowed a minute per IP: [`LIMIT`].
76    pub limit: u32,
77    /// The weight sent over the last minute, all kinds together.
78    pub minute: u32,
79    /// By kind, the heaviest first.
80    pub kinds: Vec<Kind>,
81    /// 429s over the last minute.
82    pub refused: u32,
83    /// How long the gate stays closed; 0 when it is open.
84    pub cooldown_ms: u64,
85}
86
87/// One kind of request in [`Spent`] and what it spent over the last minute.
88#[derive(Debug, Clone, PartialEq, Eq)]
89#[non_exhaustive]
90pub struct Kind {
91    /// The `/info` read's `type`, such as `l2Book`, or `exchange` for every action.
92    pub name: String,
93    /// How many went out.
94    pub count: u32,
95    /// Their weight added up.
96    pub weight: u32,
97}
98
99/// The last minute of requests: when each went out, its kind and weight; and
100/// when each refusal came.
101#[derive(Debug, Default)]
102pub(crate) struct Meter {
103    sent: VecDeque<(u64, String, u32)>,
104    refused: VecDeque<u64>,
105}
106
107impl Meter {
108    /// Drops what is a whole window old at `now`.
109    fn prune(&mut self, now: u64) {
110        let gone = |at: u64| at.saturating_add(WINDOW_MS) <= now;
111        while self.sent.front().is_some_and(|(at, _, _)| gone(*at)) {
112            self.sent.pop_front();
113        }
114        while self.refused.front().is_some_and(|at| gone(*at)) {
115            self.refused.pop_front();
116        }
117    }
118
119    pub(crate) fn record(&mut self, now: u64, kind: &str, weight: u32) {
120        self.prune(now);
121        self.sent.push_back((now, kind.to_owned(), weight));
122    }
123
124    pub(crate) fn refuse(&mut self, now: u64) {
125        self.prune(now);
126        self.refused.push_back(now);
127    }
128
129    /// How long a read of `need` waits at `now`, so the last minute stays
130    /// within [`SOFT`]: none while it fits, else until enough has rolled off.
131    pub(crate) fn wait_for(&mut self, now: u64, need: u32) -> Option<u64> {
132        self.prune(now);
133        let spent = self.sent.iter().fold(0u32, |sum, (_, _, weight)| sum.saturating_add(*weight));
134        let mut over = spent.saturating_add(need).checked_sub(SOFT).filter(|over| *over > 0)?;
135        for (at, _, weight) in &self.sent {
136            if *weight >= over {
137                return Some(at.saturating_add(WINDOW_MS).saturating_sub(now).max(1));
138            }
139            over -= weight;
140        }
141        Some(WINDOW_MS)
142    }
143
144    /// The last minute at `now`, with no cooldown: the [`Gate`] knows that.
145    pub(crate) fn spent(&mut self, now: u64) -> Spent {
146        self.prune(now);
147        let mut kinds: Vec<Kind> = Vec::new();
148        for (_, name, weight) in &self.sent {
149            match kinds.iter_mut().find(|kind| kind.name == *name) {
150                Some(kind) => {
151                    kind.count += 1;
152                    kind.weight = kind.weight.saturating_add(*weight);
153                }
154                None => kinds.push(Kind { name: name.clone(), count: 1, weight: *weight }),
155            }
156        }
157        kinds.sort_by(|a, b| b.weight.cmp(&a.weight).then_with(|| a.name.cmp(&b.name)));
158        let minute = kinds.iter().fold(0u32, |sum, kind| sum.saturating_add(kind.weight));
159        Spent {
160            limit: LIMIT,
161            minute,
162            kinds,
163            refused: u32::try_from(self.refused.len()).unwrap_or(u32::MAX),
164            cooldown_ms: 0,
165        }
166    }
167}
168
169/// What a request carries out through the [`Gate`]: how many strikes there
170/// had been when it went out, so a burst sent before a 429 counts once.
171#[derive(Debug, Clone, Copy)]
172pub(crate) struct Ticket(u64);
173
174/// Closed by a 429 for every request, reads and actions alike: the venue
175/// limits by IP, so one refusal means the next request would be refused too.
176#[derive(Debug, Default)]
177pub(crate) struct Gate {
178    until: u64,
179    /// Consecutive strikes, a burst counting once.
180    strikes: u32,
181    /// Strikes ever.
182    epoch: u64,
183}
184
185impl Gate {
186    /// A ticket out, or how long the gate stays closed.
187    pub(crate) fn open(&self, now: u64) -> Result<Ticket, u64> {
188        match self.until > now {
189            true => Err(self.until - now),
190            false => Ok(Ticket(self.epoch)),
191        }
192    }
193
194    /// The request was answered: room again, unless a 429 struck since it
195    /// went out.
196    pub(crate) fn passed(&mut self, ticket: Ticket) {
197        if ticket.0 == self.epoch {
198            self.strikes = 0;
199        }
200    }
201
202    /// A 429 came back at `now`. The first of a burst strikes: two seconds,
203    /// doubling to a minute, or a longer `Retry-After`. The rest of the burst
204    /// only moves the gate for a longer `Retry-After`. Gives the wait.
205    pub(crate) fn struck(&mut self, ticket: Ticket, now: u64, retry_after_ms: Option<u64>) -> u64 {
206        let wait = match ticket.0 == self.epoch {
207            true => {
208                self.epoch += 1;
209                self.strikes = (self.strikes + 1).min(MAX_STRIKES);
210                let backoff = (BASE_COOLDOWN_MS << (self.strikes - 1)).min(MAX_COOLDOWN_MS);
211                backoff.max(retry_after_ms.unwrap_or(0))
212            }
213            false => retry_after_ms.unwrap_or(0),
214        };
215        self.until = self.until.max(now.saturating_add(wait));
216        self.until.saturating_sub(now)
217    }
218
219    #[must_use]
220    pub(crate) const fn cooldown_ms(&self, now: u64) -> u64 {
221        self.until.saturating_sub(now)
222    }
223}
224
225#[cfg(test)]
226#[path = "tests/limit.rs"]
227mod tests;