skip to content

With a Cloudflare rate limiting rule on a login endpoint, how does a custom counting expression count only failed logins, and what must it repeat?

level: middleimportance: must knowfreq 55%

answer

  1. two expressions, two jobs
  2. response fields count after the response
  3. status 401 or 403 only
  4. it replaces the match, not narrows it

basics

~20 s

Set Increment counter when to an expression that tests the response, such as http.response.code in {401 403}, so only failed logins add to the counter. It replaces rather than extends the matching expression, so repeat the login path and method in it.

solid answer

~40 s

A Cloudflare rate limiting rule has a matching expression, which decides which requests the action falls on, and an optional **counting expression** (`counting_expression`, the dashboard's **Increment counter when**), which decides which requests add to the counter. The counting expression may read response fields such as `http.response.code`, so counting happens after the origin answers: `... and http.response.code in {401 403}` counts only failed logins, and a person who logs in successfully never moves the counter. It does not inherit the matching expression, so it must repeat `http.request.uri.path eq "/api/login"` and the method; otherwise every 401 on the zone counts. Custom counting expressions start at the Business plan. An endpoint that always answers `200`, such as a password reset that hides whether an account exists, needs request-based counting with a lower threshold instead.

code

json · 22 lines
json
{
  "description": "Failed logins per IP",
  "expression": "http.request.uri.path eq \"/api/login\" and http.request.method eq \"POST\"",
  "action": "block",
  "action_parameters": {
    "response": {
      "status_code": 429,
      "content_type": "application/json",
      "content": "{\"error\":\"too_many_failed_logins\"}"
    }
  },
  "ratelimit": {
    "characteristics": [
      "cf.colo.id",
      "ip.src"
    ],
    "period": 60,
    "requests_per_period": 5,
    "mitigation_timeout": 600,
    "counting_expression": "http.request.uri.path eq \"/api/login\" and http.request.method eq \"POST\" and http.response.code in {401 403}"
  }
}

go deeper

for a junior

Remember that a rule can count only failed logins by testing the response status, and that this needs a Business plan or higher.

for a middle

Explain the split between the matching expression, which picks where the action lands, and the counting expression, which picks what increments, and why the second must repeat the path.

for a senior

Diagnose rules that never fire, such as an Origin Rule host rewrite or a response-blind endpoint, and design escalating rules whose action scope is wider than what they count.

for a principal

Decide which login and reset flows can expose failure to the edge, and agree with the application team on the status codes or headers the rules depend on.

## Why count only failures A login endpoint sees two kinds of traffic that look the same on the wire: people typing their passwords, and a credential-stuffing tool trying leaked username and password pairs. If a Cloudflare rate limiting rule counts **every** `POST` to the login path, a household or office of legitimate users that logs in a lot can reach the threshold just as a tool does. What separates the two is the **outcome**: the tool fails almost every time. A **custom counting expression** lets the rule count only the failures. ## Two expressions in one rule A rate limiting rule can carry two expressions with different jobs: - **When incoming requests match** (`expression`), also called the mitigation expression, decides which requests the rule watches and which ones the action falls on once a counter is over its threshold. - **Increment counter when** (`counting_expression`), shown in the dashboard after you turn on **Use custom counting expression**, decides which requests add to the counter. The counting expression may use **HTTP response fields**, such as `http.response.code` and response headers. When it does, Cloudflare counts the request after the response has been sent, because only then is the status known. The matching expression cannot contain response fields, since the decision to act has to be made before the request goes on. Custom counting expressions, and the response fields in them, are available from the **Business** plan up. Free and Pro rules count every request their matching expression matches. ## The trap: the counting expression does not inherit the match If the counting expression is set, it **replaces** the matching expression for counting; it does not narrow it. A counting expression of just `http.response.code in {401 403}` counts every 401 and 403 on the whole zone, from any path, against the client's counter, and the login rule then fires on users who never touched the login form. Repeat the scope: ```plaintext When incoming requests match: http.request.uri.path eq "/api/login" and http.request.method eq "POST" Increment counter when: http.request.uri.path eq "/api/login" and http.request.method eq "POST" and http.response.code in {401 403} ``` An empty counting expression (`""` in the API) means the default: count what the matching expression matches. ## Escalating rules Cloudflare's own credential-stuffing recipe stacks rules over the same path with growing penalties: 1. A short window and a gentle action, for example four failures per minute, gives a person who mistypes a password a few tries. 2. A longer window, for example ten failures in ten minutes, catches a client that keeps failing after the first step. 3. A long window with a strong action, for example twenty failures in an hour, blocked for a day. Its matching expression can be wider than its counting expression, such as the whole host, so a client that keeps failing logins is shut out of everything, not just the login path. The first two steps in that recipe use Managed Challenge, which needs a browser to render the challenge page. A native app's JSON API cannot render a challenge page, so a rule protecting one should use Block with a JSON custom response instead. ## Endpoints that cannot report failure Some endpoints answer the same way whatever happens. A **password-reset** endpoint that does not reveal whether an account exists returns `200` for every address, and a one-time-code check may return `200` with the verdict in the body. A counting expression keyed on the status code has nothing to see there. For those, count every request with a lower threshold, or let the origin mark failures in a response header and count on that header. ## Traps when the counter never moves - An **Origin Rule** that rewrites the `Host` header changes `http.host` before counting happens. A counting expression that tests the original hostname then never matches, and the rule never fires; scope the counter by path instead, or test both hostnames. - **Workers subrequests** to the same zone can be counted as separate requests when cached assets are excluded, so the rule fires sooner than expected; exclude them with `cf.worker.upstream_zone`. - A counting expression with response fields cannot also use a **custom list**, and a rule whose matching expression uses a list must keep **Also apply rate limiting to cached assets** turned on.

  • Once the counter is over its threshold, which requests does the action fall on: those the counting expression matches or those the matching expression matches?
    Those the matching expression matches. The counting expression only decides what adds to the counter. That split is useful: a rule can count failed login POSTs but use a matching expression covering the whole host, so a client that keeps failing is blocked everywhere, not only on the login path.
  • Why might a login rate limit with a counting expression never fire after a team adds an Origin Rule that rewrites the Host header?
    Counting happens in the response phase, after the Origin Rule has changed the host. A counting expression that tests `http.host` against the original hostname no longer matches, so requests match the rule but never increment its counter. Scope the counter by path, test the rewritten hostname, or test both with `or`.

  • A counting expression narrows the matching expression, so it only needs the status code.
  • Response fields can go in the matching expression as well as the counting one.
  • Counting expressions with response fields are available on every plan, Free included.
  • With a counting expression, the action falls only on requests the counting expression matches.
  • A password-reset endpoint that always returns 200 can be limited by counting 401s.

Assumes Cloudflare as of 2026-10-10, where a custom counting expression with response fields is available from the Business plan up.