DDoS Protection

Rhapsody includes a built‑in DDoS (Distributed Denial of Service) protection middleware that limits the number of requests a single IP address can make within a given time window. When the limit is exceeded, the middleware returns a 429 Too Many Requests response with a Retry‑After header, preventing abuse.

How It Works

The protection is implemented as a global middleware (Rhapsody\Core\Middleware\DdosMiddleware). It runs on every request and tracks the request count per IP address using the framework’s cache system (file, Redis, etc.).

Once an IP exceeds the configured max_requests within the time_window (in seconds), it is blocked for the block_duration (in seconds). During the block period, all subsequent requests from that IP receive a 429 response.

Configuration

All settings are defined in your config.php file under the DDoS keys. You can also override them via environment variables in your .env file.

Config Key Environment Variable Default Description
ddos_max_requests DDOS_MAX_REQUESTS 60 Maximum allowed requests within the time window.
ddos_time_window DDOS_TIME_WINDOW 60 Time window in seconds.
ddos_block_duration DDOS_BLOCK_DURATION 300 How long (in seconds) to block the IP after the limit is exceeded.
ddos_whitelist DDOS_WHITELIST 127.0.0.100,::100 Comma‑separated list of IP addresses that are never blocked (useful for internal services).
ddos_blacklist DDOS_BLACKLIST — Comma‑separated list of IPs that are immediately blocked.

Example .env Entries

DDOS_MAX_REQUESTS=10
DDOS_TIME_WINDOW=30
DDOS_BLOCK_DURATION=120
DDOS_WHITELIST=127.0.0.1,::1,192.168.1.100

Enabling / Disabling

The middleware is automatically enabled when you include it in the middleware.global array in config.php. To disable it, simply remove it from that list.

Customising the Response

The default response is a user‑friendly HTML page. If you need to return JSON (for API endpoints), you can override the rateLimitExceededResponse() method in your own middleware or extend the core class.

Cache Driver

The rate limiter uses the framework’s cache driver (file, redis, or memcached). For production, it is recommended to use a shared cache like Redis when running multiple servers behind a load balancer, so the request counters are synchronised.

Testing

You can simulate heavy traffic using tools like ab (Apache Bench) or a simple loop with curl:

for i in {1..20}; do curl -s -o /dev/null -w "Request $i: %{http_code}\n" http://your-site.com/; done

After exceeding the limit, you should see 429 status codes.

More Information

The DDoS protection is part of the core middleware system. For more advanced use cases (e.g., endpoint‑specific limits, CAPTCHA challenges), you can extend the provided classes or write your own middleware.