5

i would like to implement a good throttle algorithm by in .net (C# or VB) but i cannot figure out how could i do that.

The case is my asp.net website should post requests to another website to fetch results. At maximum 300 requests per minute should be sent.

If the requests exceed the 300 limit the other party Api returns nothing (Which is something i would not like to use as a check in my code).

P.S. I have seen solutions in other languages than .net but i am a newbie and please be kind and keep your answers as simple as 123.

Thank you


2 답변


6

You could have a simple application (or session) class and check that for hits. This is something extremely rough just to give you the idea:

public class APIHits {
    public int hits { get; private set; }
    private DateTime minute = DateTime.Now();

    public bool AddHit()
    {
        if (hits < 300) {
            hits++;
            return true;
        }
        else
        {
            if (DateTime.Now() > minute.AddSeconds(60)) 
            {
                //60 seconds later
                minute = DateTime.Now();
                hits = 1;
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}


2

The simplest approach is just to time how long it is between packets and not allow them to be sent at a rate of more than one every 0.2 seconds. That is, record the time when you are called and when you are next called, check that at least 200ms has elasped, or return nothing.

This approach will work, but it will only work for smooth packet flows - if you expect bursts of activity then you may want to allow 5 messages in any 200ms period as long as the average over 1 minute is no more than 300 calls. In this case, you could use an array of values to store the "timestamps" of the last 300 packets, and then each time yoiu receive a call you can look back to "300 calls ago" to check that at least 1 minute has elapsed.

For both of these schemes, the time values returned by Environment.TickCount would be adequate for your needs (spans of not less than 200 milliseconds), as it's accurate to about 15 ms.

Linked


Related

Latest