Skip to content

Instantly share code, notes, and snippets.

@brmzkw
Created February 12, 2024 10:55
Show Gist options
  • Save brmzkw/105f82176b65ed3a3102af5d546e5305 to your computer and use it in GitHub Desktop.
Save brmzkw/105f82176b65ed3a3102af5d546e5305 to your computer and use it in GitHub Desktop.
chain rate limiting golang
package main
import (
"fmt"
"time"
"golang.org/x/time/rate"
)
func deploy(quotas map[string]*rate.Limiter, orga string, service string) bool {
allowed := true
fmt.Printf("Trying to deploy %s - %s\n", orga, service)
for name, limiter := range quotas {
if name == fmt.Sprintf("orga-%s", orga) || name == fmt.Sprintf("service-%s", service) {
if !limiter.Allow() {
fmt.Printf("Rate limited!\n")
allowed = false
}
}
}
if allowed {
fmt.Printf("\tDeploying for %s - %s\n", orga, service)
}
return allowed
}
func main() {
quotas := map[string]*rate.Limiter{
"orga-00000000-0000-0000-0000-000000000000": rate.NewLimiter(rate.Every(10*time.Second), 10),
"orga-11111111-1111-1111-1111-111111111111": rate.NewLimiter(rate.Every(10*time.Second), 10),
"service-00000000-0000-0000-0000-000000000000": rate.NewLimiter(rate.Every(1*time.Second), 1),
"service-11111111-1111-1111-1111-111111111111": rate.NewLimiter(rate.Every(10*time.Second), 10),
}
deploy(quotas, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000")
deploy(quotas, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000")
deploy(quotas, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000")
time.Sleep(1 * time.Second)
deploy(quotas, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000")
deploy(quotas, "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment