New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Ratelimiter #1211
Merged
+198
−30
Merged
Ratelimiter #1211
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
package httputil | ||
|
||
import ( | ||
"net/http" | ||
"sync" | ||
|
||
"golang.org/x/time/rate" | ||
) | ||
|
||
// RateLimiter wraps the provided RoundTripper with a limiter allowing 10 | ||
// requests/second/host. | ||
// | ||
// It responds to HTTP 429 responses by automatically decreasing the rate. | ||
func RateLimiter(next http.RoundTripper) http.RoundTripper { | ||
return &ratelimiter{ | ||
rt: next, | ||
lm: sync.Map{}, | ||
} | ||
} | ||
|
||
// Ratelimiter implements the limiting by using a concurrent map and Limiter | ||
// structs. | ||
type ratelimiter struct { | ||
rt http.RoundTripper | ||
lm sync.Map | ||
} | ||
|
||
const rateCap = 10 | ||
|
||
// RoundTrip implements http.RoundTripper. | ||
func (r *ratelimiter) RoundTrip(req *http.Request) (*http.Response, error) { | ||
key := req.URL.Host | ||
li, ok := r.lm.Load(key) | ||
if !ok { | ||
// Limiter allows "rateCap" per sec, one at a time. | ||
l := rate.NewLimiter(rate.Limit(rateCap), 1) | ||
li, _ = r.lm.LoadOrStore(key, l) | ||
} | ||
l := li.(*rate.Limiter) | ||
if err := l.Wait(req.Context()); err != nil { | ||
return nil, err | ||
} | ||
res, err := r.rt.RoundTrip(req) | ||
// This seems to be the contract that http.Transport implements. | ||
if err != nil { | ||
return nil, err | ||
} | ||
switch res.StatusCode { | ||
case http.StatusOK: | ||
// Try increasing on OK. | ||
if lim := l.Limit(); lim < rateCap { | ||
l.SetLimit(lim + 1) | ||
} | ||
case http.StatusTooManyRequests: | ||
// Try to allow some requests, eventually. | ||
l.SetLimit(detune(l.Limit())) | ||
} | ||
return res, nil | ||
} | ||
|
||
// Detune reduces the rate. | ||
func detune(in rate.Limit) rate.Limit { | ||
if in <= 1 { | ||
return in / 2 | ||
} | ||
return in - 1 | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package httputil | ||
|
||
import ( | ||
"net/http" | ||
"net/http/httptest" | ||
"sync" | ||
"testing" | ||
"time" | ||
) | ||
|
||
func TestRate(t *testing.T) { | ||
const nReq = 20 | ||
|
||
var wg sync.WaitGroup | ||
wg.Add(nReq) | ||
begin := make(chan struct{}) | ||
var last struct { | ||
sync.Mutex | ||
t time.Time | ||
} | ||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { | ||
last.Lock() | ||
last.t = time.Now() | ||
last.Unlock() | ||
w.WriteHeader(http.StatusOK) | ||
})) | ||
defer srv.Close() | ||
cl := srv.Client() | ||
cl.Transport = RateLimiter(cl.Transport) | ||
|
||
for i := 0; i < nReq; i++ { | ||
go func() { | ||
defer wg.Done() | ||
<-begin | ||
res, err := cl.Get(srv.URL) | ||
if err != nil { | ||
t.Error(err) | ||
return | ||
} | ||
res.Body.Close() | ||
}() | ||
} | ||
|
||
first := time.Now() | ||
close(begin) | ||
wg.Wait() | ||
|
||
t.Logf("begin: %v", first) | ||
t.Logf("end: %v", last.t) | ||
rate := nReq / last.t.Sub(first).Seconds() | ||
t.Logf("rate: %v", rate) | ||
|
||
if rate < (rateCap-1) || rate > (rateCap+1) { | ||
t.Error("rate outside acceptable bounds") | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I may be reading this wrong, but when/if the downstream recovers, would the limit be "stuck" at a lower than optimal rate?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes.
I'm not sure what to do to re-ramp the limit. Using
SetLimitAt
would result in the limit getting similarly stuck, by my thinking. Perhaps a second Limiter with token representing an increase to the limit?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am not so familiar with the request patterns or how a certain node can become overwhelmed, but would it make sense to have a second case (or an else case) that increases the Limit (retune) when
status == <good status>
and then taking theMin(newLimit, lim)
to ensure you don't go over the max? (In general, detune should reduce faster than retune increases it).In the long run it seems like using a client to mitigate against server errors would lead to a different loadbalancing strategy to the
RoundTrip
, but that seems like a discussion for a different time.