Video in progress

What is hash flooding (an algorithmic complexity attack)? How do you protect your Java services against such attacks?

An attacker deliberately sends keys that land on the same hash, turning an O(1) table into O(n) and an entire request into O(n²). Since Java 8, HashMap converts a colliding bucket into a tree, cutting the damage down to O(log n), but full protection means limits on input size, parser settings, and closing other explosive spots like regexes and recursion.

📖 Answer

The classic example is the 2011 attack: in many languages, POST parameters were put into a hash table, and String.hashCode() is predictable in advance. "Aa" and "BB" give the same hash, and from them it's easy to combine millions of keys with identical hashes. A single 2 MB request could keep the CPU busy for minutes.

What changed in Java:

  • Since Java 8, when a single bucket has more than 8 elements (and the table has at least 64 slots), HashMap turns it into a red-black tree. If the keys are Comparable (String is), lookup is O(log n). The attack is no longer "quadratic", but it still slows things down;
  • on your own key classes that aren't Comparable, this protection is weaker.

But the problem isn't only HashMap. Other attacks in the same family:

Where Attack Defense
JSON parser a 100,000-level nested array → StackOverflowError Jackson 2.15+ StreamReadConstraints: depth, string length, number length
Regex "aaaa…b" against (a+)+$ → exponential backtracking (ReDoS) don't accept user regexes, possessive/atomic groups, a time limit
XML "billion laughs" entity expansion disable DTDs, secure processing
Zip a small archive → expands to 100 GB limits on expanded size and file count
Sorting specially ordered input makes a naive quicksort O(n²) Java's Arrays.sort for primitives is a dual-pivot quicksort; since JDK 14 it falls back to heap sort if the recursion gets too deep

My organizational approach: for every place that accepts external input, a "budget": maximum bytes, maximum elements, maximum depth, maximum CPU time. Body size at the gateway level, parser limits in the application, timeouts at the request level. If one layer lets something through, the next one catches it.

For verification, fuzzing (Jazzer) and property-based tests are good: they find exactly the pathological inputs that hand-written unit tests don't.