From 5811606559ccace558bf8a4d2230d87689051048 Mon Sep 17 00:00:00 2001 From: diamondburned Date: Sat, 3 Dec 2022 19:19:07 -0800 Subject: [PATCH] gateway: Fix Send rate limiting Prior to this commit, gateways can send 120 events before being throttled at a terribly slow rate of 1 send per minute. This commit permits gateways to send 5 events before being throttled at a rate of slightly less than 120 events per minute. --- utils/ws/throttler.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/utils/ws/throttler.go b/utils/ws/throttler.go index 2e93f21..5c40e17 100644 --- a/utils/ws/throttler.go +++ b/utils/ws/throttler.go @@ -6,18 +6,34 @@ import ( "golang.org/x/time/rate" ) +// SendBurst determines the number of gateway commands that can be sent all at +// once before being throttled. The higher the burst, the slower the rate +// limiter recovers. +var SendBurst = 5 + +// NewSendLimiter returns a rate limiter for throttling gateway commands. func NewSendLimiter() *rate.Limiter { - return rate.NewLimiter(rate.Every(time.Minute), 120) + const perMinute = 120 + return rate.NewLimiter( + // Permit r = minute / (120 - b) commands per second. + rate.Every(time.Minute/(perMinute-time.Duration(SendBurst))), + SendBurst, + ) } +// NewDialLimiter returns a rate limiter for throttling new gateway connections. func NewDialLimiter() *rate.Limiter { return rate.NewLimiter(rate.Every(5*time.Second), 1) } +// NewIdentityLimiter returns a rate limiter for throttling gateway Identify +// commands. func NewIdentityLimiter() *rate.Limiter { return NewDialLimiter() // same } +// NewGlobalIdentityLimiter returns a rate limiter for throttling global +// gateway Identify commands. func NewGlobalIdentityLimiter() *rate.Limiter { return rate.NewLimiter(rate.Every(24*time.Hour), 1000) }