How to create connections limit

Good afternoon,
I need to create a system with which to limit the number of simultaneous accesses to the apphost. The idea is to define a License Manager with which to indicate the number of hosts that will be able to access the apphost simultaneously.

Ideas?

Checkout the Rate Limit approach taken in

Another alternative if you are using ServiceStack 8.1+ with Endpoint Routing is to use the ASP.NET built in rate limiter middleware, there is a documented example of a Concurrency limiter, however it sounds like you might need to do it on a per user basis so you might need to roll something more specific for that.

As an example of integration with ServiceStack, you can create it and apply the rate limiter in the UseServiceStack options.

var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;

services.AddServiceStack(typeof(MyServices).Assembly);

// Simple fixed limiter example
builder.Services.AddRateLimiter(_ => _
    .AddFixedWindowLimiter(policyName: "fixed", options => {
        options.PermitLimit = 4;
        options.Window = TimeSpan.FromSeconds(12);
        options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
        options.QueueLimit = 2;
    }).OnRejected = (context, token) => {
    context.HttpContext.Response.StatusCode = 429;
    return new ValueTask();
});

var app = builder.Build();

app.UseRateLimiter();

//.. other config

app.UseServiceStack(new AppHost(), options => {
    options.MapEndpoints();
    options.RouteHandlerBuilders.Add((routeBuilder, operation, method, route) =>
    {
        routeBuilder.RequireRateLimiting(policyName: "fixed");
    });
});

app.Run();

Make sure you have the latest version of ServiceStack, as support for Endpoint Routing is a new feature for ServiceStack 8.1+.

1 Like