mmcgrana / gobyexample

Go by Example
https://gobyexample.com
7.16k stars 1.26k forks source link

fix: problem in burst limit #499

Closed Shurtu-gal closed 9 months ago

Shurtu-gal commented 9 months ago

Suppose there is a sleep for some time then time.The tick channel keeps getting filled leading to the burst count > 3.

eg:-

  go func() {
    for t := range time.Tick(200 * time.Millisecond) {
      burstyLimiter <- t
    }
  }()

  time.Sleep(1000 * time.Millisecond)

image

Solution:- Drain the range by adding a default. eg:-

  go func() {
    for t := range time.Tick(200 * time.Millisecond) {
      select {
        case burstyLimiter <- t:
        default:
          continue
      }
    }
  }()
  time.Sleep(1000 * time.Millisecond)

image

eliben commented 9 months ago

Sorry, I do not understand the scenario this is trying to solve. Can you please clarify?

Shurtu-gal commented 9 months ago

Yeah, like I had been using this in a sample app where I was rate-limiting the api-calls. However the problem I faced was, after some delay lets say after 500 seconds, the time.Tick channel has 500 entries which can lead to serve of 500 requests at once if they do come.

Hence the need of drain.

eliben commented 9 months ago

Thanks for the clarification.

I think this example is fine as it is. It provides the basic tools and concepts, without trying to solve every variation of the problem. The idea is expose Go's flexible building blocks for building solutions suitable for your specific use case.

Shurtu-gal commented 9 months ago

Okay