Skip to content
javahacks.dev
Architecture

Redis vs Hazelcast Infinispan for Java Applications

Compare Redis, Hazelcast and Infinispan for shared caching and state in Java: deployment model, data structures, near caches, consistency and when each fits.

7 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the Redis, OpenJDK, Docker, Apache Maven and Gradle logos.

When one in process cache stops being enough, the next step is a shared one, and Java teams usually weigh the same three candidates: Redis, Hazelcast and Infinispan. They overlap in features and differ sharply in deployment model, and the deployment model is what decides which one hurts less over the years. This post builds the same small use, a shared session style counter with a time to live, in each and then compares the operational shape. If a local cache is all you need, Caffeine versus Guava versus Ehcache covers that.

The job

An API enforces a login attempt limit per account: five failures per fifteen minutes. State has to be visible to every instance behind the load balancer, expire on its own and be updated atomically so two instances cannot both let the sixth attempt through. That is a small problem that exposes the real differences: atomic increment, expiry and the network.

Redis

Redis is a server. Your Java process connects with a client, and Spring Boot ships spring-boot-starter-data-redis with Lettuce as the default client.

src/main/java/dev/javahacks/auth/RedisAttemptLimiter.javajava
package dev.javahacks.auth;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
public class RedisAttemptLimiter {
    private static final int LIMIT = 5;
    private static final Duration WINDOW = Duration.ofMinutes(15);

    private final StringRedisTemplate redis;

    public RedisAttemptLimiter(StringRedisTemplate redis) {
        this.redis = redis;
    }

    public boolean recordFailure(String account) {
        String key = "login:fail:" + account;
        Long count = redis.opsForValue().increment(key);
        if (count != null && count == 1) {
            redis.expire(key, WINDOW);
        }
        return count != null && count <= LIMIT;
    }
}

INCR is atomic on the server, so two instances incrementing at once get distinct numbers. There is a subtle gap, though: if the process dies between increment and expire, the key lives forever and the account stays locked. Production code closes it with a small Lua script, which Redis runs atomically:

java
private static final RedisScript<Long> SCRIPT = RedisScript.of("""
        local c = redis.call('INCR', KEYS[1])
        if c == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
        return c
        """, Long.class);

Long count = redis.execute(SCRIPT, List.of(key), String.valueOf(WINDOW.toSeconds()));

The shape here is the Redis model in miniature: the data lives in another process, every operation is a network round trip of a fraction of a millisecond to a few milliseconds depending on your network, and atomicity comes from server side commands and scripts.

Hazelcast

Hazelcast can run as a client talking to a cluster, or embedded: your application nodes form the cluster themselves. Embedded is the mode that makes it distinct.

src/main/java/dev/javahacks/auth/HazelcastAttemptLimiter.javajava
package dev.javahacks.auth;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class HazelcastAttemptLimiter {
    private static final int LIMIT = 5;
    private final IMap<String, Integer> attempts;

    public HazelcastAttemptLimiter(HazelcastInstance hazelcast) {
        this.attempts = hazelcast.getMap("login-failures");
    }

    public boolean recordFailure(String account) {
        Integer count = attempts.compute(account, (k, v) -> v == null ? 1 : v + 1);
        attempts.setTtl(account, 15, TimeUnit.MINUTES);
        return count <= LIMIT;
    }
}

IMap implements ConcurrentMap, so it reads like code you already know, and compute on a map entry is executed atomically on the member that owns the key. The map is partitioned across the cluster: each key has an owner node plus one or more backups. In embedded mode, a read for a key your own node owns is a local method call with no network, which is where the low latency comes from.

Infinispan

Infinispan is Red Hat's data grid and the cache behind WildFly clustering. It also runs embedded or as a server, and has the strongest ties to the Jakarta EE and Quarkus world.

src/main/java/dev/javahacks/auth/InfinispanAttemptLimiter.javajava
package dev.javahacks.auth;

import org.infinispan.Cache;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.manager.DefaultCacheManager;

import java.util.concurrent.TimeUnit;

public class InfinispanAttemptLimiter {
    private final Cache<String, Integer> attempts;

    public InfinispanAttemptLimiter() {
        var manager = new DefaultCacheManager(GlobalConfigurationBuilder.defaultClusteredBuilder().build());
        manager.defineConfiguration("login-failures", new ConfigurationBuilder()
                .clustering().cacheMode(CacheMode.DIST_SYNC).hash().numOwners(2)
                .expiration().lifespan(15, TimeUnit.MINUTES)
                .build());
        this.attempts = manager.getCache("login-failures");
    }

    public boolean recordFailure(String account) {
        Integer count = attempts.merge(account, 1, Integer::sum);
        return count <= 5;
    }
}

DIST_SYNC with numOwners(2) means each key lives on two nodes and a write returns after both acknowledge. Infinispan's Cache also extends ConcurrentMap, and merge is atomic. The expiration is set on the cache definition rather than per call, which keeps the limiter code short. Infinispan also offers transactions, querying and persistence to a store, features that make it more of a data platform than a cache.

Embedded versus remote is the real choice

Everything above hides the most consequential difference. In Redis, the data is outside your processes. In embedded Hazelcast or Infinispan, the data is inside them. That decides four things.

Deployments. Restarting a Redis client application changes nothing about the data. Restarting an embedded member makes the cluster rebalance partitions, and a rolling update of fifty pods is a rolling rebalance. Done carelessly, a deploy that replaces nodes faster than backups sync can lose partitions.

Memory. Embedded data sits on your heap or off heap alongside your application. A cache of two gigabytes per node changes your JVM sizing and your garbage collection behaviour. In Redis, that memory is on a separate machine you can size independently.

Latency. An owned key in an embedded grid is a local call. In Redis it is a network call every time. A near cache, a small local copy of hot entries that all three support, narrows the gap for read heavy keys:

java
// Hazelcast near cache on the map used by hot reads
config.addMapConfig(new MapConfig("product-catalog")
        .setNearCacheConfig(new NearCacheConfig().setMaxIdleSeconds(60)));

Blast radius. A memory problem in a Redis server affects the cache. A memory problem in an embedded grid affects the application that holds it, and a split brain network partition can leave two halves of the cluster each believing it owns the data.

What happens when the cluster is unreachable

Failure behaviour is the part of a shared cache that reviews skip and incidents expose. With Redis, a network partition or a restart makes every call throw a connection exception, and your code must decide: fail the request, or treat the cache as empty and carry on. For a login limiter, failing open means attackers get unlimited attempts while Redis is down, and failing closed means nobody can log in. That is a product decision, and it should be written in the code rather than left to whatever exception handler catches the error first. Wrap the call, choose a default and emit a metric so the choice is visible.

Embedded grids fail differently. A node that loses contact with the others may carry on alone with its partition of the data, then rejoin and merge. Hazelcast and Infinispan both let you choose a split brain policy, and the safe default for a limiter is to accept that the count may briefly be low. Test it: stop one node during a load test and read what the application logs. A cache whose failure mode you have only read about is one you have not yet chosen.

Comparison

RedisHazelcastInfinispan
Default deploymentSeparate serverEmbedded or client serverEmbedded or server
Java clientLettuce or Jedis, Spring Data RedisNative Java APINative Java API, Hot Rod client
Data modelStrings, hashes, lists, sets, streamsMaps, queues, topics, CP subsystemCaches, with indexing and queries
Atomic operationsCommands and LuaEntry processors, computeConcurrentMap operations, transactions
PersistenceSnapshots and append only fileOptional storeOptional store
Ecosystem fitSpring Boot, most stacksSpring Boot, standaloneWildFly, Quarkus, Hibernate L2

A decision

Start with Redis for shared caching, rate limits, session storage and distributed locks. It is the most widely operated, the best supported by managed cloud services and the one most teams already run, and the Java application stays stateless. Choose embedded Hazelcast or Infinispan when you need distributed execution close to the data, very low latency reads that a network hop would spoil or a JVM only deployment with no extra infrastructure to run. Choose Infinispan when you are already on WildFly or Quarkus, where it is the natural integration.

Whichever you pick, treat the data as disposable unless you built the durability on purpose. A cache that cannot be rebuilt from the source of truth is a database wearing a disguise, and none of these is configured by default to behave like one. For distributed coordination built on top of them, see implementing a distributed lock in Java.

When this does not apply

If you have one instance of the service, a local Caffeine cache is simpler and faster than any of these. If you need durable, queryable, transactional data, you want a database. And if you only need a message hand-off between services, a broker is the right tool, as described in synchronous versus asynchronous communication. The official references are the Redis documentation, the Hazelcast documentation and the Infinispan documentation.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.