PHP token bucket rate limiter
PHP
<?php
final class TokenBucket
{
private float $tokens;
private int $updated;
public function __construct(private float $rate, private int $burst)
{
$this->tokens = (float) $burst;
$this->updated = time();
}
public function take(int $cost = 1): bool
{
$now = time();
$this->tokens = min($this->burst, $this->tokens + ($now - $this->updated) * $this->rate);
$this->updated = $now;
if ($this->tokens < $cost) return false;
$this->tokens -= $cost;
return true;
}
}