How to fix API Rate Limit Exhaustion
in Plug
Executive Summary
API endpoints lacking rate limiting are high-value targets for DoS, credential stuffing, and scraping. In Elixir/Plug, failing to throttle requests allows an attacker to saturate the Erlang VM's process mailbox or exhaust database connection pools. To mitigate this, we must intercept requests early in the pipeline and enforce a sliding window or token bucket strategy.
The Vulnerable Pattern
defmodule MyApp.Router do use Plug.Router plug :match plug :dispatchVULNERABLE: This endpoint has no protection.
An attacker can automate thousands of requests per second,
leading to resource exhaustion or data exfiltration.
get “/api/v1/sensitive-data” do data = MyApp.Database.get_expensive_query() send_resp(conn, 200, data) end end
The Secure Implementation
The fix utilizes the 'Hammer' library to implement a sliding window counter. By inserting the 'RateLimiter' plug at the top of the pipeline, we ensure that every incoming request is validated against a backend store (like Redis or ETS). If the 'client_key' exceeds the defined threshold (5 requests/10s), the plug calls 'halt(conn)', immediately terminating the request lifecycle and returning a 429 status code. This prevents the application logic and database from ever processing the malicious traffic.
defmodule MyApp.Plugs.RateLimiter do import Plug.Conndef init(opts), do: opts
def call(conn, _opts) do # Identify client by IP; in production, use X-Forwarded-For if behind a proxy client_key = “request_count:#{inspect(conn.remote_ip)}”
# Limit: 5 requests per 10 seconds case Hammer.check_rate(client_key, 10_000, 5) do {:allow, _count} -> conn {:deny, _limit} -> conn |> put_resp_header("retry-after", "10") |> send_resp(429, "Rate limit exceeded. Slow down, hacker.") |> halt() endend end
defmodule MyApp.Router do use Plug.Router
SECURE: Plug the rate limiter before matching and dispatching
plug MyApp.Plugs.RateLimiter plug :match plug :dispatch
get “/api/v1/sensitive-data” do send_resp(conn, 200, “Protected Data”) end end
Your Plug API
might be exposed to API Rate Limit Exhaustion
74% of Plug apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.