Skip to main content
Blue Moose logo Blue Moose Field notes
← All articles
drupal

Rate-limit a Drupal endpoint with the Flood API

Developer at a multi-monitor desk writing code

A few months ago I added a small "redeem coupon" endpoint to a Drupal site. It took a code, checked it, returned JSON. It also let anyone script a few thousand guesses per minute against it. Drupal already ships the tool for this: the Flood API, the same thing that throttles failed logins. Here is how I wired it into a custom controller.

What the Flood API gives you

The service is flood, implementing \Drupal\Core\Flood\FloodInterface. I checked the signatures on api.drupal.org:

  • register($name, $window = 3600, $identifier = NULL) records one event.
  • isAllowed($name, $threshold, $window = 3600, $identifier = NULL) returns TRUE while the event count inside the window is below the threshold.
  • clear($name, $identifier = NULL) forgets the events for that identifier.

When $identifier is omitted it falls back to the client IP address. The $name is just a string you choose, so namespace it with your module name to avoid sharing a bucket with core.

The controller

I register only failures, so honest users never get close to the limit, and I clear the bucket on success.

<?php

declare(strict_types=1);

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Flood\FloodInterface;
use Drupal\mymodule\CouponManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

final class CouponController implements ContainerInjectionInterface {

  private const FLOOD_EVENT = 'mymodule.coupon_redeem';
  private const THRESHOLD = 5;
  private const WINDOW = 900;

  public function __construct(
    private readonly FloodInterface $flood,
    private readonly CouponManagerInterface $coupons,
  ) {}

  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('flood'),
      $container->get('mymodule.coupon_manager'),
    );
  }

  public function redeem(Request $request): JsonResponse {
    if (!$this->flood->isAllowed(self::FLOOD_EVENT, self::THRESHOLD, self::WINDOW)) {
      return new JsonResponse(
        ['error' => 'Too many attempts. Try again later.'],
        429,
        ['Retry-After' => (string) self::WINDOW],
      );
    }

    $code = (string) $request->request->get('code', '');
    if (!$this->coupons->redeem($code)) {
      $this->flood->register(self::FLOOD_EVENT, self::WINDOW);
      return new JsonResponse(['error' => 'Invalid code.'], 400);
    }

    $this->flood->clear(self::FLOOD_EVENT);
    return new JsonResponse(['status' => 'ok']);
  }

}

CouponManagerInterface is my own service, a stand-in for whatever validates your input. The route is plain:

mymodule.coupon_redeem:
  path: '/api/coupon/redeem'
  defaults:
    _controller: 'Drupal\mymodule\Controller\CouponController::redeem'
  methods: [POST]
  requirements:
    _access: 'TRUE'

Tracing it by hand

Take one IP sending wrong codes. Attempts one to five each pass isAllowed() (the count is 0 to 4, below 5) and each registers a failure. The sixth request sees five events inside the 900-second window, gets FALSE, and returns 429 without touching the coupon logic at all. That last part matters: the throttle check runs before the expensive work. Once the oldest event ages out of the window the client is allowed again. A correct code resets the counter, which is what clear() is for.

Gotchas

The default identifier is the client IP. Behind a reverse proxy that is the proxy's address unless Drupal's reverse_proxy settings are configured, and then you would throttle every visitor as one. Check that first. Conversely, NAT means many people can share an IP. For logged-in flows, pass an explicit identifier such as the user ID as the last argument to all three calls, or use both buckets with different event names.

Flood events live in the database, and stale rows are removed by cron through garbageCollection(). So this is a good fit for a coupon form or a password-reset style endpoint, but it is not a DDoS defence. For raw volume, stop traffic at the proxy before PHP boots.

BM
Blue Moose
The moose behind Blue Moose. Full-stack PHP developer — Drupal by day, Symfony by night, tests always.