skip to content

As a Rust lead, what rule do you set for when code may replace HashMap's default SipHash hasher with a faster one?

level: principalimportance: should knowfreq 30%

answer

  1. who chooses the keys
  2. measure before swapping
  3. make the choice visible in types
  4. clippy can ban a type

basics

~20 s

Keep RandomState wherever an outsider can choose or influence keys, such as words from uploaded documents; allow a fast hasher only for internal keys, after a profile shows hashing matters, behind named types that clippy's disallowed_types enforces.

solid answer

~40 s

The default `RandomState` hashes with randomly keyed SipHash 1-3, which std says is chosen for HashDoS resistance and admits is slower than alternatives for integers and long strings. So the rule turns on key provenance: anything a client, upload, file or peer can influence (uploaded words, cookie tokens, header values) keeps the default, while engine ids or interned symbols may use a fast hasher such as `rustc-hash`'s `FxHashMap`, but only with a measurement showing hashing matters. Make the choice visible through a named alias, enforce it with clippy's `disallowed_types` and `#[expect(..., reason = ...)]` at approved sites, and revisit whenever a map starts taking input. Two things are out of bounds whatever the hasher: persisting hashes, since std does not keep `DefaultHasher` stable across releases, and depending on iteration order.

code

toml · 5 lines
toml
# clippy.toml at the crate or workspace root
disallowed-types = [
    { path = "rustc_hash::FxHashMap", reason = "unkeyed hasher: only for keys no client controls" },
    { path = "rustc_hash::FxBuildHasher", reason = "unkeyed hasher: only for keys no client controls" },
]

go deeper

for a junior

Know that HashMap's default hasher is chosen to resist crafted-key attacks and that teams sometimes swap it for speed.

for a middle

Explain why key provenance decides the hasher: SipHash with secret keys resists flooding, while unkeyed fast hashes can be attacked offline.

for a senior

Classify a map's keys correctly, including indirect exposure through headers, tokens and peer messages, and back any swap with a real measurement.

for a principal

Own the written rule and its enforcement: default to RandomState, allow named fast hashers only for internal keys, enforce with clippy, and re-open the decision when a map starts taking input.

## What the default buys std's `HashMap` and `HashSet` hash with **SipHash 1-3**, keyed by a `RandomState` whose keys come from the operating system's random source. std's documentation states the purpose directly: the default algorithm is "selected to provide resistance against HashDoS attacks". A **HashDoS** (hash-flooding) attack feeds a map many keys that land in the same place, so each insert and lookup slows from near-constant to proportional to the number of colliding keys. With a secret, per-process key, an attacker cannot predict which inputs collide. The general theory of flooding and its defences belongs to the material on adversarial hash-table guarantees; the decision here is what a Rust codebase allows. std is equally direct about the cost. SipHash is competitive for medium-sized keys, but faster algorithms outperform it on small keys such as integers and on long strings, and those algorithms "will typically *not* protect against attacks such as HashDoS". The docs add two caveats a policy should respect: the algorithm is "subject to change at any point in the future", and the seed is only as good as the system's random source when it was drawn, with seeds made while entropy is abnormally low (for example, during system boot) possibly of lower quality. ## The decision Swapping the hasher is a per-map type change (`HashMap<K, V, S>`), so without a rule each engineer makes the trade-off alone and usually by benchmark alone. The question a lead answers is: **who may choose the keys?** A word-frequency counter over uploaded documents, a per-client rate limiter keyed by a header, a cache keyed by request paths: an outsider picks every key. Entity ids from an allocator, interned symbol indices, enum-derived keys: nobody outside picks them. ## A workable rule 1. **Default to `RandomState`.** Plain `HashMap::new()` stays the norm, and no justification is needed to keep it. 2. **Allow a fast hasher only for internal keys,** meaning keys that no client, file, peer or upload can choose or influence, including indirectly through a field that ends up in the key. 3. **Require a measurement.** A profile or benchmark showing that hashing matters on the real path, not a micro-benchmark of the hash alone. 4. **Make it visible in the type.** Use a named alias (such as `rustc-hash`'s `FxHashMap`, or the team's own) so a reviewer sees the choice at the definition. 5. **Enforce it mechanically.** List the fast types in `clippy.toml` under `disallowed-types` with a reason, and allow them only at approved sites with `#[expect(clippy::disallowed_types, reason = "...")]` (`#[expect]` has been stable since Rust 1.81). How workspace lint configuration is wired is covered with Cargo's lint settings. 6. **Revisit when provenance changes.** A map that was internal becomes exposed when a feature starts filling it from input; that change re-opens the decision. ## The grey areas | Map keyed by | Who controls the keys | Hasher | |---|---|---| | words from uploaded documents | the uploader | `RandomState` | | session tokens from cookies | the client, who can send anything | `RandomState` | | engine-allocated entity ids | the program | fast hasher allowed | | interned symbol indices | the program | fast hasher allowed | | ids from a peer node's messages | the peer | `RandomState` unless the peer is trusted | Random-looking legitimate values do not make a key internal: an attacker sends whatever bytes they like, not the values your system would mint. A **randomly seeded** fast hasher raises the bar, but a seed does not turn a fast function into a keyed pseudorandom function the way SipHash's design does; accept such a hasher for exposed keys only on the strength of its own documented analysis. ## What stays out of the rule, and other levers - **Never persist hashes.** `DefaultHasher`'s algorithm is unspecified and its hashes "should not be relied upon over releases", so a hash stored as an id breaks on a toolchain upgrade. - **Never depend on iteration order,** whatever the hasher. - **Bound the input as well.** Size limits on uploads and on key counts cap the damage from any attack, and a `BTreeMap` has an O(log n) worst case with no hashing at all, at the cost of ordered-key overhead (covered with ordered maps).

  • Is a randomly seeded fast hasher as safe as SipHash for keys from the network?
    Not automatically. A seed hides the hash only if the function behaves like a keyed pseudorandom function, which is what SipHash was designed to be; for some fast non-cryptographic hashes, collisions have been found that hold whatever the seed. Accept a seeded fast hasher for exposed keys only on the strength of that crate's documented security analysis, and otherwise keep `RandomState` there.
  • How do you stop the rule from eroding in a large Rust workspace?
    Put the fast types in `disallowed-types` in `clippy.toml`, run clippy in CI with warnings denied, and require `#[expect(clippy::disallowed_types, reason = "...")]` at each approved site. `#[expect]`, stable since Rust 1.81, also warns when the lint no longer fires, so stale exemptions surface on their own.
  • Why ban storing `DefaultHasher` output even in maps that keep the default hasher?
    std documents `DefaultHasher`'s algorithm as unspecified, with hashes that should not be relied upon across releases, and `RandomState` re-keys every process anyway. A hash written to a database, a cache key or a file name can silently change meaning after a toolchain upgrade or a restart. Persistent ids need a hash function the team pins and controls.

  • Hash maps are internal, so attackers cannot affect their performance
  • Cookie or header keys are safe to fast-hash because valid values look random
  • Switch the whole codebase to a fast hasher once a benchmark shows a gain
  • DefaultHasher output can be stored in a database as a stable id
  • Randomly seeding any fast hasher makes it as HashDoS-resistant as SipHash

Assumes Rust 1.99; the #[expect(..., reason = ...)] exemption the rule relies on has been stable since Rust 1.81.