简体   繁体   中英

Does the Microsoft Graph SDK for .NET automatically handle rate limits?

Microsoft rate-limits certain Graph endpoints to 10,000 requests per 10 minutes ( source ). If the limit is reached, the Retry-After header indicates how long to wait before sending another request.

Is this handled automatically by the Graph SDK? If not, what steps should the caller take?

I don't believe the Graph C# SDK automatically retries when requests are throttled, but there is a sample at https://github.com/venkateshchepuru/aspnet-webhooks-rest-sample/blob/87b1aa4967392096d22d382b7a8848bd9c0afeea/GraphWebhooks/Helpers/GraphHttpClient.cs that shows logic for exponential backoff for 429s and 503s.

This sample also follows a number of other best practices as well - max retries, logging request ids and timestamps, exponential backoff, etc.

Code for parsing the retry after header:

private TimeSpan GetServerRecommendedPause(HttpResponseMessage response)
    {
        var retryAfter = response?.Headers?.RetryAfter;
        if (retryAfter == null)
            return TimeSpan.Zero;

        return retryAfter.Date.HasValue
            ? retryAfter.Date.Value - DateTime.UtcNow
            : retryAfter.Delta.GetValueOrDefault(TimeSpan.Zero);
    }

Code for determining to use retry-after header or exponential backoff:

if (((int)response.StatusCode == 429) || ((int)response.StatusCode == 503))
            {
                // Retry Only After the server specified time period obtained from the response.
                TimeSpan pauseDuration = TimeSpan.FromSeconds(Math.Pow(2, attempt));
                TimeSpan serverRecommendedPauseDuration = GetServerRecommendedPause(response);
                if (serverRecommendedPauseDuration > pauseDuration)
                {
                    pauseDuration = serverRecommendedPauseDuration;
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM