In addition to connection operation rate limiting features Centrifugo PRO provides a generic high precision rate limiting API. It may be used for custom quota managing tasks not even related to real-time connections. Its distributed nature allows managing quotas across different instances of your application backend.
The original reason why we decided to ship this as part of our PRO version APIs was the desire to simplify our PRO users the implementation of per-user push notification limits when using Push Notification API. But you are free to use the API for other custom needs as well.
Centrifugo distributed rate limiting is a high performance zero-configuration Redis-based token bucket with milliseconds precision. Zero configuration in this case means that you don't have to preconfigure buckets in Centrifugo – bucket configuration is a part of request to check allowed limits.
curl -X POST http://localhost:8000/api/rate_limit \
-H "Authorization: apikey <KEY>" \
-d @- <<'EOF'
Or, when no tokens left in a bucket:
In your app code call
rate_limit API of Centrifugo PRO every time some action is executed and check
allowed flag to allow or discard the action.
Centrifugo PRO also returns
server_time fields to help understanding when action will be allowed. These two fields are only appended when
tokens_left are less than requested
server_time will provide you a timestamp in the future (in milliseconds) when action is possible to be executed. So you can delay next action execution till that time if possible.
To enable distributed rate limiter:
Note, that just like most of other features in Centrifugo it's possible to configure Redis shards here or use Redis Cluster.
Now let's look at API description.
|Yes||Key for a bucket - you can construct keys whatever way you like|
|Yes||Interval in milliseconds|
|Yes||Allowed rate per provided interval|
|No||Score for the current action, if not provided the default score 1 is used|
|Yes||Whether desired action is allowed at this point in time|
|Yes||How many tokens left in a bucket|
|No||Milliseconds till desired score will be allowed again|
|No||Server time as Unix epoch in milliseconds used to calculate result|