crabbucket/redis

Types

window_duration_milliseconds describes the length of the time window valid for a number of tokens. For instance, a value of 1,000 with a default token count of 100 would mean an action could occur 100 times per second.

pub type RedisTokenBucket {
  RedisTokenBucket(
    redis_connection: Subject(Message),
    window_duration_milliseconds: Int,
  )
}

Constructors

  • RedisTokenBucket(
      redis_connection: Subject(Message),
      window_duration_milliseconds: Int,
    )
pub type RemainingTokenCountFailure {
  MustWaitUntil(next_reset_timestamp: Int)
  RedisError(error: Error)
}

Constructors

  • MustWaitUntil(next_reset_timestamp: Int)
  • RedisError(error: Error)
pub type RemainingTokenCountSuccess {
  HasRemainingTokens(
    remaining_tokens: Int,
    next_reset_timestamp: Int,
  )
}

Constructors

  • HasRemainingTokens(
      remaining_tokens: Int,
      next_reset_timestamp: Int,
    )

Functions

pub fn clear_key(
  bucket: RedisTokenBucket,
  key: String,
) -> Result(Bool, Error)

Returns True if record was deleted, False if record didn’t exist

pub fn remaining_tokens_for_key(
  bucket: RedisTokenBucket,
  key: String,
  default_token_count: Int,
) -> Result(
  RemainingTokenCountSuccess,
  RemainingTokenCountFailure,
)

Takes an arbitrary string key, inserting a record if non-existing.

Suggestion: you may wish to format you string key such that it indicates usage, purpose, value type, and value. For instance, if you’re limiting a specific endpoint for a given user, the key might look something like: limit:some_endpoint_name:user:12345

Return should be either HasRemainingTokens(remaining_tokens: Int), which indicates that an action may proceed and contains how many more times the action may occur with the current window, or it may be MustWaitFor(milliseconds: Int), which indicates that no tokens remain for this keep and how many milliseconds remain until the end of the current window.

Search Document