Created
February 12, 2024 10:55
-
-
Save brmzkw/105f82176b65ed3a3102af5d546e5305 to your computer and use it in GitHub Desktop.
chain rate limiting golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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