Go by Example: Rate Limiting
Go by Example : Rate Limiting
Rate limiting is an important mechanism for controlling resource utilization and maintaining quality of service. Go elegantly supports rate limiting with goroutines, channels, and tickers . | |
| |
| |
| |
First we’ll look at basic rate limiting. Suppose we want to limit our handling of incoming requests. We’ll serve these requests off a channel of the same name. |
|
This
|
|
By blocking on a receive from the
|
|
We may want to allow short bursts of requests in
our rate limiting scheme while preserving the
overall rate limit. We can accomplish this by
buffering our limiter channel. This
|
|
Fill up the channel to represent allowed bursting. |
|
Every 200 milliseconds we’ll try to add a new
value to
|
|
Now simulate 5 more incoming requests. The first
3 of these will benefit from the burst capability
of
|
|
Running our program we see the first batch of requests handled once every ~200 milliseconds as desired. |
|
For the second batch of requests we serve the first 3 immediately because of the burstable rate limiting, then serve the remaining 2 with ~200ms delays each. |
|
Next example: Atomic Counters .