Skip Headers
Oracle® Coherence Getting Started Guide
Release 3.7.1

Part Number E22840-01
Go to Documentation Home
Go to Book List
Book List
Go to Table of Contents
Go to Feedback page
Contact Us

Go to previous page
Go to next page
View PDF

12 Read-Through, Write-Through, Write-Behind, and Refresh-Ahead Caching

Coherence supports transparent read/write caching of any data source, including databases, web services, packaged applications and file systems; however, databases are the most common use case. As shorthand "database" is used to describe any back-end data source. Effective caches must support both intensive read-only and read/write operations, and for read/write operations, the cache and database must be kept fully synchronized. Therefore, Coherence supports Read-Through, Write-Through, Refresh-Ahead and Write-Behind caching.



12.1 Pluggable Cache Store

A CacheStore is an application-specific adapter used to connect a cache to a underlying data source. The CacheStore implementation accesses the data source by using a data access mechanism (for example, Hibernate, Toplink Essentials, JPA, application-specific JDBC calls, another application, mainframe, another cache, and so on). The CacheStore understands how to build a Java object using data retrieved from the data source, map and write an object to the data source, and erase an object from the data source.

Both the data source connection strategy and the data source-to-application-object mapping information are specific to the data source schema, application class layout, and operating environment. Therefore, this mapping information must be provided by the application developer in the form of a CacheStore implementation. See "Creating a CacheStore Implementation" for more information.

12.2 Read-Through Caching

When an application asks the cache for an entry, for example the key X, and X is not in the cache, Coherence automatically delegates to the CacheStore and asks it to load X from the underlying data source. If X exists in the data source, the CacheStore loads it, returns it to Coherence, then Coherence places it in the cache for future use and finally returns X to the application code that requested it. This is called Read-Through caching. Refresh-Ahead Cache functionality may further improve read performance (by reducing perceived latency). See "Refresh-Ahead Caching" for more information.

Figure 12-1 Read Through Caching

The preceeding text describes this graphic.

12.3 Write-Through Caching

Coherence can handle updates to the data source in two distinct ways, the first being Write-Through. In this case, when the application updates a piece of data in the cache (that is, calls put(...) to change a cache entry,) the operation does not complete (that is, the put does not return) until Coherence has gone through the CacheStore and successfully stored the data to the underlying data source. This does not improve write performance at all, since you are still dealing with the latency of the write to the data source. Improving the write performance is the purpose for the Write-Behind Cache functionality. See "Write-Behind Caching" for more information.

Figure 12-2 Write-Through Caching

The preceeding text describes this graphic.

12.4 Write-Behind Caching

In the Write-Behind scenario, modified cache entries are asynchronously written to the data source after a configured delay, whether after 10 seconds, 20 minutes, a day or even a week or longer. For Write-Behind caching, Coherence maintains a write-behind queue of the data that must be updated in the data source. When the application updates X in the cache, X is added to the write-behind queue (if it is not there; otherwise, it is replaced), and after the specified write-behind delay, Coherence calls the CacheStore to update the underlying data source with the latest state of X. Note that the write-behind delay is relative to the first of a series of modifications—in other words, the data in the data source never lags behind the cache by more than the write-behind delay.

The result is a "read-once and write at a configured interval" (that is, much less often) scenario. There are four main benefits to this type of architecture:

Figure 12-3 Write Behind Caching

The preceeding text describes this graphic.

12.5 Write-Behind Requirements


The most direct implication of write-behind caching is that database updates occur outside of the cache transaction; that is, the cache transaction (usually) completes before the database transaction(s) begins. This implies that the database transactions must never fail; if this cannot be guaranteed, then rollbacks must be accommodated.

As write-behind may re-order database updates, referential integrity constraints must allow out-of-order updates. Conceptually, using the database as ISAM-style storage (primary-key based access with a guarantee of no conflicting updates). If other applications share the database, this introduces a new challenge—there is no way to guarantee that a write-behind transaction does not conflict with an external update. This implies that write-behind conflicts must be handled heuristically or escalated for manual adjustment by a human operator.



12.6 Refresh-Ahead Caching

In the Refresh-Ahead scenario, Coherence allows a developer to configure a cache to automatically and asynchronously reload (refresh) any recently accessed cache entry from the cache loader before its expiration. The result is that after a frequently accessed entry has entered the cache, the application does not feel the impact of a read against a potentially slow cache store when the entry is reloaded due to expiration. The asynchronous refresh is only triggered when an object that is sufficiently close to its expiration time is accessed—if the object is accessed after its expiration time, Coherence performs a synchronous read from the cache store to refresh its value.

The refresh-ahead time is expressed as a percentage of the entry's expiration time. For example, assume that the expiration time for entries in the cache is set to 60 seconds and the refresh-ahead factor is set to 0.5. If the cached object is accessed after 60 seconds, Coherence performs a synchronous read from the cache store to refresh its value. However, if a request is performed for an entry that is more than 30 but less than 60 seconds old, the current value in the cache is returned and Coherence schedules an asynchronous reload from the cache store.



The XML code fragment in Example 12-1 configures a refresh-ahead factor of 0.5 and an expiration time of 20 seconds for entries in the local cache. If an entry is accessed within 10 seconds of its expiration time, it is scheduled for an asynchronous reload from the cache store.

Example 12-1 Specifying a Refresh-Ahead Factor




12.7 Selecting a Cache Strategy

This section compares and contrasts the benefits of several caching strategies.

12.7.1 Read-Through/Write-Through versus Cache-Aside

There are two common approaches to the cache-aside pattern in a clustered environment. One involves checking for a cache miss, then querying the database, populating the cache, and continuing application processing. This can result in multiple database visits if different application threads perform this processing at the same time. Alternatively, applications may perform double-checked locking (which works since the check is atomic for the cache entry). This, however, results in a substantial amount of overhead on a cache miss or a database update (a clustered lock, additional read, and clustered unlock - up to 10 additional network hops, or 6-8ms on a typical gigabit Ethernet connection, plus additional processing overhead and an increase in the "lock duration" for a cache entry).


12.7.2 Refresh-Ahead versus Read-Through

Refresh-ahead offers reduced latency compared to read-through, but only if the cache can accurately predict which cache items are likely to be needed in the future. With full accuracy in these predictions, refresh-ahead offers reduced latency and no added overhead. The higher the rate of misprediction, the greater the impact is on throughput (as more unnecessary requests are sent to the database) - potentially even having a negative impact on latency should the database start to fall behind on request processing.

12.7.3 Write-Behind versus Write-Through


12.8 Idempotency


Applications that have a requirement for write-behind caching but which must avoid write-combining (for example, for auditing reasons), should create a versioned cache key (for example, by combining the natural primary key with a sequence id).

12.9 Write-Through Limitations


12.10 Cache Queries

Cache queries only operate on data stored in the cache and do not trigger the CacheStore to load any missing (or potentially missing) data. Therefore, applications that query CacheStore-backed caches should ensure that all necessary data required for the queries has been pre-loaded. For efficiency, most bulk load operations should be done at application startup by streaming the data set directly from the database into the cache (batching blocks of data into the cache by using NamedCache.putAll(). The loader process must use a "Controllable Cachestore" pattern to disable circular updates back to the database. The CacheStore may be controlled by using an Invocation service (sending agents across the cluster to modify a local flag in each JVM) or by setting the value in a Replicated cache (a different cache service) and reading it in every CacheStore method invocation (minimal overhead compared to the typical database operation). A custom MBean can also be used, a simple task with Coherence's clustered JMX facilities.

12.11 Creating a CacheStore Implementation

CacheStore implementations are pluggable, and depending on the cache's usage of the data source you must implement one of two interfaces:

These interfaces are located in the package. The CacheLoader interface has two main methods: load(Object key) and loadAll(Collection keys), and the CacheStore interface adds the methods store(Object key, Object value), storeAll(Map mapEntries), erase(Object key), and eraseAll(Collection colKeys).

See Oracle Coherence Developer's Guide for an example implementation.

12.12 Plugging in a CacheStore Implementation

To plug in a CacheStore module, specify the CacheStore implementation class name within the distributed-scheme, backing-map-scheme, cachestore-scheme, or read-write-backing-map-scheme, cache configuration element.

The read-write-backing-map-scheme configures a This backing map is composed of two key elements: an internal map that actually caches the data (see internal-cache-scheme), and a CacheStore module that interacts with the database (see cachestore-scheme).

Example 12-2 illustrates a cache configuration that specifies a CacheStore module. The <init-params> element contains an ordered list of parameters that are passed into the CacheStore constructor. The {cache-name} configuration macro is used to pass the cache name into the CacheStore implementation, allowing it to be mapped to a database table. For a complete list of available macros, see Oracle Coherence Developer's Guide.

For more detailed information on configuring write-behind and refresh-ahead, see the read-write-backing-map-scheme, taking note of the write-batch-factor, refresh-ahead-factor, write-requeue-threshold, and rollback-cachestore-failures elements.

Example 12-2 Example Cachestore Module

<?xml version="1.0"?>

<cache-config xmlns:xsi=""





Thread Count: The use of a CacheStore module substantially increases the consumption of cache service threads (even the fastest database select is orders of magnitude slower than updating an in-memory structure). Consequently, the cache service thread count must to be increased (typically in the range 10-100). The most noticeable symptom of an insufficient thread pool is increased latency for cache requests (without corresponding behavior in the backing database).

12.13 Implementation Considerations

Please keep the following in mind when implementing a CacheStore.

12.13.1 Re-entrant Calls

The CacheStore implementation must not call back into the hosting cache service. This includes OR/M solutions that may internally reference Coherence cache services. Note that calling into another cache service instance is allowed, though care should be taken to avoid deeply nested calls (as each call "consumes" a cache service thread and could result in deadlock if a cache service thread pool is exhausted).

12.13.2 Cache Server Classpath

The classes for cache entries (also known as Value Objects, Data Transfer Objects, and so on) must be in the cache server classpath (as the cache server must serialize-deserialize cache entries to interact with the CacheStore module.

12.13.3 CacheStore Collection Operations

The CacheStore.storeAll method is most likely to be used if the cache is configured as write-behind and the <write-batch-factor> is configured. The CacheLoader.loadAll method is also used by Coherence. For similar reasons, its first use likely requires refresh-ahead to be enabled.

12.13.4 Connection Pools
