Configuring Cloudflare Rate Limiting for API Protection: A Practical Guide
Set up Cloudflare Rate Limiting to guard your APIs from abuse while keeping legitimate traffic smooth. Learn how to choose between fixed‑window and sliding‑window algorithms, deploy granular rules, and verify effectiveness with built‑in dashboards and API exports.
12 Sept 2025, 18:55 UTC

Desired Outcome
Protect your authentication and data‑retrieval endpoints from request‑volume abuse while ensuring that legitimate burst traffic (e.g., a user refreshing a page or a mobile app updating in quick succession) is still served. The goal is to configure Cloudflare Rate Limiting rules that are:
- Granular – applied to specific URIs or HTTP methods.
- Adaptive – choose the right windowing algorithm for your traffic pattern.
- Observable – easy to audit via the dashboard or API.
- Recoverable – quick rollback or threshold adjustment if legitimate traffic is affected.
Prerequisites
- Cloudflare Account & Zone – You must have a Cloudflare account with access to the zone you want to protect. Rate Limiting is available on Pro, Business, and Enterprise plans; check your plan’s feature set.
- API Token – For programmatic rule creation and export, generate an API token with the
Zone: Rate Limit: Editpermission. - Targeted Endpoints – Identify the exact paths or methods you want to protect (e.g.,
POST /api/login). - Baseline Traffic Data – Optionally run a short traffic analysis (e.g., via Cloudflare Analytics or a custom script) to determine typical request rates and burst sizes.
Focused Procedure
1. Decide on the Windowing Algorithm
Cloudflare offers two algorithms:
- Fixed‑Window – Counts requests in discrete, non‑overlapping windows (e.g., 60‑second blocks). It allows a burst up to the threshold within a window but can reset abruptly, potentially causing legitimate traffic to be blocked when a new window starts.
- Sliding‑Window – Maintains a moving window that slides with each request, smoothing out bursts. It’s more complex but reduces the chance of legitimate spikes being blocked.
For most API endpoints that expect occasional bursts (login, token refresh), a sliding‑window is recommended. For high‑throughput static asset delivery where traffic is evenly distributed, a fixed‑window can suffice.
2. Create a Rate Limiting Rule via the Dashboard
- Navigate to
Security > Rate Limitingin the Cloudflare dashboard. - Click + Create a rule.
- Fill in the rule details:
- Name:
login-api-rate-limit - URI Pattern:
/api/login(use^and$for exact matches). If you want to protect all POST requests, use^/api/.*$withMethod = POST. - Threshold: 10 requests.
- Window: 60 seconds.
- Algorithm: Sliding‑Window.
- Response: 429 Too Many Requests with a custom JSON body.
- Name:
- Enable the rule and set Action to
BlockorChallengebased on risk tolerance. - Save the rule.
3. Deploy the Rule via the API (IaC Friendly)
Below is a curl example that creates the same rule programmatically. Replace YOUR_ZONE_ID and YOUR_API_TOKEN with your actual values.
curl -X POST "https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/rate_limit/rules" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"match": {
"url": {
"prefix": "/api/login"
},
"methods": ["POST"],
"request_headers": {
"User-Agent": {
"contains": "Mozilla"
}
}
},
"threshold": 10,
"period": 60,
"action": {
"mode": "block",
"response": {
"status": 429,
"content_type": "application/json",
"body": "{\"error\":\"Rate limit exceeded\"}"
}
},
"mode": "sliding-window",
"description": "Protect login endpoint"
}'
Check the response for "success": true and note the id returned – you’ll need it for updates or deletions.
4. Verify Rule Effectiveness
- In the dashboard, navigate to the rule’s detail page. The
HitsandBlockedcounters will fill as traffic passes through. - Use the
Analyticstab to view a time‑series of requests and blocks over the last 24 hours. - Export the current rule set via the API to compare against your IaC definitions:
curl -X GET "https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/rate_limit/rules" \ -H "Authorization: Bearer YOUR_API_TOKEN"
5. Monitor and Adjust
Set up a simple alert (e.g., via Cloudflare Workers or a monitoring service) that triggers when the blocked request count exceeds a threshold within a minute. This early warning helps you catch overly aggressive limits before users notice.
Expected Checks
- Rule Status – Verify the rule is
Activeand notPaused. - Hit/Block Ratio – A healthy ratio is low block counts relative to hits; a sudden spike indicates a mis‑configured threshold.
- Latency Impact – Measure end‑to‑end latency for legitimate traffic; a noticeable increase may mean the rule is throttling too aggressively.
- IP Grouping Effectiveness – If you suspect many users share a single IP (e.g., behind a corporate proxy), consider adding
source_iporcf_connecting_ipto the match criteria.
Recovery Options
- Temporarily Disable the Rule – In the dashboard, toggle the rule to
Pausedor delete it via the API. This stops blocking while you investigate. - Adjust Thresholds – Increase
thresholdorperiodvalues. For sliding windows, a longer period smooths bursts but may delay detection of sustained abuse. - Switch Algorithm – If fixed‑window resets are causing legitimate traffic to be blocked at window boundaries, switch to sliding‑window. Conversely, if a sliding window is too slow to react to a sudden spike, revert to fixed‑window with a smaller period.
- Add Exemptions – Use
match.excludeto whitelist known good IP ranges or user agents.
Limitations & Practical Checks
- Rate limits are enforced per client IP. NAT or shared proxies can cause multiple legitimate users to share a bucket, leading to false positives.
- Cloudflare’s bucket state is eventually consistent; resets may not align perfectly with your 60‑second window, causing brief overlaps.
- Rate limits run before WAF rules. An attacker can bypass them by targeting application‑level vulnerabilities; consider combining with WAF or bot management.
- High‑volume APIs may need a custom
modeoflogto monitor without blocking, then gradually tighten thresholds.
To validate that your rule behaves as expected, run a controlled test: send 20 requests to /api/login from a single IP with a 2‑second interval. Verify that the first 10 pass and the remaining 10 receive a 429 response. Adjust the threshold if you see legitimate traffic being blocked during normal usage patterns.
Conclusion
Cloudflare Rate Limiting is a powerful tool for protecting APIs from abuse, but it requires a clear understanding of your traffic patterns, careful rule construction, and ongoing monitoring. By following this guide, you can set up granular, algorithm‑aware rules, verify them through dashboards and API exports, and quickly recover if legitimate traffic is impacted.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.