Course contentsShow
← Security
Lesson 1180 of 3,05224. Application Security - Input ValidationFree lesson

Regex Timeout and Resource Limits

Implementing timeout mechanisms and execution limits to prevent regex operations from consuming excessive CPU.

Regex Timeout and Resource Limits

What you'll learn: How to prevent regular expressions from hijacking your server's CPU by setting strict execution timeouts and resource caps.


Why Timeouts Matter

You've learned that evil regex patterns can cause catastrophic backtracking, consuming massive CPU time. Without safeguards, a single malicious input can freeze your application for seconds—or minutes—while the regex engine churns away. That's a perfect DoS attack vector.

The solution? Set a hard limit on how long any regex operation can run.

How Timeouts Work

Think of a regex timeout like a kitchen timer: you start the regex engine, but if it's still running when the timer dings, you forcibly stop it and reject the input. This prevents runaway computations from monopolizing your server's resources.

Most modern regex engines support timeout parameters:

  • Timeout duration: Typically measured in milliseconds (e.g., 100ms or 1000ms)
  • Behavior on timeout: The regex operation throws an error or returns failure
  • Granularity: Some engines check the timeout between backtracking steps, not continuously

Implementation Strategy

Set timeouts at the point where you compile or execute regex patterns. Choose conservative limits: if legitimate inputs finish in 10ms, set a 100ms timeout as a safety margin.

Also consider resource limits beyond time:

  • Maximum input length checks (reject strings over N characters)
  • Regex complexity scoring (reject patterns with nested quantifiers)
  • Process-level CPU quotas in sandboxed environments

Defense in Depth

Timeouts don't replace safe regex construction—they're your last line of defense. Combine them with patterns you've already learned: avoid nested quantifiers, use atomic groups where possible, and validate regex complexity before deployment.

Key Takeaway: Always enforce regex execution timeouts and input length limits to prevent ReDoS attacks from consuming excessive CPU, even when using carefully constructed patterns.