Persistence is not authority: getting MapStore right
Persistence is not authority. How MapStore's write-through and write-behind behave when things fail, and where MapStore belongs.
There are a lot of misconceptions about Hazelcast's MapStore: what it is, how best to use it, and how not to use it. Some teams treat it as a convenient cache loader and nothing more. Others treat it as a way to make Hazelcast durable, or as a way to keep Hazelcast and a database in sync. The first view undersells it, and the other two lead to production incidents.
The mechanics are well covered already. The Hazelcast docs explain building a cache with MapStore, configuring it and implementing your own, and A Hitchhiker's Guide to Caching Patterns explains read-through, write-through and write-behind as patterns. This post doesn't repeat them. It covers three things those pages leave out:
- what MapStore is actually for, which starts with who owns the data;
- how write-through and write-behind behave when something goes wrong, scenario by scenario;
- given all that, the use cases and patterns where MapStore works best, and where it doesn't belong.
Persistence is not authority
Before choosing read-through, write-through or write-behind, answer one question: who owns the data?
It's easy to assume that because MapStore writes your data to a database, that database is now the trustworthy copy. But persisting data doesn't make it authoritative. These are two different properties:
- Persistence is a storage property. It means the data survives on disk.
- Authority is an architectural responsibility. It means this is the copy that decides what's correct when the copies disagree.
In a pure caching architecture there are three roles:
- The System of Record (SoR) holds the authoritative application state. It owns the data and decides what is correct.
- The Hazelcast map is a fast, in-memory copy derived from that authoritative data.
- MapLoader / MapStore and its backing database let you load, keep and recover that cached data independently of the Hazelcast cluster's lifetime.
The MapStore's database is physically persistent, but from the application's point of view it's still disposable: everything in it could be rebuilt from the System of Record. So Hazelcast, MapStore and the backing database together form an optional acceleration layer, not a component that owns application state.
There's a simple test that tells you which situation you're in:
If both Hazelcast and its MapStore database were deleted tomorrow, would the application lose business data, or only performance?
If you'd only lose performance, you have a cache, and MapStore is doing what it does best. If you'd lose business data, then Hazelcast and its MapStore have become part of your system of record. That's a legitimate choice, but it means their failure behaviour, described in the next section, is now your durability guarantee.
One more point, because it causes more production incidents than any configuration setting. MapStore can be connected straight to your System of Record, and that's a common and valid design. But MapStore is not a synchronisation mechanism. It has no way of seeing changes made to the database by anything other than Hazelcast. If another application, a batch job or an administrator updates a row, Hazelcast keeps serving the old value until that entry is evicted, expires or is reloaded. If your database has other writers, you need something else as well, such as change data capture (CDC), explicit cache invalidation or a reconciliation job.
MapStore provides persistence for a cache. It does not, by itself, keep that cache consistent with a System of Record.
How write-through and write-behind behave when things go wrong
On a good day, write-through and write-behind look almost the same: you put() a value, and it ends up in the database. The differences show up on bad days. The scenarios below are the ones that matter in production. They describe Hazelcast Platform 5.7, checked against the open-source code and, for Enterprise Persistence, the public documentation.
Thirteen scenarios
1. Normal write
- Write-through:
put()returns only after the database has the value. Every write is as slow as the database. - Write-behind:
put()returns as soon as the value is in memory. The database gets it later, in batches. Much faster, but a successfulput()doesn't mean the data is in the database yet.
2. The database rejects a write (for example, a constraint violation)
- Write-through: The
put()fails, the caller sees the error, and the map is unchanged. - Write-behind: The
put()has already succeeded, so the caller never finds out. Hazelcast retries the rejected entry indefinitely. One bad record keeps failing in the background until someone fixes the data.
3. The database is slow or briefly down
- Write-through: Writes slow down or fail. Your application's write availability is the database's availability.
- Write-behind: Writes carry on normally while a backlog builds up in memory. The data at risk is everything written since the outage began, not just the last few seconds. When the database comes back, the backlog arrives as a sudden burst of load.
4. The database stays down for a long time
- Write-through: Writes keep failing.
- Write-behind: With write coalescing off, each member's queue fills up (50,000 entries by default, shared across all maps and including backup copies). New writes then fail with
ReachedMaxSizeException. This is when a database outage turns into an application error.
5. A member crashes while the database is healthy
- Write-through: Every acknowledged write is already in the database. A write that was in flight may have reached the database even though the caller got an error, so a retry writes it twice.
- Write-behind: A backup copy takes over and replays the pending writes. Some may reach the database twice.
6. A member crashes while the database is lagging
- Write-through: Same as scenario 5.
- Write-behind: Backups drop their copy of each pending write about 10 seconds after its write delay expires, whether or not it has reached the database. If the database is more than that far behind when the member crashes, those writes are lost. The new value is still in Hazelcast, but it never reaches the database.
7. Planned shutdown, database healthy
- Write-through: Nothing is pending.
- Write-behind: Pending writes are flushed to the database before the member stops.
8. Planned shutdown, database down
- Write-through: Nothing is pending.
- Write-behind: The shutdown flush tries each write three times, one second apart, then drops whatever failed and carries on shutting down. The log says "Hazelcast will indefinitely retry to store them", but during a shutdown nothing retries them.
9. Whole cluster lost, no Persistence
- Write-through: The database has every acknowledged write. The cache is rebuilt from it.
- Write-behind: Every write that hadn't reached the database is lost.
10. Whole cluster restarted with Persistence
- Write-through: The map and the database agree (apart from the in-flight case in scenario 5).
- Write-behind: Persistence restores the map's values from local disk, but not the queue of pending database writes, and nothing replays them. The map can now hold values the database never received. A delete that never reached the database leaves no trace at all. Nothing warns you.
11. Another system updates the database directly
- Write-through: Hazelcast serves the old value until the entry is evicted, expires or is reloaded.
- Write-behind: Same, and a pending write from Hazelcast may later overwrite the other system's change.
12. The same key is updated many times quickly
- Write-through: Every update is written to the database.
- Write-behind: With write coalescing on (the default), only the latest value is written, and the intermediate values never reach the database. That's efficient, but you lose the change history.
13. Different keys are updated in a sequence
- Write-through: The database sees the writes in the order the callers made them.
- Write-behind: Batches from different partitions and members interleave, so the database can see writes to different keys in a different order.
For readers who want to check the mechanics: the retry logic, the backup timer, the queue limit, the shutdown flush and the write-through ordering are all linked in the source. What Persistence covers is described in the Persistence documentation.
What the scenarios tell you
Three patterns stand out.
Write-through doesn't lose acknowledged writes, but it can still diverge. Because the database write happens before the in-memory update, a put() that succeeded is in the database. What write-through can't give you is a single atomic commit across Hazelcast and the database. So the risk is a write that landed even though the caller saw an error (scenario 5), not a write that vanished.
Write-behind's risk window is as long as your worst database outage. The write-delay-seconds setting controls when Hazelcast first tries to write, not how long data can stay unwritten. Backups, graceful shutdown and Persistence all help in some cases. But as scenarios 6, 8 and 10 show, none of them guarantees that a pending write reaches the database.
In both modes, writes can be repeated. Retries, failover and backup replay all mean the database can receive the same write more than once (scenarios 5 and 6). The MapStore Javadoc says it plainly: assume at-least-once delivery, and make your writes idempotent.
Use cases and patterns
With that behaviour in mind, here's where MapStore works well, and how to set it up so the side effects work for you rather than against you.
Pattern A: Read-through cache over a system of record
Good for: product catalogues, reference and pricing data, customer profiles, configuration. Large datasets where a hot subset in memory is enough.
Shape: the database is authoritative. Hazelcast uses a MapLoader only (no MapStore writes) and loads entries on demand. Applications write to the database through its normal path, and changes reach Hazelcast through CDC or explicit invalidation. Eviction or a time-to-live (TTL) bounds both memory use and how stale an entry can get.
Why it works: none of the scenarios above apply, because Hazelcast never writes. The worst case is a stale read, and you control how stale.
Watch for: keys that don't exist. A load that returns nothing isn't cached, so repeated lookups for a missing key all go to the database. Cache "not found" briefly if that happens in your traffic. Also remember that queries run against what's in memory, not against the whole database.
Pattern B: Write-through for data that must be durable before you say yes
Good for: account settings, entitlements, reservations or inventory counts where every write goes through the application, and a confirmed write must already be in the database.
Shape: all writes go through Hazelcast with write-through. No other system writes to those tables. The MapStore uses idempotent, versioned writes, so a retry after an error (scenario 5) is harmless. Every database call has a timeout.
Why it works: a confirmed write is in the database, reads are served from memory, and the main risk (a duplicate write after an error) is designed out.
Watch for: the database's latency and availability become your write latency and availability (scenarios 1, 3 and 4). If the database is often slow, this isn't the right pattern.
Pattern C: Write-behind for fast-changing, low-stakes state
Good for: user sessions, shopping carts, presence, preferences, counters, rolling aggregates, ML feature values. State that changes often, where only the latest value matters, and where losing the writes from an outage is acceptable or can be rebuilt.
Shape: write-behind with coalescing on, so a key updated a hundred times becomes one database write (scenario 12). A loss budget agreed with the business, stated as "we can lose up to an outage's worth of updates", not "up to five seconds". Idempotent, versioned writes. Before planned maintenance, call IMap.flush() while the database is healthy and wait for the pending count to reach zero, because a shutdown flush against an unavailable database drops what's left (scenario 8).
Why it works: this is the case write-behind was built for. It absorbs write bursts, takes load off the database, and its failure modes cost little.
Watch for: a backlog that keeps growing. Watch the trend, not the size: a steadily growing queue means the database can't keep up. Plan how quickly the backlog may drain after an outage, so that recovery doesn't overload the database again.
Pattern D: Hazelcast as the source, the database as a rebuildable copy
Good for: state computed in Hazelcast from other sources, such as aggregates built from an event stream, or derived views. If it were lost, it could be recomputed.
Shape: Hazelcast is authoritative, and the MapStore database exists so that restarts are fast and other tools can read the data. Because its contents can be rebuilt, the database can be tuned for speed rather than durability (for example, PostgreSQL UNLOGGED tables). Persistence can be added for faster restarts. If you combine it with write-behind, run a reconciliation step after an abrupt cluster-wide restart (scenario 10).
Why it works: this pattern passes the deletion test honestly. Deleting both copies costs you recomputation time, not business data.
A related case: Hazelcast as an ORM second-level cache
For completeness, using Hazelcast as the second-level cache for Hibernate, through the Hazelcast Hibernate plugin, is a different use case and doesn't involve MapStore. Hibernate reads and writes the database itself, and fills or invalidates the cache around those calls. From Hazelcast's point of view, it's a cache-aside pattern. The database stays authoritative, so it passes the deletion test, and the write-behind scenarios above don't apply. Changes made outside Hibernate still leave the cache stale until entries expire (scenario 11). The details are out of scope here.
When MapStore is the wrong tool
Some requirements rule MapStore out, whichever mode you pick:
- Other systems write to the same tables. Use CDC (for example, a Hazelcast pipeline reading a change stream) to keep Hazelcast current. Don't write through MapStore.
- Correctness spans several records, or has to be atomic with the database. Ledgers, payments and orders with invariants belong here. Commit in the database first, then update or invalidate the cache.
- You need every intermediate change, such as an audit trail or event sourcing. Coalescing drops it, and ordering across keys isn't guaranteed (scenarios 12 and 13). Use an event log.
- Regulators will ask about the records. Write-behind's failure modes (scenarios 6, 8 and 10) are hard to defend in an audit.
Antipatterns: it works until it doesn't
These designs are more dangerous than the cases above, because they pass every test. They only fail in production, under load, at scale or during an incident, usually long after the design was signed off.
Write-behind as a fast, durable database
The application treats put() as "saved".
- Why it seems to work: In testing, the database is healthy and writes land within a second or two.
- When it stops working: The first time a member crashes while the database is lagging, or the cluster shuts down during a database outage, acknowledged writes never arrive (scenarios 6, 8 and 10).
Reading the database right after a write-behind put()
Reports, other services or a "verify" step read the table.
- Why it seems to work: Under light load, the delay between
put()and the database write is short. - When it stops working: Under load or during a slowdown, the backlog grows, and readers see old data for minutes.
A plain UPSERT with no version check
- Why it seems to work: Every write replaces the row, and replaying the same write changes nothing.
- When it stops working: A failover or retry replays an older value after a newer one, and the database quietly goes back in time (scenarios 5 and 6).
Sharing the tables with another writer
"Only a nightly job touches them."
- Why it seems to work: The job runs when traffic is low, and nobody notices the stale entries.
- When it stops working: Hazelcast serves pre-job values all day, or a pending write-behind entry overwrites the job's change (scenario 11).
Loading the whole table at startup (EAGER), with loadAllKeys() collecting every key into a list
- Why it seems to work: The test table has a few thousand rows, and startup takes seconds.
- When it stops working: At production size, members take minutes to start or run out of memory, and a rolling restart hits the database with every member's load.
No timeouts in the loader
- Why it seems to work: The database always answers in testing.
- When it stops working: One hung query blocks a loader thread indefinitely, and the map is stuck "still loading" until the member restarts.
Querying a lazily loaded map as if it were the database
- Why it seems to work: In tests everything has been read once, so it's all in memory.
- When it stops working: In production, queries return only what happens to be loaded, and the results are silently incomplete.
Expecting expiry to delete rows
- Why it seems to work: Entries disappear from Hazelcast on schedule.
- When it stops working: The table keeps growing, and an expired entry comes back on the next read, because expiry and eviction never call
delete().
Ignoring records the database rejects
- Why it seems to work: Bad records are rare, and a log line here and there doesn't worry anyone.
- When it stops working: One poison record retries indefinitely. With coalescing off, enough of them fill the queue until new writes fail (scenarios 2 and 4).
Two put()s for one business change
For example, debiting one account and crediting another.
- Why it seems to work: Both writes almost always land.
- When it stops working: A crash between them, or writes to different keys arriving out of order (scenario 13), leaves the database in a state the business rules don't allow.
What these share is that the failure depends on timing or scale, not on the code path. A test suite with a healthy database, small data and no member failures will pass every one of them. The only way to find them early is to test the way production fails: kill members while the database is slow, take the database down during a shutdown, and load production-sized data.
Before you go live
Whichever pattern you choose, a production-ready MapStore needs these five things:
- Idempotent, versioned writes. A plain UPSERT makes a repeated write harmless, but a replayed older write can still overwrite a newer one. Store a version and accept only newer versions. Use a versioned tombstone for deletes that must stick.
- Honest batch reporting. If
storeAllpartly succeeds, remove the entries that committed from the batch before you throw, so that only the rest is retried. - A plan for bad records. Hazelcast retries a record the database will never accept indefinitely (scenario 2). Classify the error, move the record to a dead-letter store and alert someone.
- Timeouts on every database call. Hazelcast doesn't add any timeout around your loader. A database call that never returns can leave a map stuck "still loading" until the member restarts.
- Monitoring that sees the backlog. Hazelcast's StoreLatency diagnostics show how long your store calls take. Executor queue metrics show work waiting to run, and the dirty-entry count shows pending writes. Log failures from inside the store with the key and the error code, so that "the MapStore failed" turns into "these three records keep failing on this constraint".
Back to the test
If Hazelcast and its MapStore database disappeared tomorrow, would you lose business data, or only performance?
If the answer is "only performance", you're using Hazelcast the way it was designed to be used: Pattern A or D (or an ORM second-level cache), or C with a loss budget you've agreed with the business.
If the answer is "business data", make that a deliberate decision. Use Pattern B, or move the authoritative copy into a database and feed Hazelcast from it. Either way, write down which of the scenarios you're accepting, test them by actually failing a member, and make sure everyone who relies on the data knows what they are.
Persistence is something you configure. Authority is something you design.
Views are my own, not my employer's.