---
title: "Load balance behavior"
url: "https://docs.ravendb.net/6.2/client-api/configuration/load-balance/load-balance-behavior"
version: "6.2"
language: "python"
---

# Load balance behavior

> Client language: Python. Also available for [C#](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/load-balance-behavior.md), [PHP](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/load-balance-behavior.php.md), [Node.js](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/load-balance-behavior.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 `loadBalanceBehavior` configuration allows you to specify which sessions should
>   communicate with the same node.
>
> - Sessions that are assigned the **same context** will have all their *Read* & *Write*
>   requests routed to the **same node**. Gain load balancing by assigning **different contexts**
>   to **different sessions**.
>
> - In this page:
>   - [LoadBalanceBehavior options](#loadbalancebehavior-options)
>   - [Initialize LoadBalanceBehavior on the client](#initialize-loadbalancebehavior-on-the-client)
>   - [Set LoadBalanceBehavior on the server:](#set-loadbalancebehavior-on-the-server)
>     - [By operation](#set-loadbalancebehavior-on-the-server---by-operation)
>     - [From Studio](#set-loadbalancebehavior-on-the-server---from-studio)
>   - [When to use](#when-to-use)

## LoadBalanceBehavior options

### `None` (default option)

- Requests will be handled based on the `ReadBalanceBehavior` configuration.  
  See the conditional flow described in [Client logic for choosing a node](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/overview.md#client-logic-for-choosing-a-node).
  - ***Read*** requests:  
    The client will calculate the target node from the configured [ReadBalanceBehavior Option](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/read-balance-behavior.python.md#readbalancebehavior-options).
  - ***Write*** requests:  
    Will be sent to the [preferred node](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/overview.md#the-preferred-node).  
    The data will then be replicated to all the other nodes in the database group.

### `UseSessionContext`

- **Load-balance**

  - When this option is enabled, the client will calculate the target node from the session-id.  
    The session-id is hashed from a **context string** and an optional **seed** given by the user.  
    The context string together with the seed are referred to as **"The session context"**.

  - Per session, the client will select a node from the topology list based on this session-context.  
    So sessions that use the **same** context will target the **same** node.

  - All ***Read & Write*** requests made on the session (i.e a query or a load request, etc.)  
    will address this calculated node.  
    *Read & Write* requests that are made on the store (i.e. executing an [operation](https://docs.ravendb.net/6.2/client-api/operations/what-are-operations.python.md))  
    will go to the preferred node.

  - All *Write* requests will be replicated to all the other nodes in the database group as usual.

- **Failover**

  - In case of a failure, the client will try to access the next node from the topology nodes list.

## Initialize LoadBalanceBehavior on the client

- The `LoadBalanceBehavior` convention can be set **on the client** when initializing the Document Store.  
  This will set the load balance behavior for the default database that is set on the store.

- This setting can be **overriden** by setting 'LoadBalanceBehavior' on the server, see [below](#set-loadbalancebehavior-on-the-server).

**Initialize conventions**:

```python
# Initialize 'LoadBalanceBehavior' on the client:
document_store = DocumentStore(
  urls=["ServerURL_1", "ServerURL_2", "..."],
  database="DefaultDB",
)
conventions = DocumentConventions()

# Enable the session-context feature
# If this is not enabled then a context string set in a session will be ignored
conventions.load_balance_behavior = LoadBalanceBehavior.USE_SESSION_CONTEXT

# Assign a method that sets the default context string
# This method will be called to provide a default context string for sessions that do not set one explicitly
# A sample GetDefaultContext method is defined below
conventions.load_balancer_per_session_context_selector = get_default_context

# Set a seed
# The seed is 0 by default, provide any number to override
conventions.load_balancer_context_seed = 5

document_store.conventions = conventions
document_store.initialize()
```

```python
# A customized method for getting a default context string

default_context_string = contextvars.ContextVar("default_context_string", default=None)

def get_default_context(db_name: str) -> str:
  # Get the string set by the web application elsewhere.
  ctx = default_context_string.get()
  if ctx is None:
      # return a safe default
      return db_name

  # Return the context set elsewhere or default to the db_name
  return ctx
```

**Session usage**:

```python
# Open a session that will use the DEFAULT store values:
with document_store.open_session() as session:
  # For all Read & Write requests made in this session
  # node to access is calculated from string & seed values defined on the store
  employee = session.load("employees/1-A", Employee)
```

```python
# Open a session that will use a UNIQUE context string:
with document_store.open_session() as session:
  # Call 'context' to assign a dedicated context string for this session.
  # For example: "team/9-A", representing the team that the employees loaded in this session belong to.
  session.advanced.session_info.context = "team/9-A"

  # For all Read & Write requests made in this session, including the following load calls,
  # a node to access is calculated from the unique string & the seed defined on the store
  employee1 = session.load("employees/1-A", Employee)
  employee2 = session.load("employees/3-A", Employee)
```

## Set LoadBalanceBehavior on the server

> **Note**
>
> **Note**:
>
> - Setting the load balance behavior on the server, either by an **Operation** or from the **Studio**,  
>   only 'enables the feature' and sets the seed.
>
> - For the feature to be in effect, you still need to define the context string itself:
>   - either per session, call `session.advanced.session_info.context`
>   - or, on the document store, set a default value for - `load_balancer_per_session_context_selector`

#### Set LoadBalanceBehavior on the server - by operation:

- The `LoadBalanceBehavior` configuration can be set **on the server** by sending an [operation](https://docs.ravendb.net/6.2/client-api/operations/what-are-operations.python.md).

- The operation can modify the default database only, or all databases - see examples below.

- Once configuration on the server has changed, the running client will get updated with the new settings.  
  See [keeping client up-to-date](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/overview.md#keeping-the-client-topology-up-to-date).

##### Operation\_For\_Default\_Database

```python
# Setting 'LoadBalanceBehavior' on the server by sending an operation:
with document_store:
  # Define the client configuration to put on the server
  configuration_to_save = ClientConfiguration()
  # Enable the session-context feature
  # If this is not enabled then a context string set in a session will be ignored
  configuration_to_save.load_balance_behavior = LoadBalanceBehavior.USE_SESSION_CONTEXT

  # Set a seed
  # The seed is 0 by default, provide any number to override
  load_balancer_context_seed = 10

  # NOTE:
  # The session's context string is Not set on the server
  # You still need to set it on the client:
  # * either as a convention on the document store
  # * or pass it to the 'context' method on the session

  # Configuration will be in effect when Disabled is set to false
  configuration_to_save.disabled = False

  # Define the put configuration operation for the DEFAULT database
  put_configuration_op = PutClientConfigurationOperation(configuration_to_save)

  # Execute the operation by passing it to maintenance.send
  document_store.maintenance.send(put_configuration_op)

  #  After the operation has executed:
  #  all Read & Write requests, per session, will address the node calculated from:
  #    * the seed set on the server &
  #    * the session's context string set on the client
```

##### Operation\_For\_All\_Databases

```python
with document_store:
  # Define the client configuration to put on the server
  configuration_to_save = ClientConfiguration()
  # Enable the session-context feature
  # If this is not enabled then a context string set in a session will be ignored
  configuration_to_save.load_balance_behavior = LoadBalanceBehavior.USE_SESSION_CONTEXT

  # Set a seed
  # The seed is 0 by default, provide any number to override
  load_balancer_context_seed = 10

  # NOTE:
  # The session's context string is Not set on the server
  # You still need to set it on the client:
  # * either as a convention on the document store
  # * or pass it to the 'context' method on the session

  # Configuration will be in effect when Disabled is set to false
  configuration_to_save.disabled = False

  # Define the put configuration operation for ALL databases
  put_configuration_op = PutServerWideClientConfigurationOperation(configuration_to_save)

  # Execute the operation by passing it to maintenance.server.send
  document_store.maintenance.server.send(put_configuration_op)

  #  After the operation has executed:
  #  all Read & Write requests, per session, will address the node calculated from:
  #    * the seed set on the server &
  #    * the session's context string set on the client
```

#### Set LoadBalanceBehavior on the server - from Studio:

- The `LoadBalanceBehavior` configuration can be set from the Studio's [Client Configuration view](https://docs.ravendb.net/6.2/studio/database/settings/client-configuration-per-database.md).  
  Setting it from the Studio will set this configuration directly **on the server**.

- Once configuration on the server has changed, the running client will get updated with the new settings.  
  See [keeping client up-to-date](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/overview.md#keeping-the-client-topology-up-to-date).

## When to use

- Distributing *Read and Write* requests among cluster nodes can be beneficial
  when a set of sessions consistently handles a specific group of documents or related data.
  By setting a context string per session, you can ensure that similar sessions
  (e.g., sessions for a specific user, tenant, or team) are routed to the same node,
  while other sessions are routed to different nodes - achieving effective load distribution.

- In scenarios where [optimistic concurrency](https://docs.ravendb.net/6.2/client-api/session/configuration/how-to-enable-optimistic-concurrency.python.md) is enabled,
  routing sessions for the same entity to the same node can help reduce *Write* conflicts,
  since concurrent updates tend to be coordinated on the same node.
  The node handling the write is also more likely to have the latest version of the document,
  which helps avoid cross-node conflicts.

- Once load balancing is configured to use the session context,
  if many sessions still end up being routed to the same node,
  you can introduce additional distribution by adjusting the context seed on the store.

## See also

- [What are operations](https://docs.ravendb.net/6.2/client-api/operations/what-are-operations.python.md)
- [Load balancing client requests - overview](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/overview.md)
- [Read balance behavior](https://docs.ravendb.net/6.2/client-api/configuration/load-balance/read-balance-behavior.python.md)
- [Conventions](https://docs.ravendb.net/6.2/client-api/configuration/conventions.md)
- [Requests Configuration in Studio](https://docs.ravendb.net/6.2/studio/server/client-configuration.md)
- [Requests Configuration per Database](https://docs.ravendb.net/6.2/studio/database/settings/client-configuration-per-database.md)
- [Database-group-topology](https://docs.ravendb.net/6.2/studio/database/settings/manage-database-group.md#database-group-topology---view)
