ratelimit

Token bucket and sliding-window rate limiters with per-key tracking.

v1.0.0Web & networkingbundledimport "ratelimit";
Overview Installation Documentation Examples

Overview

Zero-dependency HolyPHP rate limiting library providing Token Bucket (TokenBucket) and Sliding Window (SlidingWindowLimiter) limiters with per-key tracking.

bundled — works offline zero dependencies throttle bucket

Quick start

import "ratelimit";

// Token bucket: capacity 5 tokens, refills at 1 token/second
$bucket = new TokenBucket(5.0, 1.0);
$now = 1000.0;

if ($bucket->allow("user:42", $now)) {
    println("Allowed! Remaining: " . $bucket->remaining("user:42", $now));
} else {
    println("Rate limited. Retry after: " . $bucket->retryAfter("user:42", $now) . "s");
}

// Sliding window: max 3 requests per 10 seconds
$limiter = new SlidingWindowLimiter(3, 10.0);
$allowed = $limiter->allow("ip:127.0.0.1", $now);

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install ratelimit

This adds the library to hphp.yaml, installs it into .hphp/packages/ratelimit/ and pins the exact version in hphp.lock:

require:
  ratelimit: "^1.0"

Use it

import "ratelimit";

ratelimit is bundled with the compiler, so import "ratelimit"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install ratelimit          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install ratelimit
Packageratelimit
Version1.0.0 (follows the compiler)
Entry fileratelimit.hphp
Sourcepackages/lib/ratelimit ↗

Documentation

API Reference

TokenBucket

A per-key token bucket rate limiter supporting fractional capacities, refill rates, and custom request costs.

SlidingWindowLimiter

A per-key sliding-window log rate limiter that tracks request timestamps within a rolling window.

Helper Functions

Error Handling

All invalid configurations and arguments throw an Exception prefixed with ratelimit::

Examples

01Quick start

Bundled with the compiler — import "ratelimit"; works offline in any file, or add it to a project with hphp install ratelimit.

import "ratelimit";

// Token bucket: capacity 5 tokens, refills at 1 token/second
$bucket = new TokenBucket(5.0, 1.0);
$now = 1000.0;

if ($bucket->allow("user:42", $now)) {
    println("Allowed! Remaining: " . $bucket->remaining("user:42", $now));
} else {
    println("Rate limited. Retry after: " . $bucket->retryAfter("user:42", $now) . "s");
}

// Sliding window: max 3 requests per 10 seconds
$limiter = new SlidingWindowLimiter(3, 10.0);
$allowed = $limiter->allow("ip:127.0.0.1", $now);
Try it
hphp install ratelimit
hphp run main.hphp

Covered by the official test suite in tests/positive/lib_ratelimit.hphp.