Skip to content

Rate Limiting ​

Introduction ​

The RateLimiter facade is Laravel's rate limiter: it counts attempts per key within a time window. Only the attempts you record are counted, which is what a login form needs (count failures, clear them on success). To limit every request to a route, use the throttle middleware, which uses the same counters.

Cache Configuration ​

Attempts are stored in the cache: the store named by limiter in config/Cache.cs, or the default store. With the memory store each server counts on its own; with redis the counts are shared by every server, and incrementing is atomic.

Basic Usage ​

Attempt runs the callback unless the limit is reached, and counts it:

csharp
var sent = await RateLimiter.Attempt($"send-message:{user.Id}", maxAttempts: 5, async () =>
{
    await SendMessage();
}, decaySeconds: 60);

if (!sent) return Back().With("status", "Too many messages sent!");

Manually Incrementing Attempts ​

csharp
if (await RateLimiter.TooManyAttempts("send-message:" + user.Id, 5))
{
    var seconds = await RateLimiter.AvailableIn("send-message:" + user.Id);
    return Back().With("status", $"You may try again in {seconds} seconds.");
}

await RateLimiter.Hit("send-message:" + user.Id, decaySeconds: 60);

The window starts at the first hit and lasts decaySeconds (default 60). Attempts(key) and RemainingAttempts(key, max) return the counts.

Clearing Attempts ​

csharp
await RateLimiter.Clear("send-message:" + user.Id);

Throttling Logins ​

The AuthController from dotblaze make:auth allows five failed logins per email and IP address, then locks the form for the rest of the minute:

csharp
public async Task<IActionResult> Login(LoginRequest request)
{
    var key = $"login:{request.Email.ToLowerInvariant()}|{HttpContext.Connection.RemoteIpAddress}";
    if (await RateLimiter.TooManyAttempts(key, MaxAttempts))
    {
        var seconds = await RateLimiter.AvailableIn(key);
        return Back().WithErrors(new { Email = $"Too many login attempts. Please try again in {seconds} seconds." }).WithInput();
    }

    var user = await Auth.Validate(new { request.Email, request.Password });
    if (user is null)
    {
        await RateLimiter.Hit(key);
        return Back().WithErrors(new { Email = "These credentials do not match our records." }).WithInput();
    }
    await RateLimiter.Clear(key);

    if (user is ITwoFactorAuthenticatable twoFactor && TwoFactor.Enabled(twoFactor))
    {
        await TwoFactor.Challenge(twoFactor, request.Remember);
        return RedirectRoute("two-factor.login");
    }
    await Auth.Login(user, request.Remember);
    return Intended(Home);
}

Cache.Fake() in a test also gives the rate limiter a fresh, empty store.

This method belongs to the generated auth controller (Home = "/" or your chosen local home URL, MaxAttempts = 5, and the generated LoginRequest). Keep its two-factor challenge: Auth.Attempt signs in immediately and is not a replacement for this flow.

Throttling Routes ​

The throttle middleware counts every request to a route, per user or IP address, and answers 429 over the limit:

csharp
Route.Post<EmailVerificationController>("/email/verification-notification", c => c.Send).Middleware("throttle:6,1");

RateLimiter.For("uploads", request => Limit.PerMinute(10).By(Auth.Id()));
Route.Post<UploadController>("/uploads", c => c.Store).Middleware("throttle:uploads");

See Throttling Requests for the parameters, named limiters, and the api limiter.

Complete Example: Limit and Expiry ​

This Blog command tests counters without sleeping or changing a shared store:

csharp
// app/Commands/LimiterDemo.cs
using DotBlaze;

namespace Blog.Commands;

public class LimiterDemo : Command
{
    public override string Signature => "demo:limiter";
    public override async Task<int> Handle()
    {
        Cache.Fake();
        using var clock = Date.Freeze(
            new DateTimeOffset(2030, 1, 2, 3, 4, 5, TimeSpan.Zero));
        const string key = "docs:limiter";
        await RateLimiter.Hit(key, decaySeconds: 60);
        await RateLimiter.Hit(key, decaySeconds: 60);
        if (!await RateLimiter.TooManyAttempts(key, 2))
            throw new InvalidOperationException("The limit was not reached.");
        clock.Advance(TimeSpan.FromSeconds(61));
        if (await RateLimiter.TooManyAttempts(key, 2))
            throw new InvalidOperationException("The limit did not expire.");
        Line("Limit reached, then expired.");
        return 0;
    }
}

Run dotblaze demo:limiter. For real multi-process throttling, configure a shared Redis/database cache and cache.limiter consistently. Atomic increments do not make a separate check-then-hit sequence a strict concurrency gate.