Rate-Limit API Requests in Larzscript
Token-bucket rate limiting in about 20 lines - cap a caller to N requests with a steady refill rate instead of a blunt fixed window.
The caller owns the state (a plain dict), so it works identically in a script, a web handler, or the LarzOS kernel - no hidden global, no required database.
larzscript pkg install ratelimit
Code
import "ratelimit" as ratelimit
let buckets = {}
let i = 0
while i < 12 {
let allowed = ratelimit.allow(buckets, "user:42", 10, 1.0, 0.0)
print("request", i, "->", allowed ? "allowed" : "rate limited")
i = i + 1
}Output
request 0 -> allowed request 1 -> allowed request 2 -> allowed request 3 -> allowed request 4 -> allowed request 5 -> allowed request 6 -> allowed request 7 -> allowed request 8 -> allowed request 9 -> allowed request 10 -> rate limited request 11 -> rate limited
Related
larzratelimitToken-bucket rate limiting→Split a Bill Fairly in LarzscriptDivide a bill among people so it reconciles exactly to the cent - no language other than Larzscript treats this as a stack primitive rather than app-level logic.→Hold Funds in Escrow in LarzscriptHold a payer's funds, then release them to a payee or refund them back - using the language's own wallet and pay keywords, not a bolted-on library.→