Quick revision
The short answer
Key types should be immutable records or final classes with final fields whose equals() and hashCode() cover exactly the identity fields, and entities or mutable DTOs should never be keys. Adding a field to equals() and hashCode() changes key identity, so after the deploy old cache entries stop matching, hit rates drop and mixed versions disagree, which is why a change to key equality must be treated as a breaking change with release notes and a cache flush or key prefix bump. For Redis and other distributed caches, the library should define an explicit, versioned string or byte format for each key instead of relying on Java serialization, toString() or hashCode(), and contract tests such as EqualsVerifier belong in the library build.
What to remember
In this answer, we designed an equality contract for shared key types. In-process keys for HashMap and Caffeine should be immutable records or final classes with normalised, immutable components, and entities and mutable DTOs should stay out of keys. Distributed keys need an explicit, versioned format owned by the library, not Java serialization, toString() or hashCode(). Adding a field to equality changes key identity, so old entries stop matching and hit rates drop, which is why such a change is a breaking change with release notes and a key prefix bump or flush, enforced by EqualsVerifier and format snapshot tests in the library build.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Key types should be immutable records or final classes with final fields whose equals() and hashCode() cover exactly the identity fields, and entities or mutable DTOs should never be keys. Adding a field to equals() and hashCode() changes key identity, so after the deploy old cache entries stop matching, hit rates drop and mixed versions disagree, which is why a change to key equality must be treated as a breaking change with release notes and a cache flush or key prefix bump. For Redis and other distributed caches, the library should define an explicit, versioned string or byte format for each key instead of relying on Java serialization, toString() or hashCode(), and contract tests such as EqualsVerifier belong in the library build.
Why this question is asked
A key class looks like the most boring code in a domain library, yet it is shared by twenty services and three kinds of map, and its equality decides whether caches hit or miss across all of them. When someone adds a field to a key in version 2.4, the change is one line, compiles everywhere, and can halve the hit rate of a Redis cache during a rolling deploy. Interviewers ask this design question to see whether we think about contracts across process boundaries and across versions, not just within one JVM. In this answer, we will recap what equality means for a key in each kind of cache, design the in-process contract, design the distributed key format, work through what happens when a field is added, and finish with the tests and release rules that keep it safe.
1A Quick Recap: Three Places a Key Lives
In a HashMap or a Caffeine cache, which is an in-process cache, a key is a live Java object. Lookups use its hashCode() to find a bucket and equals() to confirm the match. Those caches live inside one JVM and are empty after a restart, so a key only has to agree with itself within one process and one version of the code.
In Redis, the key is not a Java object at all. It is a string or byte array that our code produces from the object, and it outlives every JVM that wrote it. Different services, running different library versions, read and write the same keys. So for distributed keys the contract is the serialised form, and it has to stay stable across processes, deployments and versions.
2The In-Process Contract: Immutable Value Types
For HashMap and Caffeine keys, the rules are those of a good value type. The class is a record or a final class with final fields, so its hash cannot change while it is in a map. equals() and hashCode() use exactly the fields that define identity and no others. Components are themselves immutable values; a List field should be copied with List.copyOf in the constructor, and arrays should be avoided, because a record compares array components by reference.
Notice the normalisation in the compact constructor. Decisions such as case or trailing spaces belong in the key type, not in twenty callers. Watch for values whose equals() surprises people: BigDecimal treats 1.0 and 1.00 as unequal, so a price-band key should store a normalised scale or a long of minor units. Entities and mutable DTOs never become keys, because their state, and sometimes their id, changes while they are in a map.
3The Distributed Contract: An Explicit, Versioned Format
For Redis keys, the library should own the conversion from key object to key string, and that conversion should be written out field by field, with a namespace and a version.
| Key form | Stable across JVMs? | Stable across versions? |
|---|---|---|
hashCode() of the object | no (enum and identity hashes vary) | no |
| Java serialization bytes | mostly | no: tied to class layout |
toString() | yes | no: unspecified, changes with fields |
Explicit cacheKey() with version | yes | yes, until we bump v1 to v2 |
The alternatives each fail in a different way. Java serialization ties the bytes to class structure and serialVersionUID and is a security risk to deserialise. toString() of a record has an unspecified format that the JDK is free to change and that changes whenever a component is added. hashCode() is not stable across JVMs for every type; Enum.hashCode(), for example, is an identity hash that differs on every run, so a record with an enum component hashes differently in each process. An explicit format avoids all three, and fields that can contain the separator must be escaped or encoded.
4What Happens When a Field Is Added
Suppose version 2.4 adds a channel field to PriceKey, because web and mobile prices start to differ. In-process, after each service restarts on 2.4 its Caffeine cache starts empty and fills with new keys, so the cost is just a cold start, and maps never mix versions within one JVM. But two keys that used to be equal are now different, so if any code built keys without the channel, it now misses.
In Redis it is worse. During a rolling deploy, half the instances write price:v1:t1:AB-1:EUR and half would write a key with the channel. Old entries no longer match new lookups, so the hit rate drops and load on the price service jumps. Worse, if the new version kept the same format name but changed what the key means, old instances could read a value computed for a different channel and serve wrong data. That is why the format version must change with the identity.
- Change touches equals, hashCode or cacheKey()?YesBreaking change: major or flagged releaseNoNormal release
- Bump the format prefixprice:v1 -> price:v2
- Release notes and service owner sign-offexpected hit-rate dip, warm-up plan
- Old keys expire by TTL or are flushedno reader mixes v1 and v2 meanings
4 steps in order. Play them, or step through them one at a time.
5Release Rules and Contract Tests
So the library's rule is that any change to the fields in equals(), hashCode() or cacheKey() is a breaking change. It goes in the release notes with the expected effect, ships with a bumped format prefix so old and new keys never collide, and the old keys either expire through their time-to-live or are flushed deliberately. Teams planning a deploy then know to expect a warm-up and can schedule it.
Tests in the library build enforce the rest. EqualsVerifier checks that equals() and hashCode() are symmetric, transitive, consistent with each other, null-safe and use the same fields. Snapshot tests pin the exact cacheKey() output for representative keys, so an accidental change to the format fails the build instead of a production cache.
6Follow-up questions
Should the distributed key include a hash instead of the raw fields?
Only for long or sensitive keys, and then with a stable, specified hash such as SHA-256 over the explicit format string, never Java's hashCode(). Raw fields are easier to debug and to delete by pattern, so we use them when they are short and contain nothing private.
How do we handle a key used by services that cannot upgrade at once?
We keep the old format working until the last consumer upgrades. The library can offer both cacheKeyV1() and cacheKeyV2(), new writers write v2, and readers try v2 and fall back to v1 for a transition period. Once all services are on the new version, v1 is removed and its keys expire.
Are records always safe as keys?
They are immutable at the top level, but their components may not be. A record holding a List or an array can still change through that component, and arrays use reference equality. Copy collections in the compact constructor and avoid array components in key types.
7Conclusion
In this answer, we designed an equality contract for shared key types. In-process keys for HashMap and Caffeine should be immutable records or final classes with normalised, immutable components, and entities and mutable DTOs should stay out of keys. Distributed keys need an explicit, versioned format owned by the library, not Java serialization, toString() or hashCode(). Adding a field to equality changes key identity, so old entries stop matching and hit rates drop, which is why such a change is a breaking change with release notes and a key prefix bump or flush, enforced by EqualsVerifier and format snapshot tests in the library build.
Open with
I would separate the in-process contract from the distributed one. For HashMap and Caffeine keys, the types are records or final classes with final, immutable components, equals and hashCode cover exactly the identity fields, and the compact constructor normalises values such as case so every service builds the same key.
Then, if they want more
Entities and mutable DTOs are never keys, and I avoid array components and values like BigDecimal whose equality surprises people. For Redis, the key is a string that outlives every JVM, so the library defines an explicit format per key type, with a namespace and a version, like price:v1:tenant:sku:currency, built field by field.
I would not use Java serialization, record toString, whose format is unspecified, or hashCode, which is not stable across JVMs for enums. Then the evolution rule: adding a field to equality changes key identity.
In-process caches just start cold after the deploy, but in Redis old entries stop matching, so the hit rate drops during a rolling deploy, and if the meaning changed without a new prefix, old instances could even read wrong data.
So any change to equals, hashCode or the key format is a breaking change: it goes in the release notes, it bumps the prefix to v2, and old keys expire or are flushed, with a fallback read path if services upgrade at different times.
In the library build I would run EqualsVerifier on every key type and snapshot tests that pin the exact key strings.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "You own a shared domain library whose value types are used as HashMap keys, Caffeine...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/022bb6bbce/