TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท databases ยท in-memory ยท java ยท distributed systems ยท caching

Hazelcast

Hazelcast is an in-memory data platform for the JVM that spreads data over a cluster in 271 partitions with backups, runs code and queries where the data lives, and stays available by default, with a Raft-based CP Subsystem (Enterprise) for locks and counters.

16 min8 animations

๐Ÿ“š Builds on๐Ÿ“‹ Distributed cachingโญ• Consistent hashing

๐Ÿ–จ๏ธ Cheat sheet

A hive that shares its honey

Picture a hive with lots of worker bees. No single bee keeps all the honey. Each bee looks after some of the cells in the honeycomb, and together they hold everything.

Each bee in the hive is called a member, and the whole hive is the cluster. If you want more room, you add another bee.

A gardener who needs honey can live right next to the hive and keep a bee of her own, so she is part of the hive herself. Or she can visit from outside, knock on a bee's door and be handed a map of the whole hive. After that she walks straight to the bee that has what she needs.

What Hazelcast is

Hazelcast is an in-memory data platform for the JVM. It combines a distributed data grid (maps, queues, topics, counters, locks, all held in the RAM of a cluster of members) with a stream and batch processing engine (Jet) and SQL. It's offered as a free Community Edition and a paid Enterprise Edition; some features below differ between them, and the text says so where it matters.

You run it in one of two shapes:

  • Embedded: each application JVM starts a member, so the app and the data share a process. Scaling the app scales the data.
  • Client-server: members run as their own processes, and applications connect as clients. Java is the main client; Python, Node.js, .NET, C++ and Go clients exist too.

Members find each other by multicast, a list of TCP/IP addresses, or plugins for Kubernetes and cloud platforms (the default port is 5701), and clients join by cluster name. By default a client is smart (cluster-routing mode ALL_MEMBERS in 5.5+): it connects to every member and sends each request straight to the member that owns the key.

1// Embedded: this JVM is a member of the cluster2HazelcastInstance member = Hazelcast.newHazelcastInstance();3 4// Client-server: this JVM is a client of an existing cluster5ClientConfig cfg = new ClientConfig();6cfg.setClusterName("dev");7cfg.getNetworkConfig().addAddress("10.0.0.1:5701");8HazelcastInstance client = HazelcastClient.newHazelcastClient(cfg);

The most common use is a shared, distributed cache or session store (see distributed caching), but the platform also runs computations on the data it holds.

A smart client and the partition table4 steps
๐Ÿฏ The hive๐Ÿง‘โ€๐ŸŒพGardener๐ŸBee Ada๐ŸBee Bo๐ŸBee Cy
Press play and watch it happen!

Numbered cells, each with a twin

The honeycomb has 271 numbered cells. Every jar of honey has a label, and the label decides which cell it goes in. The same label always picks the same cell.

Each cell has one bee who looks after it, the owner. A twin copy of the cell is kept with a different bee, in case the owner is lost. The hive also keeps a map of which bee looks after which cell and where each twin lives. Each numbered cell is a partition, and that map is called the partition table.

When the gardener hands over a jar, the owner puts it in the cell and then makes the twin. The owner can wait for the twin to be finished before saying "done", which is slower but safe. Or it can say "done" at once and finish the twin afterwards, which is faster but risky.

Partitions, owners and backups

Hazelcast splits each data structure into partitions: 271 by default (hazelcast.partition.count, which must be the same on every member and can't change on a running cluster). A key's partition is a hash of its serialized bytes modulo the partition count. Like Redis Cluster's hash slots (see Redis Cluster), this is a fixed number of buckets with an explicit table, not a ring as in consistent hashing.

The partition table lists, for each partition, an ordered set of replicas: replica 0 is the owner and the rest are backups, each on a different member. The oldest member acts as master and publishes the table; members and smart clients cache it and route by it.

Backups are set per data structure:

1hazelcast:2  map:3    sessions:4      backup-count: 1          # synchronous backups (default 1)5      async-backup-count: 0    # asynchronous backups (default 0)
  • With a synchronous backup, a write returns only after the backup member has applied it. You pay a round trip and gain safety.
  • With an asynchronous backup, the owner acknowledges first and sends the backup afterwards. A crash in between can lose an acknowledged write.
  • Both kinds can be combined. More backups cost memory: with backup-count: 1 every entry exists twice, with 2 three times. The documented maximum is 6 backups, synchronous and asynchronous together.

By default, all reads and writes for a key go to its owner, so operations on one key are processed one at a time there. Background anti-entropy checks repair backups that fall behind.

๐Ÿ”ง Going deeper

Keeping related keys together. Hazelcast hashes the key, so two related keys can land on different members. The PartitionAware interface, or the key@partitionKey form for String keys once the map's partition-strategy is StringPartitioningStrategy, makes several keys use one partition key (5.4 and later can also partition by key attributes), so an operation on them can run on a single member. The same idea as hash tags in Redis Cluster; as there, don't tag everything the same, or one partition becomes a hotspot. Lite members are cluster members that own no partitions: useful for compute or as query front ends.

Owners and backups5 steps
๐Ÿฏ Ada's cells๐Ÿฏ Bo's cellsCell 70123Cell 7 twin0123๐Ÿง‘โ€๐ŸŒพGardener๐ŸBee Ada๐ŸBee Bo๐ŸBee Cy
Press play and watch it happen!

A bee goes missing

Suppose the bee that owns cell 7 vanishes. The other bees notice she has stopped answering. The bee holding the twin of cell 7 steps up and becomes its owner, and the hive updates its map.

Now cell 7 has no twin, so the hive picks another bee and copies the cell over to her. This careful moving of cells between bees is called migration.

It happens whenever the hive changes. If a new bee arrives, the hive gives her some cells, moving them a few at a time while everyone keeps working. If a bee leaves politely, the hive moves her cells off first, so nothing is at risk.

Members joining and leaving

Failure detection uses heartbeats between members, and a connection that keeps failing is dropped within moments. A member that goes silent is removed after the heartbeat timeout (hazelcast.max.no.heartbeat.seconds, 60 seconds by default). When a member is removed:

  1. The master promotes the first surviving backup of each of its partitions to owner and bumps the partition table version.
  2. The new table is published to members and clients.
  3. The cluster creates fresh backups on other members, copying whole partitions in the background. This is migration.

Joining is the reverse: the master rebalances by migrating partitions to the new member, a few at a time, while the cluster serves requests (operations for a partition mid-move are briefly retried). A graceful hz.shutdown() migrates its data off first and is safe; a crash is survived only as far as the backups go.

The limit to remember: with backup-count: 1, losing the owner and its only backup before migration re-creates the backup loses that partition's data. In the free Community Edition the data lives only in memory, so a full-cluster restart loses it, unless you add a MapStore that writes through to a database. Enterprise adds a Persistence feature that stores data on disk.

Migrations cost network and CPU, so churn matters: restarting members all at once, or flapping members, keeps the cluster busy moving data.

A member dies and the cluster heals5 steps
๐Ÿฏ Ada's cells๐Ÿฏ Bo's cells๐Ÿฏ Cy's cellsCell 70123Cell 7 twin0123๐Ÿง‘โ€๐ŸŒพGardener๐ŸBee Ada๐ŸBee Bo๐ŸBee Cy
Press play and watch it happen!

Shelves of jars, a pocket jar and a dancing bee

The hive's main shelf is a set of labelled jars: put a jar in, take it out by its label. Jars can come with an expiry time, after which the honey is thrown away. A shelf can have a size limit, and when it's full the jar least wanted is thrown out. The bees can ring a bell whenever a jar is added, changed or removed.

A gardener who asks for the same jar all day can keep a small pocket jar by her door with a copy. That's quick, but the copy can go stale, so the hive sends word when the real one changes. That pocket jar is a near cache.

There are also a line of job notes where each note goes to one bee, and a waggle dance where one bee tells everyone watching, but nobody who walks in late sees past dances.

IMap, near cache, queues and topics

IMap is the main structure: a distributed ConcurrentMap partitioned as above.

  • TTL and max-idle: time-to-live-seconds expires an entry that long after its last write; max-idle-seconds expires it after its last read or write. Per entry: map.put(key, value, 1, TimeUnit.HOURS).
  • Eviction: off by default. Set eviction-policy (LRU, LFU) with a max-size-policy and size to cap memory.
  • Entry listeners: addEntryListener delivers add, update, remove and evict events, asynchronously.
  • MapStore: optional read-through and write-through to a database.

A near cache keeps recently read entries in the memory of the client or member that asked, so a repeat read costs no network hop. The owner sends invalidation events when an entry changes (invalidate-on-change is true by default), so near caches are eventually consistent: for a short time, or after a lost event, a reader can see a stale value. Hazelcast detects missed invalidations and drops affected entries. in-memory-format: OBJECT stores deserialized objects so reads don't deserialize again.

1ClientConfig cfg = new ClientConfig();2NearCacheConfig near = new NearCacheConfig("products");3near.setInMemoryFormat(InMemoryFormat.OBJECT);4cfg.addNearCacheConfig(near);

IQueue is a distributed blocking queue held in one partition (with backups). ITopic is publish/subscribe: subscribers only see messages published after they subscribe, and nothing is stored. ReliableTopic keeps recent messages in a Ringbuffer so slow subscribers can catch up. For durable, replayable messaging at scale, use Kafka instead.

A near cache and its invalidation6 steps
๐Ÿฏ The hivePocket jar012Shelf of jars012๐Ÿง‘โ€๐ŸŒพGardener๐Ÿ‘ฉโ€๐ŸŒพOther gardener๐ŸBee Ada
Press play and watch it happen!

Send the bee to the honey

Say the gardener wants to take one spoonful from the apple jar. She could ask the owner to hand the whole jar over, carry it home, take her spoonful and carry it back. That's two long trips, and while it's gone, another gardener might also take a spoonful from the old jar, so one spoonful is forgotten.

The better way is to give the owner a short work order: take one spoonful and tell me what's left. The owner does it on the spot, with no one interrupting, and the jar never leaves the cell.

The hive can also find jars without opening every one, if the bees have put labels on the lids. Each bee checks only her own cells and the answers are put together.

Running code where the data is

The slow pattern is get, change in the client, put: the value crosses the network twice, and two clients can interleave and overwrite each other. An EntryProcessor ships the code to the member that owns the key and runs it there, on that partition's thread, so nothing else touches the partition while it runs. No explicit lock is needed, and only the (small) result comes back.

1public class Sell implements EntryProcessor<String, Integer, Integer> {2    @Override3    public Integer process(Map.Entry<String, Integer> entry) {4        int left = entry.getValue() - 1;5        entry.setValue(left);          // modifies the entry in place, on the owner6        return left;7    }8}9 10IMap<String, Integer> stock = hz.getMap("stock");11int left = stock.executeOnKey("apples", new Sell());

executeOnEntries(processor, predicate) runs it across all members in parallel. The cautions are real: a processor holds the partition thread, so keep it short and never block on I/O or call other maps from it. In client-server mode, the processor class must also be on the members' classpath (or deployed with Enterprise User Code Namespaces).

Queries also run where the data is. Each member filters its own partitions and the results are merged:

1stock.addIndex(IndexType.SORTED, "this");     // index the value itself2Collection<Integer> low = stock.values(Predicates.lessThan("this", 5));

Without an index, each member scans all its entries, which means deserializing them. Hazelcast SQL (hz.getSql().execute(...)) queries maps and also feeds Jet. Before SQL can read a map, you create a mapping for it (CREATE MAPPING stock TYPE IMap OPTIONS ('keyFormat'='varchar', 'valueFormat'='int')). Pulling a whole map to the client to filter it there is the mistake to avoid.

Pull the data or push the code4 steps
๐Ÿฏ Ada's cellsApple jar0123๐Ÿง‘โ€๐ŸŒพGardener๐ŸBee Ada
Press play and watch it happen!

Carry on, or wait for a vote

Suppose a fence goes up through the hive and the bees can't pass over it. The bees on each side can't tell whether the others are gone or just cut off. By default they carry on. Each side keeps serving gardeners, and may even change the same jar. That keeps honey flowing, but it means two versions can exist.

When the fence comes down, the two halves meet and must decide which jar to keep. They follow a merge policy, a simple rule such as "the newest one wins" or "keep the one already there". Some changes made during the split can be lost.

For jobs where two answers would be dangerous, like who holds the single key to the nursery, the hive has a small council of bees. A decision counts only when most of the council agrees. If the fence cuts the council off from its majority, the council simply waits, because waiting is safer than guessing.

AP by default, CP when you ask

Hazelcast's data structures favour availability (the A of the CAP theorem). If the network splits the cluster into two, each part keeps serving, promotes its backups and builds new ones: a split-brain. When the parts can reach each other again, the smaller cluster (by member count) merges into the larger. For each entry that existed on the smaller side, the structure's merge policy decides the result. Built-in ones include PutIfAbsentMergePolicy, LatestUpdateMergePolicy, HigherHitsMergePolicy, PassThroughMergePolicy and DiscardMergePolicy. The default for every structure that supports merging is PutIfAbsentMergePolicy (HyperLogLogMergePolicy for CardinalityEstimator). LatestUpdateMergePolicy needs per-entry-stats-enabled on the map. Writes made on the losing side during the split can vanish or be overwritten, so pick the policy to match what your data means. Structures like semaphores and latches have no merge, and the smaller side's copy is discarded.

For correctness, Hazelcast has the CP Subsystem, built on the Raft consensus algorithm (see consensus). It gives linearizable FencedLock, IAtomicLong, IAtomicReference, ISemaphore and ICountDownLatch:

1FencedLock lock = hz.getCPSubsystem().getLock("invoice-run");2long fence = lock.lockAndGetFence();   // a fencing token that grows with each lock3try {4    // protected work5} finally {6    lock.unlock();7}
  • It is off by default (cp-member-count: 0), and CP structures then run in unsafe mode, with no consistency guarantees and fit only for development. Set cp-member-count to at least 3. CP groups have an odd size of 3 to 7, and a group works only while a majority of its members are reachable. The minority side of a split stops serving CP operations. That is the trade: consistency over availability.
  • CP structures are small coordination primitives. Your IMap data is still AP.
  • Editions: From 5.5 the CP Subsystem is Enterprise-only (a breaking change for Community users), and so is CP Subsystem Persistence, which lets CP members recover state from disk.
๐Ÿ”ง Going deeper

Locks without CP. IMap.lock(key) still exists, but its state is AP data: it can be lost or duplicated across a split. A FencedLock returns a monotonically increasing fencing token you pass to the resource, so that a paused old holder can be rejected. Compare how Redis distributed locks face the same questions.

Split-brain and the merge policy5 steps
๐Ÿฏ Left half๐Ÿฏ Right halfShelf, left side012Shelf, right side012๐Ÿง‘โ€๐ŸŒพGardener Mia๐ŸBee Ada๐ŸBee Bo๐ŸBee Cy๐Ÿ‘ฉโ€๐ŸŒพGardener Raj
Press play and watch it happen!

What can go wrong

A bee dozes off. If a bee falls asleep for a very long time, the others decide she's gone, rebuild her cells' twins elsewhere and carry on. When she wakes, she has to be let back in as if new, and all that carrying happens again.

Huge jars. A jar so big it needs two bees to lift is slow every time it's moved or copied. The cells with the biggest jars get slow, and the hive spends its day moving them.

Too few cells to go round. With only 271 cells and lots of bees, some bees get a cell more than others, and the bee with the extra cell is always busier. You can't add cells after the hive is built.

What can go wrong

  • Split-brain. A network partition makes two clusters that both accept writes (see above). Symptom: two cluster views with different sizes in logs and monitoring; after healing, lost or overwritten updates. Fix: a merge policy that fits the data, split-brain protection (a minimum cluster size) so the minority side rejects operations, and CP primitives (Enterprise) for anything that must not diverge.
  • Slow or huge values. Every get and put serializes and deserializes, and big values also fill the network, the heap and each migration. Java serialization is slow and bulky. Symptom: high latency, slow-operation warnings from the slow operation detector, long migrations. Fix: smaller values, a leaner serializer such as IdentifiedDataSerializable or Compact serialization, OBJECT format where reads dominate, and splitting big values across keys.
  • GC pauses on large heaps. Members keep data on the Java heap, so big heaps mean long stop-the-world collections. A pause longer than the heartbeat timeout gets the member removed, triggering migrations, and when it wakes it must rejoin: a migration storm. Symptom: members leaving and joining in the logs, long GC lines. Fix: moderate heaps with more members, a modern collector (G1 or ZGC), headroom for backups, and Enterprise's off-heap High-Density Memory Store. Raising the heartbeat timeout hides pauses but slows detection of real failures. See garbage collection.
  • Too few partitions per member. 271 partitions over 50 members is about 5 each, and one extra is a fifth more load. A single hot key can't be spread at all. Fix: size the cluster so each member holds dozens of partitions, spread keys well, and decide the partition count before first start.
  • Migration churn. Restarting many members at once, or members that keep flapping, keeps the cluster copying partitions. Fix: roll restarts one at a time with graceful shutdown.
ChoiceYou gainYou pay
Synchronous backupsNo acknowledged write lost on one failureA network round trip per write
Asynchronous backupsFaster writesA crash can lose acknowledged writes
Near cacheLocal, network-free readsStale reads until invalidated
Bigger heap per memberFewer members to runLonger GC pauses
Embedded membersNo extra network hop for local dataApp and data scale and restart together
A long GC pause looks like a crash6 steps
๐Ÿฏ The hive๐Ÿง‘โ€๐ŸŒพGardener๐ŸBee Ada๐ŸBee Bo๐ŸBee Cy
Press play and watch it happen!

A hive in your garden, or a hive down the road

A gardener who keeps bees in her own garden can reach her own bees without leaving the garden. Jars owned by those bees come to her at once. Jars owned by other bees need one trip to another garden. But her garden and her bees now come and go together, and if she shuts the garden, her bees go too.

A gardener visiting an outside hive always makes a trip. In return, the hive keeps running when she goes home.

A different kind of helper is a storeroom down the road with one very quick keeper. It's simple, and everyone knows how to use it. The keeper can follow short written instructions too, but she can't run your own gardener's tools the way a bee in your garden can.

Hazelcast or Redis

Both keep data in memory, split it into a fixed number of buckets (271 partitions against Redis Cluster's 16,384 slots) and replicate it. They fit different jobs.

HazelcastRedis or Valkey
ShapeJava library you can embed, or a cluster of JVMsA separate server in C, used by any language
Data modelIMap, queues, topics, counters, plus SQL and Jet streamingStrings, hashes, lists, sets, sorted sets, streams and more, with a rich command set
Running code on dataEntryProcessor, distributed queries, Jet jobs, all in JavaCommands, Lua scripts and functions
ReplicationSynchronous or asynchronous backups, per structureAsynchronous replicas (WAIT narrows the window)
Locks and countersCP Subsystem with Raft (Enterprise from 5.5)Single-node atomic commands; locks with documented caveats
EcosystemSmaller; Java is the best-supported languageVery large, with managed services such as ElastiCache
LicenceCommunity: Apache 2.0 plus the Hazelcast Community License; patch releases and CP only in EnterpriseRedis 8+: RSALv2, SSPLv1 or AGPLv3 (7.4 was RSALv2/SSPLv1 only); Valkey: BSD-3-Clause

Hazelcast fits when the app is JVM-based, you want data in the same process or want to run Java logic next to it, or you need grid features such as near caches and entry processors, or stream processing over the same data. Redis fits when you want a small, well-known server used from many languages, rich data types, a huge community and managed hosting, and when your work is mostly simple commands. For a plain cache, both do the job; choose by team skills and operations, not by a benchmark. Compare the cluster side in Redis Cluster and the single server in Redis and Valkey.

Embedded member or separate client3 steps
๐Ÿก Mia's garden๐Ÿก Bo's garden๐Ÿง‘โ€๐ŸŒพGardener Mia๐ŸHer own bee๐ŸBee Bo
Press play and watch it happen!

๐Ÿ”Ž Spot it in real code

This is the hive as real Java code. Pick a label, then tap the line where that happens.

Tap the line where you see: Joining the hive with a bee of your own.

0 of 4 placed

๐Ÿงฉ Finish the code

Now set up the shelf yourself. Acknowledged jars must survive one lost bee, with just one twin per jar, jars must spoil an hour after they were last changed, and after a fence comes down the newest change must win.
  1. 1 Make one twin and wait for it before saying done
  2. 2 Spoil an hour after the jar was last changed
  3. 3 When the fence comes down, the newest change wins
1MapConfig stock = config.getMapConfig("stock");2stock.1(1);3stock.2(3600);4stock.setPerEntryStatsEnabled(true);5stock.getMergePolicyConfig().setPolicy(3);
0 of 3 gaps filled

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Hazelcast, told the same way as the story.
  1. Ada owns cell 7 and Bo keeps its twin, with the careful way of copying. The gardener hands Ada a jar. When does Ada say "done"?
  2. Ada vanishes, and her cell's twin is with Bo. What does the hive do?
  3. The gardener wants one spoonful from a huge jar. Which way is better, and why?
  4. A fence splits the hive and both halves change Ana's jar. When it comes down, with the keep-the-one-already-there rule, what happens?
  5. Why does a hive with a council of bees stop answering when a fence cuts the council off from its majority?
Answer every question to check.Passing marks Hazelcast as done.
Got the hang of Hazelcast? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿงฐ Caching with Redis, Valkey and HazelcastStep 8 of 8

โ† Previous on the path๐Ÿช Amazon ElastiCacheLast step ๐ŸŽ‰Back to the path