← Lessons

quiz vs the machine

Gold1430

Security

Regular Expression Denial Of Service Prevention

Why a single regex can hang a server and how to keep matching fast.

5 min read · core · beat Gold to climb

The Risk

Many regex engines use backtracking. For some patterns a crafted input causes the engine to explore an enormous number of paths, so matching time grows explosively with input length. An attacker who can send such input ties up a worker thread and starves the service. This is regular expression denial of service, or ReDoS.

The trigger is usually nested or overlapping repetition, such as a group that can match the same text in many ways followed by a condition that fails at the end.

The Defense

  • Avoid ambiguous repetition. Rewrite patterns so each character has one clear way to match.
  • Prefer a linear time engine that does not backtracking, when your platform offers one.
  • Set a timeout or input length limit on untrusted matching.
  • Replace complex patterns with simple string operations when possible.
  • Test patterns against long pathological inputs as part of review.

Key idea

Write unambiguous patterns and bound matching with timeouts or linear engines so no input can make a regex consume unbounded time.

Check yourself

Answer to earn rating on the learn ladder.

1. What causes ReDoS in many engines?

2. Which mitigation bounds the worst case?