How to Use Hazelcast or Redis for Shared State in Java
Use Hazelcast or Redis for shared state in Java services: sessions, caches, locks and counters, with Spring configuration, trade-offs and failure handling.

Once an application runs on more than one instance, anything kept in a single instance's memory stops being shared. A user's session, a cache of expensive lookups, a counter, a lock: each of those needs a place that all instances can see. Redis and Hazelcast both provide that place, with different shapes. Redis is a separate server your instances talk to. Hazelcast is a library that runs inside your own JVMs and forms a cluster among them. This post compares them, shows the code for each, and covers the failure handling that decides whether shared state improves your system or becomes its weakest part.
Decide whether you need shared state at all
Shared state is a dependency, and every dependency can fail. Before adding it, check whether the problem has a simpler answer. A per-instance cache such as Caffeine is fine when each instance can fill its own copy and slightly stale data is acceptable; see choosing an eviction policy. Session state can be avoided entirely by using signed tokens, a trade-off covered in session versus JWT. Reach for a shared store when instances must agree: one rate limit across the fleet, one lock, one session store, one counter that must not double-count.
Redis
Redis is a separate process, usually managed, that holds data in memory and answers simple commands very quickly. Spring Data Redis is the usual client:
@Service
class VisitCounter {
private final StringRedisTemplate redis;
VisitCounter(StringRedisTemplate redis) {
this.redis = redis;
}
long hit(String page) {
String key = "visits:" + page;
Long count = redis.opsForValue().increment(key);
redis.expire(key, Duration.ofDays(1));
return count == null ? 0 : count;
}
}increment is atomic on the server, so concurrent instances never lose a count, which a read-modify-write in application code cannot promise. Set an expiry on everything. A key without one lives until someone removes it, and a cache that never evicts is a memory leak with a nicer name. Redis also stores Spring sessions through Spring Session, and works as the storage for a @Cacheable cache by setting spring.cache.type=redis. The client documentation is in the Spring Data Redis reference.
Hazelcast
Hazelcast runs inside your application. Each instance starts a member, the members discover each other and form a cluster, and distributed data structures are partitioned across them:
Config config = new Config();
config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
config.getNetworkConfig().getJoin().getKubernetesConfig().setEnabled(true);
config.getMapConfig("sessions").setTimeToLiveSeconds(1800);
HazelcastInstance hz = Hazelcast.newHazelcastInstance(config);
IMap<String, UserSession> sessions = hz.getMap("sessions");
sessions.put(token, session);An IMap behaves like a ConcurrentMap that spans the cluster. Because data lives in your JVMs, reads of data held on the local member avoid a network hop, and you can add a near cache so frequently read entries are kept locally. There is no separate server to run, and that is also the cost: the data lives in your application's heap, so cluster size, heap size and garbage collection pauses are now tied together. A rolling deployment moves data between members, which needs care. Details are in the Hazelcast documentation.
Choosing
| Redis | Hazelcast | |
|---|---|---|
| Where it runs | Separate server or managed service | Inside your JVMs |
| Operations | A service to run and monitor | Cluster membership and heap sizing |
| Client support | Every language | Mainly JVM, some other clients |
| Latency | A network call per operation | Local for data on the member, plus near caches |
| Data model | Strings, hashes, lists, sets, streams | Java collections, maps, queues, topics |
| Failure of the store | One central place to protect | Each member is a node of the store |
For most teams the answer is Redis, because managed offerings exist and the operational model is well understood. Choose Hazelcast when the application is Java throughout, when you want the data structures to be Java objects, and when you accept the store sharing the application's heap and lifecycle.
Distributed locks
A lock across instances is a common reason to add either store. In Redis the pattern is a key set only if absent, with an expiry, and released only by the holder:
Boolean acquired = redis.opsForValue().setIfAbsent("lock:nightly", ownerId, Duration.ofSeconds(30));
if (Boolean.TRUE.equals(acquired)) {
try {
runJob();
} finally {
// release only if we still own it; use a script so check and delete are atomic
redis.execute(RELEASE_IF_OWNER, List.of("lock:nightly"), ownerId);
}
}The expiry protects against a crashed holder and creates the danger: if the job takes longer than 30 seconds, the lock expires while the job still runs and another instance starts. Choose the expiry from the real worst-case duration, or renew it while working. Hazelcast offers a FencedLock through its CP subsystem, which provides stronger guarantees at the price of running the subsystem on at least three members. A lock that guards money or irreversible work should also be backed by a fencing token or an idempotent operation downstream; the full discussion is in leader election and distributed locks.
Plan for the store being unavailable
The failure mode that surprises teams is not data loss but a slow store. A Redis call that hangs for thirty seconds ties up request threads and takes the service down with it. Set short connect and command timeouts, usually tens to a few hundred milliseconds. Decide per use what happens when the call fails: a cache miss falls through to the database, a rate limiter fails open or closed depending on what it protects, a session store failure logs the user out. Wrap calls in the patterns from building a resilient client, with timeouts and a circuit breaker, and test the failure by stopping the store in a staging environment. Treat the data as disposable where you can, and design caches so that an empty store is slow but correct.
Keep state small
Shared state is expensive per byte. Store identifiers and small values, not whole object graphs, and set limits on the number of entries. Serialise with a format you can evolve, because a deployment where old and new versions run side by side will read each other's entries. Java serialisation is the wrong choice for this reason, and JSON or a schema-based format is safer.
Observe it from the start
Add metrics before the first incident. For Redis, track command latency, connection pool use, evictions and memory use against its configured maximum, and alert on a hit rate that drops, which usually means keys are expiring faster than they are being refilled. For Hazelcast, watch cluster size, partition migration activity, and the heap of each member, because a member that falls out of the cluster during a garbage collection pause causes a burst of data movement. Both expose their statistics through Micrometer. A dashboard with those four or five lines turns "the cache feels slow" into a specific, checkable statement.
When this does not apply
A single instance, or a stateless service that reads everything from a database, needs none of this. A database table with a unique constraint is often a perfectly good lock or counter at low volume and adds no new dependency.


