Rate Limiter Pattern
1 min read
Pronunciation
[rayt li-mi-ter pat-ern]
Analogy
Rate limiting is like a turnstile that only allows one person through every 10 seconds to prevent overcrowding.
Definition
A contract design that restricts the frequency or volume of operations per account or globally to mitigate spam and abuse.
Key Points Intro
Rate Limiter Pattern controls usage through:
Key Points
Timestamps map: Records last action time per user.
Counters window: Tracks number of operations within a time window.
Require checks: Enforces `block.timestamp - lastTime >= interval`.
Global vs. per‑user: Can apply limits per address or on aggregate.
Example
```
mapping(address=>uint) lastCall;
function mint() external {
require(block.timestamp - lastCall[msg.sender] >= 1 hours, "Wait an hour");
lastCall[msg.sender] = block.timestamp;
_mint(...);
}
```
Technical Deep Dive
Use a mapping `lastAction[address]` to store the timestamp of the last permitted call. In each function, `require(now - lastAction[msg.sender] >= interval)` then update the mapping. For volume limits, maintain a circular buffer of timestamps or count resets every window using `if now > windowStart + windowSize` reset counter.
Security Warning
Reliance on `block.timestamp` can be manipulated by miners within ~15 seconds; avoid very tight intervals.
Caveat
Static intervals can degrade UX; consider dynamic or token‑bucket algorithms off‑chain.
Rate Limiter Pattern - Related Articles
No related articles for this term.