Ratelix CIHex Docs

An Elixir library that provides robust, concurrent-safe rate limiting using two classic algorithms: Leaky Bucket and Token Bucket. It is designed for use in APIs, background jobs, or anywhere you need to control the rate of operations. All that in local node context.

Features

Installation

Add ratelix to your list of dependencies in mix.exs:

def deps do
  [
    {:ratelix, "~> 1.0.0"}
  ]
end

Usage

Warning

Ensure ratelix supervisor is started.

Starting a Rate Limiter

You can start a rate limiter process with either algorithm:

Leaky Bucket

{:ok, _sup} = Ratelix.Supervisor.start_link(nil)
{:ok, _worker} = Ratelix.start_process(:client, algorithm: :leaky_bucket, capacity: 5, interval: 1)

Token Bucket

{:ok, _sup} = Ratelix.Supervisor.start_link(nil)
{:ok, _worker} = Ratelix.start_process(:client, algorithm: :token_bucket, capacity: 10, rate: 2, interval: 1)

Requesting Permission

To check if an action is allowed (and update the limiter’s state):

case Ratelix.wait_for_turn(:client) do
  :ok -> do_the_thing()
  {:error, reason} -> handle_rate_limit(reason)
end

Checking Limiter State

Ratelix.bucket_stats(:client)

Example

{:ok, _worker} = Ratelix.start_process(:client, algorithm: :leaky_bucket, capacity: 10, interval: 1)

for _ <- 1..12 do
  IO.inspect Ratelix.wait_for_turn(:client)
end

Algorithms

Leaky Bucket

Token Bucket

When to Use

Contributing

Before submitting a PR, ensure you run mix check and all checks passes successfully.

Version Bumps

This project adheres to Semantic Versioning, which means the version number will follow the format MAJOR.MINOR.PATCH.

Also, the github-tag-action is used to automatically create a new tag when the PR is merged to master.

When open a PR meant to generate a new version:

  1. Update the mix.exs and README with the new version.

  2. Update CHANGELOG with the new version tight to semantic versioning.

  3. Don't forget to include in your commit the tag:

    • "#patch" for increment PATCH version. E.g.: "Fix failing tests (#patch)".
    • "#minor" for increment MINOR version. E.g.: "Add Telemetry utility to instrument the projects (#minor)".
    • "#major" for increment MAJOR version. E.g.: "Release x.y.z (#major)".

If for some reason GH actions are not working (maybe because we ran out of minutes), then push the tag manually, like so:

git tag -a v0.1.0 -m "Ratelix version 0.1.0"
git push origin v0.1.0

License

Apache License 2.0. See the project’s LICENSE file for details.