My favorites | Sign in
Project Home Wiki
Search
for
RateLimiting  
Rate Limiting
time, rpc, rate
Updated May 23, 2011 by ajm...@gmail.com

Rate Limiting

To limit the rate of operations per unit time, use time.Tick:

import "time"

rate_per_sec := 10
throttle := time.Tick(1e9 / rate_per_sec)
for req := range requests {
  <-throttle  // rate limit our Service.Method RPCs
  go client.Call("Service.Method", req, ...)
}

To allow some bursts, add a buffer to the throttle:

import "time"

rate_per_sec := 10
burst_limit := 100
tick := time.NewTicker(1e9 / rate_per_sec)
defer tick.Stop()
throttle := make(chan int64, burst_limit)
go func() {
  for ns := range tick {
    select {
      case: throttle <- ns
      default:
    }
  }  // exits after tick.Stop()
}()
for req := range requests {
  <-throttle  // rate limit our Service.Method RPCs
  go client.Call("Service.Method", req, ...)
}

References

time.Tick: http://golang.org/pkg/time/#Tick

Powered by Google Project Hosting