RateLimiter class

A utility class that implements rate limiting functionality.

This class is used to ensure that a particular section of code is not executed more than a certain number of times within a specified interval.

Parameters:

  • maxRequests: The maximum number of requests allowed within the interval.
  • interval: The time interval in which the number of requests is counted.

Example:

// Create a new rate limiter that allows 10 requests per minute.
var rateLimiter = RateLimiter(maxRequests: 10, interval: Duration(minutes: 1));

// Example function that performs an action that should be rate-limited.
void performAction() {
  try {
    rateLimiter.checkRateLimiting();
    print('Action performed.');
  } on Exception catch (e) {
    print(e);
  }
}

// Simulate performing actions.
for (int i = 0; i < 15; i++) {
  performAction();
}

Expected output if called 15 times in a loop:

Action performed.
Action performed.
Action performed.
... // repeated until the 10th print statement
Exception: Rate limit exceeded. Please try again later.

Constructors

RateLimiter.new({int maxRequests = 100, Duration interval = const Duration(seconds: 1)})
Constructs a RateLimiter with optional parameters maxRequests and interval. If not specified, maxRequests defaults to 100 and interval defaults to 1 second.

Properties

hashCode int
The hash code for this object.
no setterinherited
interval Duration
Time interval in which maxRequests is counted.
getter/setter pair
maxRequests int
Maximum number of requests that can be made in the defined interval.
getter/setter pair
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

checkRateLimiting() → void
Checks if the rate limit has been exceeded.
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