You are here
Home > ASP.NET Core > Rate Limiting in .NET 7

Rate Limiting in .NET 7

Rate Limit API Requests

With the release of .NET 7, your applications will see an increase in performance and new features for C# 11, F# 7, .NET MAUI, ASP.NET Core/Blazor, Web APIs, WinForms, WPF and more. Download .NET 7 for Windows, macOS, and Linux. A nice feature that has been added is rate limiting.

Not quite what you are looking for? Try these links instead:

Get the code from my GitHub repo if you want to follow along. Let’s look at the new rate limiting middleware now available to developers.

ASP.NET Core Rate Limiting Middleware

Rate limiting is a method to control the amount of traffic a web application or API can receive. It limits the number of requests an application can make at a specific time. Implementing it is simple as you will see from the code below.

The Service

For this demo, I have created an Interface for a service that will return the current time. Here I use the new TimeOnly struct, introduced in .NET 6.

using System;
namespace RateLimitAPI.Services
{
    public interface IGetTimeService
    {
        TimeOnly currentTime();
    }
}

My Service returns the implementation of the Interface to get the current time.

using System;
namespace RateLimitAPI.Services
{
    public class GetTimeService : IGetTimeService
    {
	public GetTimeService()
	{
	}

        public TimeOnly currentTime()
        {
            return TimeOnly.FromDateTime(DateTime.Now);
        }
    }
}

Add Rate Limiting to the Program.cs File

Inside the Program.cs file, I added my service as a scoped service and then set up the rate limiter. The rate limiter will only permit one request every 10 seconds. If the requests exceed that limit, it will only queue three requests.

using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;
using RateLimitAPI.Services;

namespace RateLimitAPI;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
                
        builder.Services.AddControllers();
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();

        builder.Services.AddScoped<IGetTimeService, GetTimeService>();
        builder.Services.AddRateLimiter(_ => _
            .AddFixedWindowLimiter(policyName: "LimiterPolicy", options =>
            {
                options.PermitLimit = 1;
                // Only allow 1 request every 10 seconds
                options.Window = TimeSpan.FromSeconds(10); 
                options.QueueProcessingOrder =     QueueProcessingOrder.OldestFirst;
                // Only queue 3 requests when we go over that limit
                options.QueueLimit = 3; 
            }));

        var app = builder.Build();
        app.UseRateLimiter();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseHttpsRedirection();
        app.UseAuthorization();
        app.MapControllers();
        app.Run();
    }
}

The Time Controller

Inside my controller, I add the EnableRateLimiting attribute to my Action. This is it. You need not do anything else to enable rate limiting on your service call.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using RateLimitAPI.Services;

namespace RateLimitAPI.Controllers
{
    [ApiController]
    public class TimeController : Controller
    {
        IGetTimeService _service;

        public TimeController(IGetTimeService service)
        {
            _service = service;
        }

        [HttpGet]
        [Route("[controller]/time-current")]
        [EnableRateLimiting("LimiterPolicy")]
        public IActionResult Index()
        {
            return Ok(_service.currentTime());
        }
    }
}

Running the Rate Limiting API

If you run the API and execute it in Swagger, you will see that the service returns the current time as expected.

Making the API call to the GetTime Service.

If you execute a second request immediately after that, you will see that Swagger does not execute the request immediately. When it does return the current time, ten seconds have elapsed.

Rate limiting the API call

Your service call is now rate limited as set up in your Program.cs file.

Dirk Strauss
Dirk is a Software Developer from South Africa. He loves all things Technology and is slightly addicted to Jimi Hendrix. Apart from writing code, he also enjoys authoring books and articles. "I love sharing knowledge and connecting with people from around the world. It's the diversity that makes life so beautiful." Dirk feels very strongly that pizza is simply not complete without Tabasco, that you can never have too much garlic, and that cooking the perfect steak is an art he has almost mastered.
https://dirkstrauss.com

Similar Articles

Top