Saltar para o conteúdo
Voltar aos artigos

Cloudflare rate limiting: the rules to set for login, OTP, API and checkout

Which Cloudflare rate limiting rules to write first, what each plan allows, and how to set thresholds that stop credential stuffing without locking out customers behind shared IPs.
Cloudflare rate limiting: the rules to set for login, OTP, API and checkout

Ouvir este artigo

0:00 / –:––

Pontos principais

  • Spend your few rate limiting rules on the routes where abuse costs money, starting with login, one-time codes, password reset and checkout.
  • On Business and above, count failed responses rather than every request, so customers who sign in normally never reach the limit.
  • Mobile networks and offices put many people behind one IP address, so set thresholds from your own traffic, not from a template.
  • Rate limiting counters are per data centre and not exact. Treat a rule as a brake on abuse, not a quota.

It is common to find a Cloudflare account with no rate limiting rule at all, or with one rule copied from a forum post that counts every request to / and never fires. Meanwhile the login form takes thousands of password guesses a day, and the one-time code endpoint sends SMS messages someone else is paying for.

Rate limiting rules are one of the cheapest controls Cloudflare offers, and on most plans you get very few of them. This post covers which rules to write first, the thresholds to start from, and the mistakes that lock out real customers.

What a rate limiting rule does, and what it does not

A rate limiting rule counts requests that match an expression, grouped by characteristics such as the client IP. When one group goes over the rate you set within a period, Cloudflare applies an action: block, a challenge, or (on Enterprise) log.

Three details matter before you write anything:

  • It is not a precise quota. Cloudflare says rate limiting rules are not designed to let an exact number of requests reach your origin. Counters are kept per data centre and can lag by a few seconds1. If your API contract promises "exactly 100 requests a minute", enforce that in the application.
  • Order matters. Rate limiting runs after WAF custom rules and before the managed rules and Super Bot Fight Mode2. A custom rule that blocks or skips a request stops it before the rate limit ever counts it.
  • Challenges throttle rather than lock out. On Free, Pro and Business, a rule with a challenge action applies only to requests over the rate, and a visitor who passes the challenge starts counting again. A block can last for the duration you choose.
The order of Cloudflare's security phases. A request blocked or challenged in an earlier phase never reaches the later ones.

What your plan gives you

The plan decides how many rules you have and what they can count on.

PlanRulesCount byLongest periodLongest blockCount only certain responses
Free1IP10 seconds10 secondsNo
Pro2IP1 minute1 hourNo
Business5IP, or IP with NAT support10 minutes1 dayYes
EnterpriseBy contractIP, or IP with NAT support; headers, cookies, API keys, ASN and more with Advanced Rate LimitingUp to about 18 hours1 day, or custom through the APIYes

Source: Cloudflare's rate limiting documentation, checked 20 October 202613. Plan limits change, so check the current figures before you plan around them. How the WAF features differ by plan is on our Cloudflare WAF page.

With one or two rules, you can't protect everything. Pick the routes where abuse costs you money or customers.

The four rules to write first

1. Login: count failures, not attempts

Credential stuffing is the attack rate limiting is best at. Attackers replay leaked username and password pairs, many attempts per IP address, against your login endpoint.

On Business and above, use a counting expression so the rule only counts failed sign-ins. A customer who types the right password never adds to the counter. This is the pattern Cloudflare uses in its own guidance4:

matching-expression.txtText
http.request.uri.path eq "/login" and http.request.method eq "POST"
counting-expression.txtText
http.request.uri.path eq "/login" and http.request.method eq "POST" and http.response.code in {401 403}
With a counting expression, only failed sign-ins add to the counter.

The counting expression does not inherit the matching expression, so repeat the path and method in it. Counting happens after your origin responds, so the application must return a real 401 or 403 on a failed sign-in. If it returns 200 with an error message in the page, the rule sees nothing to count.

Cloudflare's example uses three tiers on the same route: a managed challenge at 4 failures a minute, another at 10 failures in 10 minutes, and a one-day block at 20 failures an hour. That is a reasonable start for a consumer login. Tighten it for an admin panel; loosen it if your users often mistype one-time passwords that share the endpoint.

On Free and Pro you cannot count by response, so the rule counts every POST to the login path by IP. Set the threshold well above what a person can type, for example 10 requests in 10 seconds on Free, and let the challenge do the work.

Here is the Business-plan version of the first tier through the API, in the http_ratelimit phase:

login-rule.jsonJSON
{
  "description": "Login failures per IP",
  "expression": "(http.request.uri.path eq \"/login\" and http.request.method eq \"POST\")",
  "action": "managed_challenge",
  "ratelimit": {
    "characteristics": ["ip.src", "cf.colo.id"],
    "period": 60,
    "requests_per_period": 4,
    "mitigation_timeout": 0,
    "counting_expression": "(http.request.uri.path eq \"/login\" and http.request.method eq \"POST\" and http.response.code in {401 403})"
  }
}

cf.colo.id is always part of the characteristics, because counters are per data centre. mitigation_timeout must be 0 for a challenge action on plans below Enterprise.

2. One-time codes and password reset: protect the bill

Endpoints that send SMS, WhatsApp or email codes have a direct cost. An attacker who loops a "send code" request can run up a messaging bill, or use your site to spam phone numbers. This is often called SMS pumping or toll fraud.

Limit these endpoints harder than login, because a real person needs only a few codes. Cloudflare's example for one-time codes is 5 failures a minute followed by a 10-minute block4. For the "send code" request itself, count requests rather than failures: three or four sends in 10 minutes from one client is already unusual.

If one rule is all you have, this is often a better use of it than login, because the cost of abuse is easy to measure.

3. API: give clients a 429 they understand

APIs need a different shape of rule. The clients are programs, they can't solve a challenge, and a challenge page in reply to a JSON request looks like an outage to the developer on the other end.

  • Use Block, not a challenge, on API paths, with a custom JSON response and a 429 status. Custom responses are available on Pro and above.
  • Count per API key, not per IP, if you have Advanced Rate Limiting on Enterprise. One partner behind a cloud NAT can otherwise exhaust the limit for every other partner on the same provider.
  • Without Advanced Rate Limiting, count by IP per path, and set the limit from your heaviest legitimate client, with headroom. Look at a week of traffic before you choose the number.
  • Tell your API consumers what the limit is and what a 429 looks like, so they back off rather than retry harder.

Request

GET /v1/orders HTTP/1.1

Anfitrião
api.example.com
Accept
application/json

Response429 Too Many Requests

Content-Type
application/json
{"error": "rate_limited", "message": "Too many requests. Wait a minute and try again."}
An example custom response for an API rate limit: a 429 with a JSON body the client can act on.

4. Checkout and payment: stop card testing

Card testing is when stolen card numbers are tried in small payments to see which ones work. It shows up as many checkout or "add payment method" requests from a small number of clients, mostly declined.

A rate limit on the payment submission route, counted per IP (or per session cookie with Advanced Rate Limiting), slows this down and keeps your payment provider's fraud scoring from turning against you. Two cautions:

  • Exclude the payment provider's callbacks by how they authenticate, such as a signature or a fixed source documented by the provider. A path name or a user agent is not evidence.
  • Verify through payment. After you add the rule, run a real purchase on an approved test account and confirm the order was created. Our post on when Cloudflare blocks checkout during a campaign covers that check in detail.

Shared IP addresses: the mistake that locks out real customers

Counting by IP assumes one IP is one person. Often it isn't:

  • Mobile networks commonly put many subscribers behind a small pool of addresses (carrier-grade NAT). In markets where most customers bank and shop on mobile data, such as much of Africa and the Middle East, a large share of your traffic can arrive from a handful of carrier IPs.
  • Offices, universities and corporate proxies send hundreds of staff through one address. Zero Trust and VPN egress does the same.
  • Your own systems, such as monitoring, load tests or a partner integration, can come from one address too.

Two ways to handle it:

  • Count failures, not attempts (Business and above). Customers behind a shared IP who sign in correctly never add to the counter, so the threshold can stay low for attackers.
  • Use "IP with NAT support" on Business and Enterprise. Cloudflare then counts per visitor, using a cookie it sets, rather than per IP address3. Clients that don't keep cookies, such as most bots and many API clients, share one counter, so this suits browser routes and not APIs.

Whichever you choose, check the Security Events for a new rule during its first few days and look at which IPs and ASNs it acted on. If a mobile carrier's network appears near the top, the threshold is wrong, not the customers.

Roll a rule out without guessing

  1. Pick the route and write down the risk. For example: "credential stuffing on /login, about 3,000 failed sign-ins a day from rotating IPs".

  2. Measure normal traffic. In Security Analytics, filter on the path and look at requests per IP over a busy week. Your threshold sits above the heaviest legitimate client.

  3. Start soft. On Enterprise, use the Log action first. On other plans, start with a managed challenge at a generous threshold, which throttles rather than blocks.

  4. Watch the first days. Review the events the rule acted on, and ask support whether customers reported being challenged.

  5. Tighten and record. Lower the threshold or move to a block in a separate, recorded change, with the reason and a review date. Our WAF change-control runbook has a template.

Check what you already have

Before you add rules, see what the account already does. The Cloudflare Checkup is a free, read-only review of a Cloudflare account. Its full report covers WAF, bot and DDoS settings across every zone. How it works and what it checks is in the Checkup documentation.

How many rate limiting rules do I get on Cloudflare?

Free has 1, Pro 2 and Business 5. Enterprise depends on your contract. Advanced Rate Limiting, an Enterprise add-on, adds counting by headers, cookies, API keys and other fields.

Why is Cloudflare rate limiting my own users?

Usually the rule counts by IP and many users share one address, through a mobile network, an office or a VPN. Count only failed requests, use IP with NAT support on Business and above, or raise the threshold.

Does rate limiting replace bot management?

No. Rate limiting catches volume from one client. Distributed attacks that send a few requests from each of thousands of IPs stay under any per-IP limit, and need bot detection. Our Cloudflare Bot Management page explains the bot products by plan.

Can I test a rate limiting rule before it blocks anyone?

The Log action is Enterprise only. On other plans, start with a managed challenge at a high threshold, which only affects requests over the rate, and review Security Events before you tighten it.

If you would rather not tune these rules yourself, Vigilbase Shield covers a single domain on a monthly plan, with our engineers setting up and tuning the WAF rules for your application. For several domains, APIs that need per-key limits, or 24/7 operations, Vigilbase sells Cloudflare Enterprise, scopes add-ons such as Advanced Rate Limiting with it, and runs the WAF under Managed Cloudflare.

Fontes

  1. Cloudflare, Rate limiting rules: plan availability and accuracy notes.

    ↩
  2. Cloudflare, WAF phases: execution order of custom rules, rate limiting, managed rules and Super Bot Fight Mode.

    ↩
  3. Cloudflare, Rate limiting parameters: characteristics, periods, durations, counting expressions and IP with NAT support.

    ↩
  4. Cloudflare, Rate limiting best practices: login, one-time code and API examples.

    ↩

Partilhar este artigo

Etiquetas

CloudflareLimitação de taxaWAFSegurança da APIPreenchimento de credenciais

Obtenha um Cloudflare Checkup gratuito

Uma classificação de A a F para a sua conta Cloudflare em cerca de 2 minutos. Apenas leitura: inicie sessão com a Cloudflare e o acesso é revogado quando a verificação terminar. A classificação e as conclusões gratuitas não têm custo; o relatório completo é uma atualização opcional.

Executar o Checkup gratuito
Ilyas Esmail

Ilyas Esmail

Founder

Founder @ Vigilbase

Sobre a Vigilbase

A Vigilbase é o sistema operativo de cibersegurança. O Vigilbase OS liga as ferramentas de segurança que uma organização já paga, mantém os seus registos e eventos num único local auditável e põe o agente Vigil a investigar, aplicar correções autorizadas e verificar o resultado. Como Preferred Cloudflare Partner, a Vigilbase também vende o Cloudflare Enterprise e opera-o como Managed Cloudflare. A Vigilbase está em conformidade com a ISO 27001 e o SOC 2 Type 2.

Mantenha-se à frente das ameaças

Receba os mais recentes insights e práticas recomendadas sobre cibersegurança na sua caixa de entrada.