Last active
May 22, 2022 23:30
-
-
Save lpabon/985abd3b2535812ab7610e410cac0bb0 to your computer and use it in GitHub Desktop.
Testing out rate limiting
This file contains hidden or 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" | |
"math/rand" | |
"sync" | |
"time" | |
"golang.org/x/time/rate" | |
) | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
// Allow at most 50 (burst) per second | |
// Refresh tokens at 100 per second (or in other words every 10ms) | |
l := rate.NewLimiter(100, 50) | |
st := time.Now() | |
var wg sync.WaitGroup | |
for i := 0; i < 3000; i++ { | |
wg.Add(1) | |
go func(i int) { | |
for { | |
if l.Allow() { | |
fmt.Printf("[%d] allowed in %v\n", i, time.Now().Sub(st)) | |
break | |
} else { | |
fmt.Printf("[%d] !!disallowed in %v\n", i, time.Now().Sub(st)) | |
time.Sleep(2*time.Second + time.Duration(rand.Intn(10000*i))) | |
} | |
} | |
wg.Done() | |
}(i) | |
} | |
wg.Wait() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment