Per-IP sliding window rate limiter
OCaml 86.2%
Dune 4.0%
Other 9.8%
17 1 0

Clone this repository

https://tangled.org/gazagnaire.org/ocaml-rate-limit https://tangled.org/did:plc:jhift2vwcxhou52p3sewcrpx/ocaml-rate-limit
git@git.recoil.org:gazagnaire.org/ocaml-rate-limit git@git.recoil.org:did:plc:jhift2vwcxhou52p3sewcrpx/ocaml-rate-limit

For self-hosted knots, clone URLs may differ based on your setup.

Download tar.gz
README.md

rate-limit#

Per-IP sliding window rate limiter with Eio support.

Overview#

Thread-safe per-client rate limiting using the sliding window algorithm. Multi-domain safe with Eio.Mutex for concurrent access from multiple OCaml 5 domains.

Features#

  • Sliding window rate limiting (more accurate than fixed windows)
  • Per-client (IP) tracking
  • Thread-safe with Eio.Mutex
  • Configurable window size and request limit
  • Retry-after calculation for 429 responses
  • Automatic cleanup of expired entries

Installation#

opam install rate-limit

Usage#

(* Create a rate limiter: 100 requests per 60 seconds *)
let limiter = Rate_limit.create ~max_requests:100 ~window_seconds:60.0 ()

let handle_request ~ip =
  let now = Unix.gettimeofday () in
  match Rate_limit.check_and_record limiter ~ip ~now with
  | true, remaining ->
      (* Request allowed *)
      Printf.printf "Allowed, %d requests remaining\n" remaining;
      process_request ()
  | false, _ ->
      (* Rate limited - calculate retry-after *)
      let retry = Rate_limit.retry_after limiter ~ip ~now in
      Printf.printf "Rate limited, retry after %.0f seconds\n" retry;
      respond_429 ~retry_after:(int_of_float retry)

API#

  • Rate_limit.create - Create a new rate limiter
  • Rate_limit.check_and_record - Check if request allowed and record it
  • Rate_limit.retry_after - Calculate seconds until limit resets
  • Rate_limit.current_count - Get current request count for an IP
  • Rate_limit.stats - Get (tracked_ips, total_requests) statistics

Standards#

  • RFC 6585 - Additional HTTP Status Codes (429 Too Many Requests)
  • No standalone rate limiting packages found in opam
  • This implementation is Eio-native with minimal dependencies

Licence#

MIT License. See LICENSE.md for details.