Rate limiting with rack-attack

Protecting the API from abuse and runaway clients

Pagination caps how much a single request can cost you. Rate limiting caps how many requests a single client can make in a stretch of time β€” the other half of protecting the API from abuse, whether that's a scraper hammering /walkers, a buggy client stuck retrying in a tight loop, or a real attacker probing /login.

rack-attack is a gem that does this as Rack middleware β€” meaning it runs BEFORE your request ever reaches a Rails controller. A throttled request never touches current_user, never queries the database, never runs any of your application code at all; rack-attack just returns a 429 Too Many Requests response straight from the middleware layer. That's a deliberate design choice: the whole point of protecting against abuse is to reject cheaply, before the expensive parts of your stack ever get involved.

A throttle block gives rack-attack a name, a limit, a period, and a block that returns the thing to count by (an IP, an API token, a user id β€” whatever identifies "one client"). Once a client crosses limit requests within period, rack-attack starts returning 429 for the rest of that window. The 429 status itself is the client's cue: it means "you're fine, just slow down" β€” not a permanent ban, just back-pressure.

This is the exact same idea as the Python course's rate-limit module, just at a different layer: there, a decorator wraps one endpoint function inside the app; here, middleware wraps the WHOLE app before any endpoint runs. Same concept β€” cap how often something can happen in a window β€” applied one layer earlier.