Skip to content

Instantly share code, notes, and snippets.

@iyashjayesh
Created March 31, 2023 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iyashjayesh/5e6fff62ba8f8d864d76f39ef8d2671f to your computer and use it in GitHub Desktop.
Save iyashjayesh/5e6fff62ba8f8d864d76f39ef8d2671f to your computer and use it in GitHub Desktop.
Implementing Rate Limiting in Go APIs.
package main
import (
"fmt"
"sync"
"time"
)
type RateLimiter struct {
sync.Mutex
requests int
requestsLimit int
interval time.Duration
}
func NewRateLimiter(requestsLimit int, interval time.Duration) *RateLimiter {
return &RateLimiter{
requests: 0,
requestsLimit: requestsLimit,
interval: interval,
}
}
func (rl *RateLimiter) AllowRequest() bool {
rl.Lock()
defer rl.Unlock()
if rl.requests >= rl.requestsLimit {
return false
}
rl.requests++
time.AfterFunc(rl.interval, func() {
rl.Lock()
defer rl.Unlock()
rl.requests--
})
return true
}
func main() {
rl := NewRateLimiter(3, time.Second*10)
for i := 1; i <= 10; i++ {
if rl.AllowRequest() {
fmt.Printf("Request %d allowed.\n", i)
} else {
fmt.Printf("Request %d denied.\n", i)
}
time.Sleep(time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment