Video in progress
Can an attacker slow a service down by sending keys with the same hashCode (hash flooding)? How is Java protected against it?
Yes: HTTP parameters or JSON keys end up in a HashMap, and since String.hashCode can be computed ahead of time, it's easy to build colliding keys. Since Java 8, a colliding bucket turns into a tree (O(log n)), but that only works fully for Comparable keys. Limiting the input size is the main defense.
📖 Answer
In 2011-2012, many languages (Java, PHP, Python) ran into this attack: a single POST request with 100 thousand parameters, all with the same hash. A HashMap bucket becomes one long linked list, every put is O(n), the total is O(n²), and a single request keeps the CPU busy for minutes.
String.hashCode is deterministic: s[0]*31^(n-1) + ... + s[n-1]. "Aa" and "BB" give the same hash, and by combining them you can build as many colliding strings as you like.
The Java 8 solution (JEP 180): if a single bucket holds more than 8 elements and the table is at least 64 long, the list turns into a red-black tree (treeification). Lookup is O(log n). In the tree, ordering uses the hash first, then compareTo if the keys are Comparable, and otherwise a tie-break based on System.identityHashCode. String is Comparable, so the protection works well for String keys. With your own key type that isn't Comparable, efficiency under collisions is lower.
But this isn't enough:
- even O(n log n) is noticeable for a large n;
- treeification itself is expensive;
- the problem isn't only in
HashMap: JSON parsers, headers and form parameters go through the same path.
Layered defense:
- Limit the input size. This matters most. Tomcat:
maxParameterCount(the default is 10,000; since the 2025 releases only theserver.xmlshipped with Tomcat sets 1000, while Spring Boot's embedded Tomcat stays at 10,000, so lower it to what you need),maxHttpHeaderSize, the request body size. In Jackson 2.15+,StreamReadConstraintssets limits on string length, nesting depth and number length. - Don't put external keys into a
Mapas they are: bind them to known fields (a DTO), not "any JSON object" into aMap<String, Object>. - If you have your own key type, give it a well-distributed
hashCodeand, if possible, make itComparable. - Monitoring: request size and CPU-per-request metrics; anomalous requests get cut off at the WAF/gateway level.
The point at the staff level: algorithmic complexity is also a security boundary. For every user-controlled collection (the number of keys, a regex, recursion depth), the question "what happens in the worst case" should be part of the architecture review.
Sign up to mark studied questions and save your progress.