flashman
← All posts

Regex catastrophic backtracking in production

Find catastrophic regex backtracking by testing adversarial input, timing failures, simplifying quantifiers, and bounding data before CPU spikes become outages.

2026-08-26 · 7 min read · Rahul Chitturi

  • regex
  • performance
  • security

A regular expression can match normal samples instantly and consume seconds of CPU on one carefully shaped non-match. Nested quantifiers and ambiguous alternatives make some backtracking engines explore an enormous number of paths before giving up.

This failure mode, often called ReDoS, appears in validators, log pipelines, routing rules, and redaction code. Because the input is usually small, infrastructure graphs may look like an unexplained CPU spike rather than a data-volume problem.

Test the failing shape

Start from the shortest sanitized input that reproduces the delay. Increase its repeated section gradually and record elapsed time. Exponential growth is a stronger signal than one slow benchmark.

  • Look for nested forms such as (a+)+ or overlapping alternatives
  • Test near-matches that fail at the final character
  • Check engine-specific support for atomic groups or possessive quantifiers
  • Set realistic input-length and execution limits at the caller

Simplify before optimizing syntax

Replace ambiguous repetition with a more specific character class or split validation into several clear checks. Anchors can help when the whole input must match, but they do not make an ambiguous core safe by themselves.

If the pattern handles untrusted data, consider a linear-time regex engine or a parser with explicit bounds. A passing browser test does not prove that another runtime uses the same engine or behavior.

A Flashman workflow

Use the regex tester with synthetic, non-sensitive samples, the timestamp converter to align slow requests with logs, the diff tool to review pattern revisions, and the JSON formatter for structured log evidence.

Keep adversarial fixtures in tests and document the input cap. Performance behavior is part of the validation contract, not an optional benchmark.

Try these tools