Video in progress

What is a "hash flooding" attack on HashMap, and how do you defend against it in Java?

The attacker sends thousands of keys that land in the same bucket (for example request parameters or JSON fields), and every insertion turns into a linear scan, tying up the CPU. Treeification in Java 8 brings this down to O(log n), but you still have to limit the input size.

📖 Answer

In 2011–2012 this was used against many platforms: String.hashCode() is deterministic, so it is easy to precompute colliding strings ("Aa" and "BB" give the same hash, and you can build combinations from them). With 100,000 such parameters in a single POST request, the server is busy for several seconds with one request.

What Java did:

  • 7u6 added alternative hashing for String, and it was removed in Java 8;
  • since Java 8, a bucket with heavy collisions turns into a red-black tree. Because String is Comparable, the worst case is O(log n), not O(n).

But that is not enough. If the key is not Comparable, the tree doesn't help much. Besides, other structures like Set.of/Map.of, and libraries, have their own behavior.

In practice I put protection at the edge of the system:

  • limits on request body size and parameter count (maxParameterCount in Tomcat, server.tomcat.max-parameter-count in Spring Boot; document size and depth with StreamReadConstraints in Jackson);
  • a size limit on Maps that get filled with keys supplied by external users;
  • watching request time p99 and CPU in metrics, and taking a profile if a single endpoint slows down sharply.

Think about this when you write your own hashCode() too: computing it as a plain sum over a user-controlled field opens the door to an attack.