Laravel Rate Limiting and Cloudflare Turnstile Guide ~ Ibrahim Kaya
×
Web Security

Laravel Rate Limiting and Cloudflare Turnstile Guide

İbrahim Kaya Published: Updated: 3 min read
Laravel Rate Limiting and Cloudflare Turnstile Guide
Contents

Public web applications deal with automated traffic constantly, including credential stuffing, brute-force logins, and automated scrapers. Handling these requires two separate controls: capping request volume and identifying automated clients.

Laravel handles request frequency through its RateLimiter facade and throttle middleware. Cloudflare Turnstile handles bot verification in the background without forcing users through image puzzles. Used together, they protect server resources without blocking actual users.

Laravel RateLimiter and throttle middleware

Laravel tracks interaction counts over time using your application's cache driver. The standard approach is attaching the throttle middleware to routes in your route files.

routes/api.php
use Illuminate\Support\Facades\Route;

Route::middleware('throttle:60,1')->group(function () {
    Route::get('/transactions', [TransactionController::class, 'index']);
});

This rule limits clients to 60 requests per minute. If a client exceeds that count, Laravel returns an HTTP 429 Too Many Requests response. Under heavy traffic, using Redis as the cache store prevents race conditions on counter increments:

config/cache.php
'default' => env('CACHE_STORE', 'database'),
'limiter' => 'redis',

Custom limiters with the RateLimiter facade

When fixed thresholds are too rigid, RateLimiter::for() lets you write rules based on IP address, user account, or subscription tier. You typically register these in the boot method of AppServiceProvider.

app/Providers/AppServiceProvider.php
namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        RateLimiter::for('auth', function (Request $request) {
            return Limit::perMinute(5)->by($request->ip());
        });
    }
}

For operations outside HTTP middleware, such as queued jobs or password reset triggers, RateLimiter::attempt() handles execution and countdowns directly:

PHP
use Illuminate\Support\Facades\RateLimiter;

$executed = RateLimiter::attempt(
    'dispatch-report:'.$user->id,
    $perMinute = 2,
    function () {
        // Execute report generation
    },
    $decayRate = 60
);

if (! $executed) {
    $seconds = RateLimiter::availableIn('dispatch-report:'.$user->id);
    return response()->json(['message' => "Retry after {$seconds} seconds."], 429);
}

Cloudflare Turnstile bot detection

Rate limits block rapid bursts of traffic, but they do not stop slow crawlers that cycle through residential IP addresses. Cloudflare Turnstile addresses this by inspecting browser signals directly rather than displaying CAPTCHA challenges.

Community packages like coderflex/laravel-turnstile or njoguamos/laravel-turnstile handle integration. Install the package through Composer and set your site keys:

bash
composer require coderflex/laravel-turnstile
php artisan vendor:publish --tag="turnstile-config"
.env
TURNSTILE_SITE_KEY=0x4AAAAAAxxxxxxxxxxxxxx
TURNSTILE_SECRET_KEY=0x4AAAAAAyyyyyyyyyyyyyy

Validating tokens in form requests

When a user submits a protected form, the Turnstile widget includes a cf-turnstile-response token. The backend must check this token against Cloudflare's validation endpoint before processing the request.

app/Http/Requests/LoginRequest.php
namespace App\Http\Requests;

use Coderflex\LaravelTurnstile\Rules\TurnstileCheck;
use Illuminate\Foundation\Http\FormRequest;

class LoginRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
            'cf-turnstile-response' => ['required', new TurnstileCheck()],
        ];
    }
}

In CI pipelines and local testing, you can set TURNSTILE_ENABLED=false so test suites do not make outbound calls to Cloudflare.

Combining both layers

Rate limits and bot checks work best together:

  • Apply strict throttle limits to login and registration routes to slow down credential stuffing.
  • Use Turnstile validation on sensitive forms to block headless browsers and scripts.
  • Call RateLimiter::clear() on successful logins so valid users do not get locked out after an initial mistake.

Overall rating

0.0 / 5

Based on 0 reviews

Rate this post

5 out of

Reviews

No reviews yet.