next image
next image
Ian Edgehill & Clifford Spielman • November 3, 2026

Rate Limiting in ASP.NET Core Using Redis on Windows

Technical articles and news about Memurai.

Introduction

Rate limiting is a practical safeguard for protecting an API from accidental overload, abusive clients, and unexpected traffic spikes. For single-instance deployments, ASP.NET Core 7 and later include built-in rate limiting middleware, but a more comprehensive solution is needed when the same API runs across multiple application instances.

If each instance tracks request counts only in its own process, the enforced rate limit is limited to each individual instance and not the deployment overall. As a result, a client limited to 100 requests per minute might successfully issue 100 requests per minute per instance. In a load-balanced deployment with four instances, for example, that intended limit of 100 requests unintentionally turns into 400 requests.

Redis® solves this problem by centralizing the request counters that each application instance uses to enforce rate limits. For a given client, every running instance of the API leverages the same Redis counters, so limits are enforced across the deployment rather than separately inside each instance.

For Windows teams, Memurai provides a Redis-compatible server that runs natively on Windows, making it possible to use Redis-backed rate limiting without adding Linux, WSL, or Docker to the application stack.

This article builds a fixed-window rate limiter for ASP.NET Core APIs on Windows using Redis, StackExchange.Redis, and Memurai.

Rate Limiting Strategies

Most API rate limiting implementations use one of three common strategies. They differ mainly in implementation complexity and in how they handle short spikes of requests.

StrategyHow it worksStrengthTradeoff
Fixed Window (Covered in this article)Counts requests in predetermined fixed time windows, such as one minute.Straightforward to implement with Redis counters and TTLs.Allows bursts near time window boundaries.
Sliding WindowCalculates usage over sliding, rolling time intervals.Provides more consistent enforcement near time window boundaries.Requires more tracking and cleanup than a single fixed-window counter.
Token BucketRefills a bucket of request tokens over time and consumes one token per request.Handles uneven request patterns while maintaining an average rate over time.Requires tracking token balance and refill timing, and bucket size affects how much burst traffic is allowed.

This article uses a fixed-window rate-limiting approach because it maps cleanly to the Redis INCR and EXPIRE commands. INCR atomically increments the integer value stored at a Redis key, which makes it a natural fit for counting requests during a fixed time window. EXPIRE assigns a time-to-live to the key so Redis can remove old counters after they are no longer needed.

Fixed-window rate limiting is a practical starting point when the goal is a clear request quota with straightforward implementation, efficient Redis storage, and consistent enforcement across application instances.

Building a Redis Counter for Fixed-Window Rate Limiting

Before implementing a fixed-window rate limiter, we need to define the scope of the limit: whether it applies to the entire API, a specific route, or requests identified by a user account, IP address, API key, or another request identifier.

By convention, the Redis key includes that scope along with a time window identifier, so requests in the same time window increment the same counter and requests during subsequent windows increment their respective counters.

When the user’s first request arrives in a new time window, the application increments a key such as ratelimit:user123:28597642 and sets that key to expire when the time window ends. Later requests from the same user during that same time window increment the same counter.

The ratelimit prefix in the sample key identifies the purpose of the key. The user123 portion identifies the client or subject being limited. The final value identifies the current time window. Refer to the code for the precise construction of the Redis key name.

Redis removes the key when the time window ends, and if the counter exceeds the configured limit, the API rejects the request by returning HTTP 429 Too Many Requests.

The next step in applying fixed-window rate limiting to an actual application is to build the underlying rate limiter mechanism. See the FixedWindowRateLimiter class below.

At a high-level, it performs the following actions:

  1. Construct Redis key based on elements mentioned above, to be used as the request counter
  2. Increment the counter with INCR, which creates it at 1 if it does not exist
  3. Set TTL to the end of the time window if counter is 1
  4. Return results to the caller, including the time left until the window resets

We will build on this later in the article when we implement rate-limiting middleware.

Go ahead and create a new minimal Web API project and add the FixedWindowRateLimiter class. Make sure to include the supporting RateLimitResult record type as well.

using StackExchange.Redis;

public class FixedWindowRateLimiter
{
    private readonly IDatabase _db;
    private readonly int _windowSeconds;
    private readonly int _requestLimit;

    public FixedWindowRateLimiter(IConnectionMultiplexer redis, int windowSeconds, int requestLimit)
    {
        _db = redis.GetDatabase();
        _windowSeconds = windowSeconds;
        _requestLimit = requestLimit;
    }

    public async Task<RateLimitResult> HitCounterAsync(string clientId)
    {
        // Compute the current time window by dividing Unix time seconds by window seconds.
        // All requests from the same user within the same time window share the same key.
        DateTimeOffset now = DateTimeOffset.UtcNow;
        long fixedWindowId = now.ToUnixTimeSeconds() / _windowSeconds;
        DateTimeOffset windowEnd = DateTimeOffset.FromUnixTimeSeconds((fixedWindowId + 1) * _windowSeconds);
        string key = $"ratelimit:{clientId}:{fixedWindowId}";

        long currentCount = await _db.StringIncrementAsync(key);

        if (currentCount == 1)
        {
            await _db.KeyExpireAsync(key, windowEnd.UtcDateTime);
        }

        bool allowed = (currentCount <= _requestLimit);
        return new RateLimitResult(allowed, currentCount, _requestLimit, windowEnd - now);
    }
}

public sealed record RateLimitResult(bool Allowed, long CurrentCount, int RequestLimit, TimeSpan ResetAfter);

The StringIncrementAsync method performs the increment step, which atomically increments the counter value. The first request in a new time window returns 1, so the code sets the key to expire at the end of the window using the KeyExpireAsync method. When the time window ends, Redis removes the counter automatically. The limiter also returns ResetAfter, the time left until the window resets, which the middleware uses later in the article. The same pattern works whether the subject is a user ID, an IP address, or an API key.

Here is a bare bones Program.cs to try out the FixedWindowRateLimiter class.

using StackExchange.Redis;

await using var redis = await ConnectionMultiplexer.ConnectAsync("127.0.0.1:6379");

// Allow 5 requests per 10-second window.
var limiter = new FixedWindowRateLimiter(redis, windowSeconds: 10, requestLimit: 5);

const string clientId = "user123";

// Simulate 7 requests in rapid succession from the same client.
for (int i = 1; i <= 7; i++)
{
    var result = await limiter.HitCounterAsync(clientId);

    Console.WriteLine(result.Allowed
        ? $"Request {i}: allowed (count {result.CurrentCount} of {result.RequestLimit})."
        : $"Request {i}: rejected (count {result.CurrentCount} exceeds limit of {result.RequestLimit}).");
}

On a fresh 10-second window, the final two results should indicate that the request was rejected due to an exceeded rate limit. Run the program again within 10 seconds and every request is rejected from the start: the counter lives in Redis, not in the process, which is exactly what lets several application instances share one limit.

Implementing ASP.NET Core Rate-Limiting Middleware

The next step is to apply our fixed-window rate limiter to incoming HTTP requests. In ASP.NET Core, a custom IMiddleware class is a natural place for that logic: it can inspect each request, identify the rate-limit subject, call the limiter, and either allow the request to continue or return HTTP 429 Too Many Requests when the configured limit has been exceeded.

Building on our existing API, go ahead and add the following RateLimitingMiddleware class. Don’t forget the supporting RateLimitingOptions class as well.

using StackExchange.Redis;

public class RateLimitingOptions
{
    public int WindowSeconds { get; set; } = 60;
    public int RequestLimit { get; set; } = 10;
    public HashSet<string> SkipPaths { get; set; } = new(StringComparer.OrdinalIgnoreCase);
}

public class RateLimitingMiddleware : IMiddleware
{
    private readonly FixedWindowRateLimiter _limiter;
    private readonly RateLimitingOptions _options;

    public RateLimitingMiddleware(IConnectionMultiplexer redis, RateLimitingOptions options)
    {
        _options = options;
        _limiter = new FixedWindowRateLimiter(redis, options.WindowSeconds, options.RequestLimit);
    }

    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        // Skip rate limiting for configured paths such as system health checks.
        if (_options.SkipPaths.Contains(context.Request.Path.Value ?? string.Empty))
        {
            await next(context);
            return;
        }

        // Identify the subject. This demo uses a header called X-Client-Id.
        // Production scenarios might use an authenticated user id, API key, or client IP.
        string clientId = context.Request.Headers["X-Client-Id"].FirstOrDefault()
            ?? "anonymous";

        var result = await _limiter.HitCounterAsync(clientId);

        if (!result.Allowed)
        {
            context.Response.StatusCode = StatusCodes.Status429TooManyRequests;

            int retryAfterSeconds = (int)Math.Ceiling(result.ResetAfter.TotalSeconds);

            context.Response.Headers["Retry-After"] = retryAfterSeconds.ToString();
            await context.Response.WriteAsync($"Rate limit exceeded. Retry after {retryAfterSeconds} seconds.");
            return;
        }

        await next(context);
    }
}

To register the rate-limiting middleware, create a shared IConnectionMultiplexer and add the middleware to the ASP.NET Core pipeline. ConnectionMultiplexer is intended to be reused, so register it once instead of creating a new Redis connection per request. Below is a revised Program.cs which accomplishes this.

using StackExchange.Redis;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
    ConnectionMultiplexer.Connect("127.0.0.1:6379"));

builder.Services.AddSingleton(new RateLimitingOptions
{
    WindowSeconds = 60,
    RequestLimit = 10,
    SkipPaths = new(StringComparer.OrdinalIgnoreCase) { "/health" }
});

builder.Services.AddTransient<RateLimitingMiddleware>();

var app = builder.Build();

app.UseMiddleware<RateLimitingMiddleware>();

app.MapGet("/health", () => "OK");
app.MapGet("/api/data", () => "Here is some rate-limited data.");

app.Run();

The RateLimitingMiddleware implementation follows this request flow:

  1. Check whether the current path should bypass rate limiting, such as a health-check endpoint. If so, pass the request to the next middleware immediately.
  2. Identify the request subject for rate-limiting purposes, which for this demo is in the X-Client-Id header, or anonymous if the header is not present.
  3. Call HitCounterAsync to increment the Redis counter for the current subject and time window, creating the counter if needed.
  4. If the request exceeds the rate limit, return HTTP 429 Too Many Requests, set Retry-After to the time remaining in the current window, and stop the request before it reaches the endpoint.
  5. If the request is still within the rate limit, call next(context) so the request can continue through the ASP.NET Core pipeline.

With this middleware approach, each running API instance uses the same Memurai server and the same Redis key convention. When requests fall under the same rate limit, they increment and check the same Redis counter. The result is that the request count is shared across the deployment instead of being isolated inside each application process.

The middleware returns 429 when the request count exceeds the configured limit. It also sets the Retry-After header to the number of seconds until the current window resets, giving clients a practical signal for when they can retry.

We can test our API and new fixed-window rate-limiting middleware using curl.exe as follows, remembering to change the port number as needed:

curl.exe -H "X-Client-Id: user123" -i http://localhost:5099/api/data

Because the /api/data route is not excluded from rate limiting, you should see output such as the following (headers trimmed):

HTTP/1.1 200 OK

Here is some rate-limited data.

Running that command more than 10 times in a 60 second time window will generate something to the effect of the following, assuming we exceeded the limit 5 seconds into the time window:

HTTP/1.1 429 Too Many Requests
Retry-After: 55

Rate limit exceeded. Retry after 55 seconds.

If we try any routes added to RateLimitingOptions.SkipPaths such as /health, we bypass rate limiting and get the following every time:

HTTP/1.1 200 OK

OK

Verifying the Counter in Memurai

We can inspect the Redis counter keys directly when testing or troubleshooting the rate limiter. Because the key name includes a lengthy time-related value, it is often easiest to find matching rate-limit keys first using SCAN with MATCH, then inspect specific keys with GET and TTL.

memurai-cli.exe SCAN 0 MATCH "ratelimit:user123:*"

SCAN returns a batch of matching keys along with a cursor value. Keep passing the returned cursor into the next SCAN call until it returns 0, which means the iteration is complete. See the Redis SCAN documentation for details.

Then home in on specific keys, which will look similar to the following:

memurai-cli.exe GET "ratelimit:user123:28597642"
memurai-cli.exe TTL "ratelimit:user123:28597642"

GET returns the request count stored at that key. TTL returns the remaining lifetime of that Redis key in seconds. Because the key expires exactly when its window ends, its TTL is the time left in the current window. When the TTL reaches zero, Redis removes the old counter for cleanup purposes, and new requests use a different counter because the calculated fixed-window ID has changed. See the fixedWindowId assignment in the HitCounterAsync method and how it contributes to the counter key name.

A positive TTL is the number of seconds left in the current window. A -2 result means the key does not currently exist, usually because the window has ended or the key has not been created yet.

Getting Started with Memurai

In this article, we learned how to implement Redis fixed-window rate limiting in .NET using StackExchange.Redis and Memurai as a Redis-compatible native Windows Service. By using Memurai, we eliminate the need for additional layers such as Linux, containers, or WSL.

Memurai is free for development and testing, making it straightforward to continue learning about rate limiting with Redis and other concepts from this article on a local or staging machine. Memurai Developer has three restrictions that are important to be aware of before you scale up: a maximum uptime of 10 days before an automatic shutdown, a maximum of 10 unique connected IP addresses, and a RAM cap of 50% of available system memory.

If you're ready to move beyond Memurai Developer, register on the Memurai portal for a free 90-day Memurai Enterprise trial and run everything in this article without the listed restrictions.

Redis® is a registered trademark of Redis Ltd. Any rights therein are reserved to Redis Ltd. Any use by Memurai is for referential purposes only and does not indicate any sponsorship, endorsement, or affiliation between Redis and Memurai.

Categories