RateLimit class
Lets a client send at most max requests in each per window.
One more request gets 429 Too Many Requests with a Retry-After
header (seconds). Every answer has X-RateLimit-Limit and
X-RateLimit-Remaining.
Route.post('/login', <dynamic>[
RateLimit(max: 5, per: Duration(minutes: 1)),
authController.login,
]);
Where the counts live:
- the default cache store is Redis: in Redis. All isolates and all servers share them.
- else: in the main isolate. All isolates of this server share them. The other isolates send each count to the main isolate (one message and its answer per limited request). Each server has its own counts.
- store names a store: in that store (a
memorystore counts in the main isolate, like above). - cacheStore is given: in that store, as it is. A
MemoryDriverstore given here counts in each isolate on its own.
By default it is a fixed window: the counter starts again at each new window (eg. each new minute). So a client can send up to 2 x max requests around the end of one window and the start of the next. Set sliding to stop that burst.
A blocked request still counts. So a client that keeps sending while it is blocked stays blocked.
- Implemented types
Constructors
- RateLimit({int max = 60, Duration per = const Duration(minutes: 1), RateLimitKey? key, String? name, String? store, CacheStore? cacheStore, bool sliding = false, DateTime now()?})
Properties
- cacheStore → CacheStore?
-
a ready cache store to keep the counts, eg. in tests
final
- hashCode → int
-
The hash code for this object.
no setterinherited
- key → RateLimitKey
-
the client to count for. Default is the client ip. With
CoreFlags.rateLimitIpv6Prefixan IPv6 client counts by its /64, see ipBucket.final - max → int
-
the most requests in one window
final
- name → String
-
Two limits with the same name (and the same key) share one counter.
Default is made from max and per.
final
- per → Duration
-
the length of one window
final
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- sliding → bool
-
Use a sliding window. The count is then a guess of the requests in
the last per: the count of this window plus a part of the count
of the window before. That part gets smaller as this window goes
on. Eg. 30% into this window, 70% of the last count is added.
It stops the burst of 2 x max at the edge of a window. It costs
one more read per request, and each count is kept for 2 windows.
final
- store → String?
-
the name of a cache store from
AppConfig.cacheto keep the counts. Default: the default store when it is Redis, else memory.final
Methods
-
handle(
IDoxRequest req) → Future -
override
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited