Share via


RequestOptions.SessionToken Property

Definition

Gets or sets the token for use with session consistency in the Azure Cosmos DB service.

public string SessionToken { get; set; }
member this.SessionToken : string with get, set
Public Property SessionToken As String

Property Value

The token for use with session consistency.

Examples

This example shows how you can retrieve the SessionToken from a ResourceResponse<TResource> and then use it on a different instance of DocumentClient within RequestOptions This example assumes that the each instance of the client is running from code within a different AppDomain, such as on different nodes in the case of multiple node web application

string sessionToken;
string docSelfLink;

using (DocumentClient client = new DocumentClient(new Uri(""), ""))
{
    ResourceResponse<Document> response = client.CreateDocumentAsync(collection.SelfLink, new { id = "an id", value = "some value" }).Result;
    sessionToken = response.SessionToken;
    Document created = response.Resource;
    docSelfLink = created.SelfLink;
}

using (DocumentClient client = new DocumentClient(new Uri(""), ""))
{
    ResourceResponse<Document> read = client.ReadDocumentAsync(docSelfLink, new RequestOptions { SessionToken = sessionToken }).Result;
}

Remarks

One of the ConsistencyLevel for Azure Cosmos DB is Session. In fact, this is the deault level applied to accounts.

When working with Session consistency, each new write request to Azure Cosmos DB is assigned a new SessionToken. The DocumentClient will use this token internally with each read/query request to ensure that the set consistency level is maintained.

In some scenarios you need to manage this Session yourself; Consider a web application with multiple nodes, each node will have its own instance of DocumentClient If you wanted these nodes to participate in the same session (to be able read your own writes consistently across web tiers) you would have to send the SessionToken from ResourceResponse<TResource> of the write action on one node to the client tier, using a cookie or some other mechanism, and have that token flow back to the web tier for subsequent reads. If you are using a round-robin load balancer which does not maintain session affinity between requests, such as the Azure Load Balancer, the read could potentially land on a different node to the write request, where the session was created.

If you do not flow the Azure Cosmos DB SessionToken across as described above you could end up with inconsistent read results for a period of time.

Applies to

See also