Aggressive Caching

Cache options

The RavenDB client provides a caching feature out of the box. You can determine whether Raven should cache a request or not for a particular URL. By default all requests are cached:

documentStore.Conventions.ShouldCacheRequest = url => true;

The second cache option is the number of cached requests. The default value is 2048:

documentStore.MaxNumberOfCachedRequests = 2048;

The client utilizes the notion of the 304 Not Modified RavenDB server's response and will serve the data from the cache if available.

Aggressive mode

The aggressive caching feature goes even further. If you enable it RavenDB can do not even ask the server and simply return the reply directly from a local cache if it is there, when means that you will get it very fast. By default the client subscribes to server notifications and by taking advantage of them it is able to invalidate documents in the cache when they have been changed. It makes that the client knows when it needs to ask the server and when can serve the response from the cache. However you need to be aware that it is still possible to get stale data because of the time needed to receive the notification from the server.

You can also disable the mechanism of changes tracking by using the following convention:

documentStore.Conventions.ShouldAggressiveCacheTrackChanges = false;

Note that it makes that it becomes more likely that you might get stale results.

To activate the aggressive caching mode use the code:

using (session.Advanced.DocumentStore.AggressivelyCacheFor(TimeSpan.FromMinutes(5)))
	var user = session.Load<User>("users/1");

Now, if there is a value in the cache for users/1 that is at most 5 minutes old and we haven't get any change notification about it, we can directly use that. The same mechanism works on queries as well:

using (session.Advanced.DocumentStore.AggressivelyCacheFor(TimeSpan.FromMinutes(5)))
	var users = session.Query<User>().ToList();

The usage of the notification system means that you can set an aggressive cache duration to longer period. The document store exposes the method:

using  (session.Advanced.DocumentStore.AggressivelyCache()) { }

which is equivalent to:

using (session.Advanced.DocumentStore.AggressivelyCacheFor(TimeSpan.FromDays(1))) { }

Saving changes

An another aggressive cache specific convention is:

documentStore.Conventions.ShouldSaveChangesForceAggressiveCacheCheck = true;

This option set to true (default) forces the client to check the cache with the server after calling SaveChanges() (when you know that things have been changed - by you).


The Silverlight version of the RavenDB client doesn't have own implementation of the aggressive caching because Silverlight already has the built-in and actively working cache.