Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of current limiting Control based on sliding window in ASP.NET Core

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to share with you the relevant knowledge of ASP.NET Core current-limiting control method based on sliding window. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Foreword:

In the actual project, in order to ensure the stable operation of the server, it is necessary to limit the access frequency of the interface to avoid excessive pressure on the server due to frequent requests from the client.

At present, AspNetCoreRateLimit is the most commonly used current limiting solution under ASP.NET Core.

Looking at its implementation code, I found that it uses a fixed window algorithm.

Var entry = await _ counterStore.GetAsync (counterId, cancellationToken); if (entry.HasValue) {/ / entry has not expired if (entry.Value.Timestamp + rule.PeriodTimespan.Value > = DateTime.UtcNow) {/ / increment request count var totalCount = entry.Value.Count + _ config.RateIncrementer?.Invoke ()? 1 / / deep copy counter = new RateLimitCounter {Timestamp = entry.Value.Timestamp, Count = totalCount};}} II. Fixed window algorithm

The fixed window algorithm divides the timeline into fixed-size windows and assigns a counter to each window. Each request is mapped to a window according to its time of arrival. If the counter in the window has reached the limit, the request that falls in this window is rejected.

For example, if we set the window size to one minutes, allow ten requests per minute:

ASP.NET Core implements current-limiting control based on sliding window algorithm # yyds dry goods inventory # _ sliding window

Requests for 59 seconds will be blocked because 10 requests have already been accepted. The counter returns to zero in 1 minute, so a request of 1 minute and 01 seconds is acceptable.

The main problem of the fixed window algorithm is that if a large number of requests occur at the edge of the window, it will lead to the invalidation of the current limiting policy.

For example, nine requests are received in 59 seconds, and another 10 requests can be received in 1 minute 01 seconds, which is equivalent to 20 requests allowed per minute.

Third, sliding window algorithm

The sliding window is similar to the fixed window algorithm, but it calculates the estimate by adding the weighted count from the previous window to the count in the current window, and if the estimate exceeds the count limit, the request is blocked.

The specific formula is as follows:

Estimate = previous window count * (1-current window elapsed time / unit time) + current window count

For example, suppose the limit is 10 per minute:

There are nine requests in the window [00:00, 00:01) and five requests in the window [00:01, 00:02). For requests that arrive at 01:15, that is, the 25% position of the window [00:01, 00:02), the request count is calculated by the formula: 9 x (1-25%) + 5 = 11.75 > 10. Therefore, we reject this request.

Even if neither window exceeds the limit, the request is rejected because the weighted sum of the previous and current windows does exceed the limit.

IV. Realization

According to the above formula, the code to implement the sliding window algorithm is as follows:

Public class SlidingWindow {private readonly object _ syncObject = new object (); private readonly int _ requestIntervalSeconds; private readonly int _ requestLimit; private DateTime _ windowStartTime; private int _ prevRequestCount; private int _ requestCount; public SlidingWindow (int requestLimit, int requestIntervalSeconds) {_ windowStartTime = DateTime.Now; _ requestLimit = requestLimit; _ requestIntervalSeconds = requestIntervalSeconds } public bool PassRequest () {lock (_ syncObject) {var currentTime = DateTime.Now; var elapsedSeconds = (currentTime-_ windowStartTime) .TotalSeconds; if (elapsedSeconds > = _ requestIntervalSeconds * 2) {_ windowStartTime = currentTime; _ prevRequestCount = 0; _ requestCount = 0; elapsedSeconds = 0 } else if (elapsedSeconds > = _ requestIntervalSeconds) {_ windowStartTime = _ windowStartTime.AddSeconds (_ requestIntervalSeconds); _ prevRequestCount = _ requestCount; _ requestCount = 0; elapsedSeconds = (currentTime-_ windowStartTime) .TotalSeconds;} var requestCount = _ prevRequestCount * (1-elapsedSeconds / _ requestIntervalSeconds) + _ requestCount + 1 If (requestCount {context.Response.StatusCode = StatusCodes.Status403Forbidden; return Task.CompletedTask;}, EndpointMetadataCollection.Empty, "current limit");} await next (context);}}

It should be noted that when we register for Middleware, we must use singleton mode to ensure that all requests pass the same SlidingWindow count:

Services.AddSingleton (); these are all the contents of the article "ASP.NET Core current limiting Control based on sliding window". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report