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)]
73pub struct Spent {
74    /// The weight allowed a minute per IP: [`LIMIT`].
75    pub limit: u32,
76    /// The weight sent over the last minute, all kinds together.
77    pub minute: u32,
78    /// By kind, the heaviest first.
79    pub kinds: Vec<Kind>,
80    /// 429s over the last minute.
81    pub refused: u32,
82    /// How long the gate stays closed; 0 when it is open.
83    pub cooldown_ms: u64,
84}
85
86/// One kind of request in [`Spent`] and what it spent over the last minute.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Kind {
89    /// The `/info` read's `type`, such as `l2Book`, or `exchange` for every action.
90    pub name: String,
91    /// How many went out.
92    pub count: u32,
93    /// Their weight added up.
94    pub weight: u32,
95}
96
97/// The last minute of requests: when each went out, its kind and weight; and
98/// when each refusal came.
99#[derive(Debug, Default)]
100pub(crate) struct Meter {
101    sent: VecDeque<(u64, String, u32)>,
102    refused: VecDeque<u64>,
103}
104
105impl Meter {
106    /// Drops what is a whole window old at `now`.
107    fn prune(&mut self, now: u64) {
108        let gone = |at: u64| at.saturating_add(WINDOW_MS) <= now;
109        while self.sent.front().is_some_and(|(at, _, _)| gone(*at)) {
110            self.sent.pop_front();
111        }
112        while self.refused.front().is_some_and(|at| gone(*at)) {
113            self.refused.pop_front();
114        }
115    }
116
117    pub(crate) fn record(&mut self, now: u64, kind: &str, weight: u32) {
118        self.prune(now);
119        self.sent.push_back((now, kind.to_owned(), weight));
120    }
121
122    pub(crate) fn refuse(&mut self, now: u64) {
123        self.prune(now);
124        self.refused.push_back(now);
125    }
126
127    /// How long a read of `need` waits at `now`, so the last minute stays
128    /// within [`SOFT`]: none while it fits, else until enough has rolled off.
129    pub(crate) fn wait_for(&mut self, now: u64, need: u32) -> Option<u64> {
130        self.prune(now);
131        let spent = self.sent.iter().fold(0u32, |sum, (_, _, weight)| sum.saturating_add(*weight));
132        let mut over = spent.saturating_add(need).checked_sub(SOFT).filter(|over| *over > 0)?;
133        for (at, _, weight) in &self.sent {
134            if *weight >= over {
135                return Some(at.saturating_add(WINDOW_MS).saturating_sub(now).max(1));
136            }
137            over -= weight;
138        }
139        Some(WINDOW_MS)
140    }
141
142    /// The last minute at `now`, with no cooldown: the [`Gate`] knows that.
143    pub(crate) fn spent(&mut self, now: u64) -> Spent {
144        self.prune(now);
145        let mut kinds: Vec<Kind> = Vec::new();
146        for (_, name, weight) in &self.sent {
147            match kinds.iter_mut().find(|kind| kind.name == *name) {
148                Some(kind) => {
149                    kind.count += 1;
150                    kind.weight = kind.weight.saturating_add(*weight);
151                }
152                None => kinds.push(Kind { name: name.clone(), count: 1, weight: *weight }),
153            }
154        }
155        kinds.sort_by(|a, b| b.weight.cmp(&a.weight).then_with(|| a.name.cmp(&b.name)));
156        let minute = kinds.iter().fold(0u32, |sum, kind| sum.saturating_add(kind.weight));
157        Spent {
158            limit: LIMIT,
159            minute,
160            kinds,
161            refused: u32::try_from(self.refused.len()).unwrap_or(u32::MAX),
162            cooldown_ms: 0,
163        }
164    }
165}
166
167/// What a request carries out through the [`Gate`]: how many strikes there
168/// had been when it went out, so a burst sent before a 429 counts once.
169#[derive(Debug, Clone, Copy)]
170pub(crate) struct Ticket(u64);
171
172/// Closed by a 429 for every request, reads and actions alike: the venue
173/// limits by IP, so one refusal means the next request would be refused too.
174#[derive(Debug, Default)]
175pub(crate) struct Gate {
176    until: u64,
177    /// Consecutive strikes, a burst counting once.
178    strikes: u32,
179    /// Strikes ever.
180    epoch: u64,
181}
182
183impl Gate {
184    /// A ticket out, or how long the gate stays closed.
185    pub(crate) fn open(&self, now: u64) -> Result<Ticket, u64> {
186        match self.until > now {
187            true => Err(self.until - now),
188            false => Ok(Ticket(self.epoch)),
189        }
190    }
191
192    /// The request was answered: room again, unless a 429 struck since it
193    /// went out.
194    pub(crate) fn passed(&mut self, ticket: Ticket) {
195        if ticket.0 == self.epoch {
196            self.strikes = 0;
197        }
198    }
199
200    /// A 429 came back at `now`. The first of a burst strikes: two seconds,
201    /// doubling to a minute, or a longer `Retry-After`. The rest of the burst
202    /// only moves the gate for a longer `Retry-After`. Gives the wait.
203    pub(crate) fn struck(&mut self, ticket: Ticket, now: u64, retry_after_ms: Option<u64>) -> u64 {
204        let wait = match ticket.0 == self.epoch {
205            true => {
206                self.epoch += 1;
207                self.strikes = (self.strikes + 1).min(MAX_STRIKES);
208                let backoff = (BASE_COOLDOWN_MS << (self.strikes - 1)).min(MAX_COOLDOWN_MS);
209                backoff.max(retry_after_ms.unwrap_or(0))
210            }
211            false => retry_after_ms.unwrap_or(0),
212        };
213        self.until = self.until.max(now.saturating_add(wait));
214        self.until.saturating_sub(now)
215    }
216
217    #[must_use]
218    pub(crate) const fn cooldown_ms(&self, now: u64) -> u64 {
219        self.until.saturating_sub(now)
220    }
221}
222
223#[cfg(test)]
224#[path = "tests/limit.rs"]
225mod tests;