60-second quickstart¶
This path uses the in-memory backend, so it needs only Go and the GoRL module.
1. Install¶
2. Run the canonical example¶
From the repository root:
The complete program is compiled by go test ./...:
examples/inmemory/main.go
// Package main demonstrates the usage of the in-memory rate limiter.
package main
import (
"context"
"fmt"
"time"
"github.com/AliRizaAynaci/gorl/v2"
"github.com/AliRizaAynaci/gorl/v2/core"
)
// main runs a simple demonstration of the rate limiter.
func main() {
limiter, err := gorl.New(core.Config{
Strategy: core.TokenBucket,
Limit: 3,
Window: 10 * time.Second,
})
if err != nil {
panic(err)
}
defer limiter.Close()
ctx := context.Background()
start := time.Now()
for i := 1; i <= 15; i++ {
res, err := limiter.Allow(ctx, "127.0.0.1")
elapsed := time.Since(start).Seconds()
timestamp := time.Now().Format("15:04:05")
fmt.Printf("[%s +%.1fs] Request #%d: allowed=%v, remaining=%d, retry_after=%v, err=%v\n",
timestamp, elapsed, i, res.Allowed, res.Remaining, res.RetryAfter, err,
)
time.Sleep(1000 * time.Millisecond)
}
}
3. Read the decisions¶
The token bucket begins full with three tokens. The first requests consume that capacity; later requests are denied until time has replenished enough tokens. Each line reports:
allowed: whether application work may proceed,remaining: whole-request capacity after the decision,retry_after: the earliest reliable delay after a denial,err: a backend or algorithm failure, if one occurred.
Move toward production¶
Before deploying, decide:
- which application identity becomes the key,
- which algorithm matches the traffic contract,
- whether state is process-local or shared through Redis,
- whether a backend failure should fail open or fail closed,
- where
Closebelongs in the application shutdown path.
Process-local means process-local
Two application instances with in-memory limiters enforce two independent capacities. Use Redis when the limit must be shared.