Skip to main content

Endpoint-Specific Rate Limits

Apply different rate limits to different API endpoints using Unkey. Configure per-route limits with separate quotas for reads and writes.
1 min read

Not all endpoints are equal. Your /health endpoint can handle thousands of requests, but your /ai/generate endpoint calls an expensive LLM. This recipe shows how to apply different rate limits per endpoint.

The pattern#

Full implementation#

Next.js Middleware#

Express with route-specific middleware#

Hono with route groups#

Cost-based limiting#

For endpoints where some operations are more expensive than others, use cost-based limiting:

With a limit of 100/minute:

  • 100 cheap model calls, OR
  • 50 gpt-3.5 calls, OR
  • 10 gpt-4 calls

Best practices#

Use separate namespaces

Different namespaces mean separate counters. A user can hit their AI limit without affecting their regular API quota.

Order patterns correctly

When matching paths, put more specific patterns first. /api/ai/* should come before /api/*.

Consider the user experience

Tight limits on expensive endpoints are fine, but communicate them clearly in your API docs.

Monitor and adjust

Use Unkey analytics to see which endpoints hit limits most often, then adjust accordingly.

Next steps#