---
title: "What is a Session and How Does it Work"
description: "RavenDB sessions implement the Unit of Work pattern, tracking entity changes and batching all modifications into a single SaveChanges call."
url: "https://docs.ravendb.net/7.2/client-api/session/what-is-a-session-and-how-does-it-work"
version: "7.2"
language: "csharp"
---

# What is a Session and How Does it Work

> Client language: C#. Also available for [Java](https://docs.ravendb.net/7.2/client-api/session/what-is-a-session-and-how-does-it-work.java.md), [Python](https://docs.ravendb.net/7.2/client-api/session/what-is-a-session-and-how-does-it-work.python.md), [PHP](https://docs.ravendb.net/7.2/client-api/session/what-is-a-session-and-how-does-it-work.php.md), [Node.js](https://docs.ravendb.net/7.2/client-api/session/what-is-a-session-and-how-does-it-work.nodejs.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> - The **Session**, which is obtained from the [Document Store](https://docs.ravendb.net/7.2/client-api/what-is-a-document-store.md),  
>   is the primary interface your application will interact with.
>
> - In this article:
>   - [Session overview](#session-overview)
>   - [Unit of work pattern](#unit-of-work-pattern)
>     - [Tracking changes](#tracking-changes)
>     - [Create document example](#create-document-example)
>     - [Modify document example](#modify-document-example)
>   - [Identity map pattern](#identity-map-pattern)
>   - [Batching & Transactions](#batching--transactions)
>   - [Concurrency control](#concurrency-control)
>   - [Reducing server calls (best practices)](#reducing-server-calls-best-practices)
>     - [The N+1 problem](#the-select-n1-problem)
>     - [Large query results](#large-query-results)
>     - [Retrieving results on demand (Lazy)](#retrieving-results-on-demand-lazy)

## Session overview {#session-overview}

- **What is the session**:

  - The session (`ISession`/`IAsyncDocumentSession`) serves as a [Unit of Work](https://en.wikipedia.org/wiki/Unit_of_work) representing a single  
    **[Business Transaction](https://martinfowler.com/eaaCatalog/unitOfWork.html)** on a specific database (not to be confused with an [ACID transaction](https://docs.ravendb.net/7.2/client-api/faq/transaction-support.md)).

  - It is a container that allows you to query for documents and load, create, or update entities  
    while keeping track of changes.

  - Basic document CRUD actions and document Queries are available through the `Session`.  
    More advanced options are available using the `Advanced` Session operations.

- **Batching modifications**:  
  A business transaction usually involves multiple requests such as loading of documents or execution of queries.  
  Calling [SaveChanges()](https://docs.ravendb.net/7.2/client-api/session/saving-changes.md) indicates the completion of the client-side business logic.
  At this point, all modifications made within the session are batched and sent together in a **single HTTP request** to the server to be persisted as a single ACID transaction.

- **Tracking changes**:  
  Based on the [Unit of Work](https://martinfowler.com/eaaCatalog/unitOfWork.html) and the [Identity Map](https://martinfowler.com/eaaCatalog/identityMap.html) patterns,
  the session tracks all changes made to all entities that it has either loaded, stored, deleted, or queried for.  
  Only the modifications are sent to the server when *SaveChanges()* is called.

- **Client side object**:  
  The session is a pure client side object. Opening the session does Not establish any connection to a database,  
  and the session's state isn't reflected on the server side during its duration.

- **Configurability**:  
  Various aspects of the session are configurable.  
  For example, the number of server requests allowed per session is [configurable](https://docs.ravendb.net/7.2/client-api/session/configuration/how-to-change-maximum-number-of-requests-per-session.md) (default is 30).

- **The session and ORM Comparison**:  
  The RavenDB Client API is a native way to interact with a RavenDB database.  
  It is *not* an Object–relational mapping (ORM) tool. Although if you're familiar with NHibernate of Entity Framework ORMs you'll recognize that
  the session is equivalent of NHibernate's session and Entity Framework's DataContext which implement UoW pattern as well.

## Unit of work pattern {#unit-of-work-pattern}

### Tracking changes

- Using the Session, perform needed operations on your documents.  
  e.g. create a new document, modify an existing document, query for documents, etc.
- Any such operation '*loads*' the document as an entity to the Session,  
  and the entity is added to the **Session's entities map**.
- The Session **tracks all changes** made to all entities stored in its internal map.  
  You don't need to manually track the changes and decide what needs to be saved and what doesn't,  
  the Session will do it for you.
- Prior to saving, you can review the changes made if necessary. See:
  - [Get tracked entities](https://docs.ravendb.net/7.2/client-api/session/how-to/get-tracked-entities.md)
  - [Check for session changes](https://docs.ravendb.net/7.2/client-api/session/how-to/check-if-there-are-any-changes-on-a-session.md)
- All the tracked changes are combined & persisted in the database only when calling `SaveChanges()`.
- Entity tracking can be disabled if needed. See:
  - [Disable entity tracking](https://docs.ravendb.net/7.2/client-api/session/configuration/how-to-disable-tracking.md)
  - [Clear session](https://docs.ravendb.net/7.2/client-api/session/how-to/clear-a-session.md)
  - [Evict a single entity](https://docs.ravendb.net/7.2/client-api/session/how-to/evict-entity-from-a-session.md)

---

### Create document example

- The Client API, and the Session in particular, is designed to be as straightforward as possible.  
  Open the session, do some operations, and apply the changes to the RavenDB server.
- The following example shows how to create a new document in the database using the Session.

#### Sync

```csharp
// Obtain a Session from your Document Store
using (IDocumentSession session = store.OpenSession())
{
    // Create a new entity
    Company entity = new Company { Name = "CompanyName" };
    
    // Store the entity in the Session's internal map
    session.Store(entity);
    // From now on, any changes that will be made to the entity will be tracked by the Session.
    // However, the changes will be persisted to the server only when 'SaveChanges()' is called.
    
    session.SaveChanges();
    // At this point the entity is persisted to the database as a new document.
    // Since no database was specified when opening the Session, the Default Database is used.
}
```

#### Async

```csharp
// Obtain a Session from your Document Store
using (IAsyncDocumentSession asyncSession = store.OpenAsyncSession())
{
    // Create a new entity
    Company entity = new Company { Name = "CompanyName" };
    
    // Store the entity in the Session's internal map
    asyncSession.StoreAsync(entity);
    // From now on, any changes that will be made to the entity will be tracked by the Session.
    // However, the changes will be persisted to the server only when 'SaveChanges()' is called.
    
    asyncSession.SaveChangesAsync();
    // At this point the entity is persisted to the database as a new document.
    // Since no database was specified when opening the Session, the Default Database is used.
}
```

---

### Modify document example

- The following example modifies the content of an existing document.

#### Sync

```csharp
// Open a session
using (IDocumentSession session = store.OpenSession())
{
    // Load an existing document to the Session using its ID
    // The loaded entity will be added to the session's internal map
    Company entity = session.Load<Company>(companyId);
    
    // Edit the entity, the Session will track this change
    entity.Name = "NewCompanyName";

    session.SaveChanges();
    // At this point, the change made is persisted to the existing document in the database
}
```

#### Async

```csharp
// Open a Session
using (IAsyncDocumentSession asyncSession = store.OpenAsyncSession())
{
    // Load an existing document to the Session using its ID
    // The loaded entity will be added to the session's internal map
    Company entity = await asyncSession.LoadAsync<Company>(companyId);
    
    // Edit the entity, the Session will track this change
    entity.Name = "NewCompanyName";

    asyncSession.SaveChangesAsync();
    // At this point, the change made is persisted to the existing document in the database
}
```

## Identity map pattern {#identity-map-pattern}

- The session implements the [Identity Map Pattern](https://martinfowler.com/eaaCatalog/identityMap.html).
- The first `Load()` call goes to the server and fetches the document from the database.  
  The document is then stored as an entity in the Session's entities map.
- All subsequent `Load()` calls to the same document will simply retrieve the entity from the Session -  
  no additional calls to the server are made.

### Sync

```csharp
// A document is fetched from the server
Company entity1 = session.Load<Company>(companyId);

// Loading the same document will now retrieve its entity from the Session's map
Company entity2 = session.Load<Company>(companyId);

// This command will Not throw an exception
Assert.Same(entity1, entity2);
```

### Async

```csharp
// A document is fetched from the server
Company entity1 = await asyncSession.LoadAsync<Company>(companyId);

// Loading the same document will now retrieve its entity from the Session's map
Company entity2 = await asyncSession.LoadAsync<Company>(companyId);

// This command will Not throw an exception
Assert.Same(entity1, entity2);
```

- Note:  
  To override this behavior and force `Load()` to fetch the latest changes from the server see:
  [Refresh an entity](https://docs.ravendb.net/7.2/client-api/session/how-to/refresh-entity.md).

## Batching & Transactions {#batching-transactions}

> **Note**
>
> #### Batching
>
> - Remote calls to a server over the network are among the most expensive operations an application makes.  
>   The session optimizes this by batching all **write operations** it has tracked into the `SaveChanges()` call.
> - When calling *SaveChanges*, the session evaluates its state to identify all pending changes requiring persistence in the database.
>   These changes are then combined into a single batch that is sent to the server in a **single remote call** and executed as a single ACID transaction.

> **Note**
>
> #### Transactions
>
> - The client API does not provide transactional semantics over the entire session.  
>   The session **does not** represent a [transaction](https://docs.ravendb.net/7.2/client-api/faq/transaction-support.md) (nor a transaction scope) in terms of ACID transactions.
> - RavenDB provides transactions over individual requests, so each call made within the session's usage will be processed in a separate transaction on the server side.
>   This applies to both reads and writes.
>
> ##### Read transactions
>
> - Each call retrieving data from the database will generate a separate request. Multiple requests mean separate transactions.
> - The following options allow you to read *multiple* documents in a single request:
>   - Using overloads of the [Load()](https://docs.ravendb.net/7.2/client-api/session/loading-entities.md#load---multiple-entities) method that specify a collection of IDs or a prefix of ID.
>   - Using [Include](https://docs.ravendb.net/7.2/client-api/session/loading-entities.md#load-with-includes) to retrieve additional documents in a single request.
>   - A query that can return multiple documents is executed in a single request,  
>     hence it is processed in a single read transaction.
>
> ##### Write transactions
>
> - The batched operations that are sent in the `SaveChanges()` complete transactionally, as this call generates a single request to the database.
>   In other words, either all changes are saved as a **Single Atomic Transaction** or none of them are.  
>   So once *SaveChanges* returns successfully, it is guaranteed that all changes are persisted to the database.
> - *SaveChanges* is the only time when the RavenDB Client API sends updates to the server from the Session,  
>   resulting in a reduced number of network calls.
> - To execute an operation that both loads and updates a document within the same write transaction, use the patching feature.
>   This can be done either with the usage of a [JavaScript patch](https://docs.ravendb.net/7.2/documents/patching-documents/patch-a-single-document/api-overview.md) syntax or [JSON Patch](https://docs.ravendb.net/7.2/documents/patching-documents/patch-a-single-document/json-patch.md) syntax.

> **Note**
>
> #### Transaction mode
>
> - The session's transaction mode can be set to either:
>   - **Single-Node** - transaction is executed on a specific node and then replicated
>   - **Cluster-Wide** - transaction is registered for execution on all nodes in an atomic fashion
>   - > **Warning**
>     >
>     > The phrase "session's transaction mode" refers to the type of transaction that will be executed on the server-side when `SaveChanges()` is called.
>     > As mentioned earlier, the session itself does not represent an ACID transaction.
>   - Learn more about these modes in [Cluster-wide vs. Single-node](https://docs.ravendb.net/7.2/client-api/session/cluster-transaction/overview.md#cluster-wide-transaction-vs-single-node-transaction) transactions.

> **Info:** Transactions in RavenDB {#transactions-in-ravendb}
>
> For a detailed description of transactions in RavenDB please refer to the [Transaction support in RavenDB](https://docs.ravendb.net/7.2/client-api/faq/transaction-support.md) article.

## Concurrency control {#concurrency-control}

A session may load documents, modify them in memory, and save the changes back to the database.  
Since loading/querying and saving occur in **separate requests**, other sessions or clients may modify the same documents during this time -
between when your session loads the document and when `SaveChanges()` is called.

By default, sessions do not detect these conflicts and use a "Last Write Wins" strategy,
where the most recent `SaveChanges()` call overwrites any prior changes made by other sessions.

If your application requires detecting and preventing conflicting updates rather than silently overwriting them,
you can enable **optimistic concurrency**, which ensures documents have not been modified by other sessions since they were loaded into your session.

See [Enable optimistic concurrency](https://docs.ravendb.net/7.2/client-api/session/configuration/how-to-enable-optimistic-concurrency.md) for detailed behavior and configuration options.

## Reducing server calls (best practices) {#reducing-server-calls-best-practices}

Reducing server calls (best practices) for:

#### The select N+1 problem

- The Select N+1 problem is common
  with all ORMs and ORM-like APIs.  
  It results in an excessive number of remote calls to the server, which makes a query very expensive.
- Make use of RavenDB's `include()` method to include related documents and avoid this issue.  
  See: [Document relationships](https://docs.ravendb.net/7.2/client-api/how-to/handle-document-relationships.md)

#### Large query results

- When query results are large and you don't want the overhead of keeping all results in memory,  
  then you can [Stream query results](https://docs.ravendb.net/7.2/querying/stream-query-results.md).  
  A single server call is executed and the client can handle the results one by one.
- [Paging](https://docs.ravendb.net/7.2/indexes/querying/paging.md) also avoids getting all query results at one time,  
  however, multiple server calls are generated - one per page retrieved.

#### Retrieving results on demand (Lazy)

- Query calls to the server can be delayed and executed on-demand as needed using `Lazily()`
- See [Perform queries lazily](https://docs.ravendb.net/7.2/client-api/session/querying/how-to-perform-queries-lazily.md)

## See also

- [Open a Session](https://docs.ravendb.net/7.2/client-api/session/opening-a-session.md)
- [Storing Entities](https://docs.ravendb.net/7.2/client-api/session/storing-entities.md)
- [Loading Entities](https://docs.ravendb.net/7.2/client-api/session/loading-entities.md)
- [Saving Changes](https://docs.ravendb.net/7.2/client-api/session/saving-changes.md)
- [Query Overview](https://docs.ravendb.net/7.2/querying/overview.md)
- [Querying an Index](https://docs.ravendb.net/7.2/indexes/querying/query-index.md)
- [What is a Document Store](https://docs.ravendb.net/7.2/client-api/what-is-a-document-store.md)
- [Optimistic Concurrency](https://docs.ravendb.net/7.2/client-api/session/configuration/how-to-enable-optimistic-concurrency.md)
- [Transaction Support](https://docs.ravendb.net/7.2/client-api/faq/transaction-support.md)
