RavenDB handles the replication in an asynchronous manner. Saving an entity on a server will cause that an async task will be run which will replicate the newly added document to configured destination servers.
From the code perspective it means that when you call
session.SaveChanges() document is stored on the primary node and it does not wait for the replication to the other ones.
In order to handle write assurance, the client API allows you to wait until replication is completed. Here is the code:
await session.StoreAsync(user); await session.SaveChangesAsync(); var userEtag = session.Advanced.GetEtagFor(user); var replicas = await ((DocumentStore)store). Replication.WaitAsync(etag: userEtag, timeout: TimeSpan.FromMinutes(1), replicas: 1);
The Raven client will ping all of the replicas, waiting to see that replication has matched or exceeded the ETag that we just wrote.
You can specify the number of replicas that are required to consider the document write as "safe". Optionally you can also provide a timeout and if the nodes aren’t reachable,
you will get an error about that. As the result the
WaitAsync method returns the number of nodes that caught up to the specified ETag.
You can also use parameterless version of the
await ((DocumentStore) store).Replication.WaitAsync();
Then the default parameters that will be used:
- etag - last written ETag in the document store (
- timeout - no timeout,
- database - default database of the document store,
- replicas - 2 destination servers.