FOUNDING PRICING · 40% OFFfor the first 1,000 members · from ₹95/month
OutageCloudflare11 min read

Cloudflare's 2019 Outage: One Regex and Runaway Backtracking

How a single WAF regular expression exhausted CPU across Cloudflare's network on 2 July 2019, with regex backtracking explained from first principles.

ShareXLinkedInWhatsApp
A row of black server racks filled with rack-mounted servers, their status lights glowing, receding down a data centre aisle.
A row of black server racks filled with rack-mounted servers, their status lights glowing, receding down a data centre aisle. Photo: Victorgrigas, CC BY-SA 3.0, via Wikimedia Commons.

On 2 July 2019, websites behind Cloudflare around the world returned 502 errors for 27 minutes. The cause was not an attack or a hardware fault. It was one regular expression inside a new firewall rule, which made the regex engine do so much repeated work that every CPU core handling web traffic was pinned at 100%. The incident is a compact lesson in two things interviewers care about: how an innocent-looking pattern can take far more time than its input size suggests, and why even small configuration changes need a staged rollout.

Diagram of the outage: a new WAF rule is pushed to every edge location within seconds, the regular expression in it backtracks on each request and pins all CPU cores, and visitors receive 502 errors instead of reaching the origin.

What users saw

Cloudflare sits in front of its customers' websites as a reverse proxy. A visitor's request reaches a Cloudflare edge server first, is inspected, and is then forwarded to the customer's origin server. When the edge servers ran out of CPU they could not process requests, so visitors to sites proxied through Cloudflare saw a 502 Bad Gateway page.

Cloudflare said traffic fell by 82% at the worst point. Customers also could not log in to the Cloudflare dashboard or use its API, because those are served through the same edge. The company noted that it had not had a global outage in six years.

Close view of rack-mounted servers and drive bays in a dark rack, with rows of blue and green status lights.
Rack servers of the general kind that handle web traffic, here at NOIRLab headquarters in Tucson, Arizona. Illustrative; not Cloudflare hardware. Photo: NOIRLab/NSF/AURA/T. Slovinský, CC BY 4.0, via Wikimedia Commons.

Timeline

All times are UTC, as given in Cloudflare's post-mortem. Indian Standard Time is alongside.

Time (UTC)Time (IST)Event
13:3119:01The pull request containing the new rule is merged after approval
13:3719:07The build system builds the rules and runs the tests, which pass
13:4219:12The rule change is deployed, and goes to the whole network
About 13:4519:15The first alert pages engineers, followed by many more: failing tests, 502s, CPU exhaustion
14:0019:30The WAF is identified as the cause and an attack is ruled out
14:0219:32The team proposes a global terminate of the WAF managed rules
14:0719:37The global terminate is executed
14:0919:39Traffic and CPU return to normal
14:5220:22With the faulty rule removed and the fix verified, the WAF is switched back on
Timeline in UTC from the pull request being merged at 13:31, through the build and tests at 13:37, the deployment to the whole network at 13:42, the first alert at about 13:45, the WAF identified as the cause at 14:00, the global terminate proposed at 14:02 and executed at 14:07, traffic and CPU back to normal at 14:09, and the WAF switched back on at 14:52. The 27 minutes from 13:42 to 14:09 are highlighted as the period of 502 errors.
Eleven minutes from merge to global deployment, then 27 minutes of 502 errors.

What the rule was for

A web application firewall, or WAF, inspects the content of HTTP requests and blocks those that look like attacks. Cloudflare maintains a set of managed rules that it updates frequently as new attack techniques appear. In the 60 days before the incident it had handled 476 change requests for these rules, about one every three hours.

The change on 2 July improved detection of cross-site scripting, where an attacker tries to smuggle JavaScript into a page. The new rule was deployed in simulate mode. In that mode a rule runs against real traffic and logs what it would have done, but blocks nothing, so the team can measure false positives. The important detail is that a simulated rule still executes. Its regular expression is still evaluated on every request, so it still costs CPU.

Backtracking from first principles

The rule's regular expression was long, but Cloudflare identified the damaging part as the fragment .*(?:.*=.*). Ignoring the non-capturing group, which does not change matching here, that is:

.*.*=.*

Read it piece by piece. . matches any single character. * means zero or more of the previous thing. So the pattern says: any run of characters, then another run of characters, then an equals sign, then any run of characters.

How a backtracking engine works

Many regex engines, including the PCRE library Cloudflare's WAF used at the time, match by trial and error. The engine walks through the pattern from left to right. Whenever it has a choice, it picks one option, remembers the others, and carries on. If the rest of the pattern later fails, it goes back to the most recent choice and tries the next option. That going back is backtracking.

.* is greedy: it first grabs as many characters as it can, and gives them back one at a time only if it must.

A small example

Take the input xxxx, four characters and no equals sign, and try .*.*=.* from the start of the string.

  1. The first .* grabs all four characters. The second .* has nothing left and matches the empty string. The engine now needs =, but it is at the end of the input. Fail.
  2. Backtrack. The first .* gives back one character and holds xxx. The second .* grabs the remaining x. Need =: fail. The second .* gives back its character and holds nothing. Need =, but the next character is x: fail.
  3. Backtrack again. The first .* holds xx. The second .* tries holding xx, then x, then nothing. Each attempt fails at =.
  4. This continues until the first .* holds nothing at all and the second has tried every length from four down to zero.

The engine cannot know that there is no = anywhere. It has to try every way of dividing the text between the two stars before it can give up. The number of ways is easy to count. If the first star takes k characters, the second can take anything from 0 to n − k, where n is the input length. Adding those up gives (n + 1)(n + 2) / 2 combinations.

Input length nWays to split between the two .*
521
1066
20231
40861
1,000501,501

Doubling the input roughly quadruples the work. And this counts only attempts anchored at the first character. An engine searching for a match anywhere in the string repeats the process from each later starting position too, and every extra .* in the pattern multiplies the combinations again.

Cloudflare measured this with a regex debugger and published the numbers. Matching .*.*=.* against x=x took 23 steps. Against x= followed by 20 x characters it took 555 steps. When the input was 20 x characters with no = at all, the engine needed 4,067 steps just to conclude that there was no match. With a semicolon added to the end of the pattern, so that x= followed by 20 x characters no longer matched, the count rose to 5,353 steps.

Those are tiny inputs. Real HTTP requests carry bodies and query strings thousands of characters long, and the WAF was running the pattern on live traffic at every edge location.

Why this is avoidable

Backtracking is a property of the engine, not of regular expressions. An alternative family of engines simulates all possible positions in the pattern at once, moving through the input one character at a time and never going back. Their running time grows linearly with the input length. The idea dates back to a 1968 paper by Ken Thompson, as Cloudflare's post points out. RE2 and Rust's regex library work this way. The price is that they give up a few features, such as backreferences, that cannot be matched in linear time.

Why the safeguards did not catch it

Cloudflare listed the contributing factors itself. Several independent protections each had a gap.

  • The CPU guard had been removed. The WAF once had a protection that stopped a regular expression from using too much CPU. It was removed by mistake during a refactoring a few weeks earlier, a refactoring whose purpose was to make the WAF use less CPU.
  • The engine offered no guarantee. PCRE backtracks and puts no bound on how long a match may take.
  • The tests checked correctness, not cost. The test suite verified that rules blocked what they should and passed what they should. It had no way to detect a rule that consumed excessive CPU.
  • WAF rules skipped the staged rollout. Cloudflare's software goes out in stages: first to a location used only by employees, then to one carrying a small share of customer traffic, then to canary locations, and only then to everything. WAF rule updates were exempt so that new threats could be blocked quickly. They were distributed through Quicksilver, Cloudflare's key-value store, which pushes changes to the whole network in seconds. This change was not an emergency, but it took the fast path anyway.
  • Rollback was too slow. The planned way to undo the change needed the full WAF build to run twice.
  • The tools were behind the broken system. Engineers had trouble reaching internal systems because those were protected by Cloudflare's own products, which were down. Some had also lost access because credentials that had not been used recently were disabled as a security measure.
Two rows comparing release paths. The top row shows the staged rollout used for other Cloudflare software: an employee-only location, then a location with a small share of customer traffic, then canary locations, then the whole network. The bottom row shows the WAF rule on 2 July 2019: pull request merged at 13:31, tests that check only correctness pass at 13:37, a Quicksilver push with no stages at 13:42, and the whole network running the rule seconds later.
The staged path that would have limited the damage, and the fast path the rule actually took.

In the end the team used a global terminate, a kill switch that disables one component across the whole network. Turning off the WAF managed rules brought CPU back to normal within two minutes.

What Cloudflare changed

The post-mortem listed concrete actions, with their status at the time of writing:

  • The protection against excessive CPU use by a rule was put back.
  • All 3,868 managed WAF rules were inspected by hand for other patterns that could backtrack excessively.
  • Performance profiling of every rule was being added to the test suite.
  • The WAF was to move to a regex engine with run-time guarantees, either RE2 or Rust's.
  • The procedure for rule changes was altered to use the same staged rollout as other software, while keeping an emergency path for active attacks.
  • Plans were made for a way to take the dashboard and API off the Cloudflare edge in an emergency, and for automatic status page updates.

The computer science underneath

Layer 7 inspection costs CPU per request. A device that forwards packets by IP address and port does a small, fixed amount of work for each one. A WAF works at the application layer: it must reassemble the HTTP request and run pattern matching over its contents. That is far more work, and how much depends on the content and on the rules. The lessons on layer 4 versus layer 7 load balancers and on firewalls explain what each layer can see and what that visibility costs.

Algorithmic complexity is an operational concern. The same pattern can be matched in time proportional to n by one algorithm and proportional to n squared, or worse, by another. On test inputs of ten characters the difference is invisible. On production inputs it is the difference between a healthy server and a dead one.

A CPU-bound task with no preemption point starves everything else. When every worker is stuck inside a long regex match, there is no core left to serve other requests. The operating system can share cores fairly between processes, but it cannot make a busy worker finish sooner. This is why per-task CPU budgets and timeouts matter, and it is the same reasoning behind time slices in CPU scheduling.

Configuration is code. A rule update is as capable of breaking production as a binary release. Staged rollouts limit the blast radius by exposing a change to a small slice of traffic first and watching the metrics. See rolling, blue-green and canary deployments.

What an interviewer could ask from this

1. What is catastrophic backtracking? It is when a backtracking regex engine has to try a very large number of ways to divide the input among the quantifiers in a pattern before it can report a match or a failure. The work grows polynomially or exponentially with the input length.

2. Why is .*.*=.* slow on a string with no equals sign? Each .* can match any length, so the engine tries every way of splitting the text between them, about n squared over two combinations, before it can conclude there is no match.

3. How do you guarantee linear-time matching? Use an engine based on automata, such as RE2, which tracks all possible states at once and never rereads input. You lose backreferences and some lookaround features.

4. The rule was in simulate mode. Why did it still cause an outage? Simulate mode skips the blocking action, not the evaluation. The expensive part, running the regex, happened on every request.

5. How would you roll out a rule change safely? Test it for CPU cost as well as correctness, deploy to a small canary first, watch CPU and error rates, then widen in stages. Keep a fast, well-practised kill switch.

Takeaways

  • A regular expression is a program. Its worst-case running time depends on the engine, and backtracking engines have no upper bound that is safe for untrusted input.
  • Test performance, not just correctness, and test with inputs that fail to match as well as inputs that succeed.
  • Every change that reaches production deserves a staged rollout, including rules and configuration.
  • Defence in depth only works if each layer is verified. Here a CPU guard, a test suite and a rollout process all had gaps that lined up.
  • Keep a kill switch, and make sure you can reach it when your own product is down.

Sources

  1. Details of the Cloudflare outage on July 2, 2019 (Cloudflare Blog)
  2. Cloudflare outage caused by bad software deploy (Cloudflare Blog)

Written by the Codevizag Academy team

An independent explainer built from the public sources listed above. Codevizag Academy is not affiliated with Cloudflare. Found a mistake? Write to support@codevizag.com.

More case studies

Understood it? Now prove it.

The lessons behind this case study are free, and 20 problems a month are judged on real test cases at no cost.

Start solving free