---
title: "Conventions"
description: "Configure RavenDB client conventions to customize serialization, identity generation, load balancing, request handling, and cluster behavior."
url: "https://docs.ravendb.net/7.2/client-api/configuration/conventions"
version: "7.2"
language: "csharp"
---

# Conventions

> Client language: C#. Also available for [Node.js](https://docs.ravendb.net/7.2/client-api/configuration/conventions.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**
>
> - **Conventions** in RavenDB are customizable settings that users can configure to tailor client behaviors  
>   according to their preferences.
>
> - In this article:
>   - [How to set conventions](#how-to-set-conventions)
>   - [Conventions](#conventions)  
>     [AddIdFieldToDynamicObjects](#addidfieldtodynamicobjects)  
>     [AggressiveCache.Duration](#aggressivecacheduration)  
>     [AggressiveCache.Mode](#aggressivecachemode)  
>     [AsyncDocumentIdGenerator](#asyncdocumentidgenerator)  
>     [CreateHttpClient](#createhttpclient)  
>     [DisableAtomicDocumentWritesInClusterWideTransaction](#disableatomicdocumentwritesinclusterwidetransaction)  
>     [DisableTcpCompression](#disabletcpcompression)  
>     [DisableTopologyCache](#disabletopologycache)  
>     [DisableTopologyUpdates](#disabletopologyupdates)  
>     [DisposeCertificate](#disposecertificate)  
>     [FindClrType](#findclrtype)  
>     [FindClrTypeName](#findclrtypename)  
>     [FindClrTypeNameForDynamic](#findclrtypenamefordynamic)  
>     [FindCollectionName](#findcollectionname)  
>     [FindCollectionNameForDynamic](#findcollectionnamefordynamic)  
>     [FindIdentityProperty](#findidentityproperty)  
>     [FindIdentityPropertyNameFromCollectionName](#findidentitypropertynamefromcollectionname)  
>     [FindProjectedPropertyNameForIndex](#findprojectedpropertynameforindex)  
>     [FindPropertyNameForDynamicIndex](#findpropertynamefordynamicindex)  
>     [FindPropertyNameForIndex](#findpropertynameforindex)  
>     [FirstBroadcastAttemptTimeout](#firstbroadcastattempttimeout)  
>     [GlobalHttpClientTimeout](#globalhttpclienttimeout)  
>     [HttpClientType](#httpclienttype)  
>     [HttpPooledConnectionIdleTimeout](#httppooledconnectionidletimeout)  
>     [HttpPooledConnectionLifetime](#httppooledconnectionlifetime)  
>     [HttpVersion](#httpversion)  
>     [IdentityPartsSeparator](#identitypartsseparator)  
>     [LoadBalanceBehavior](#loadbalancebehavior)  
>     [LoadBalancerContextSeed](#loadbalancebehavior)  
>     [LoadBalancerPerSessionContextSelector](#loadbalancebehavior)  
>     [MaxHttpCacheSize](#maxhttpcachesize)  
>     [MaxNumberOfRequestsPerSession](#maxnumberofrequestspersession)  
>     [Modify serialization of property name](#modify-serialization-of-property-name)  
>     [OperationStatusFetchMode](#operationstatusfetchmode)  
>     [OptimisticConcurrencyMode](#optimisticconcurrencymode)  
>     [PreserveDocumentPropertiesNotFoundOnModel](#preservedocumentpropertiesnotfoundonmodel)  
>     [ReadBalanceBehavior](#readbalancebehavior)  
>     [RequestTimeout](#requesttimeout)  
>     [ResolveTypeFromClrTypeName](#resolvetypefromclrtypename)  
>     [SaveEnumsAsIntegers](#saveenumsasintegers)  
>     [SaveEnumsAsIntegersForPatching](#saveenumsasintegersforpatching)  
>     [SecondBroadcastAttemptTimeout](#secondbroadcastattempttimeout)  
>     [SendApplicationIdentifier](#sendapplicationidentifier)  
>     [SessionPatchBehavior](#sessionpatchbehavior)  
>     [ShouldIgnoreEntityChanges](#shouldignoreentitychanges)  
>     [TopologyCacheLocation](#topologycachelocation)  
>     [TransformTypeCollectionNameToDocumentIdPrefix](#transformtypecollectionnametodocumentidprefix)  
>     [UseHttpCompression](#usehttpcompression)  
>     [UseHttpDecompression](#usehttpdecompression)  
>     [HttpCompressionAlgorithm](#httpcompressionalgorithm)  
>     [WaitForIndexesAfterSaveChangesTimeout](#waitforindexesaftersavechangestimeout)  
>     [WaitForNonStaleResultsTimeout](#waitfornonstaleresultstimeout)  
>     [WaitForReplicationAfterSaveChangesTimeout](#waitforreplicationaftersavechangestimeout)

## How to set conventions {#how-to-set-conventions}

- Access the conventions via the `Conventions` property of the `DocumentStore` object.

- The conventions set on a Document Store will apply to ALL [sessions](https://docs.ravendb.net/7.2/client-api/session/what-is-a-session-and-how-does-it-work.md)
  and [operations](https://docs.ravendb.net/7.2/client-api/operations/what-are-operations.md) associated with that store.

- Customizing the conventions can only be set **before** calling `DocumentStore.Initialize()`.  
  Trying to do so after calling *Initialize()* will throw an exception.

```csharp
using (var store = new DocumentStore()
{
    Conventions =
    {
        // Set conventions HERE, e.g.:
        MaxNumberOfRequestsPerSession = 50,
        AddIdFieldToDynamicObjects = false
        // ...
    }
}.Initialize())
{
    // * Here you can interact with the RavenDB store:
    //   open sessions, create or query for documents, perform operations, etc.
    
    // * Conventions CANNOT be set here after calling Initialize()
}
```

## Conventions {#conventions}

### AddIdFieldToDynamicObjects

- Use the `AddIdFieldToDynamicObjects` convention to determine whether an `Id` field is automatically added  
  to [dynamic objects](https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interop/using-type-dynamic) when [storing new entities](https://docs.ravendb.net/7.2/client-api/session/storing-entities.md) via the session.

- DEFAULT: `true`

```csharp
// Syntax:
public bool AddIdFieldToDynamicObjects { get; set; }
```

### AggressiveCache.Duration

- Use the `AggressiveCache.Duration` convention to define the [aggressive cache](https://docs.ravendb.net/7.2/client-api/how-to/setup-aggressive-caching.md) duration period.

- DEFAULT: `1 day`

```csharp
// Syntax:
public TimeSpan Duration { get; set; }
```

### AggressiveCache.Mode

- Use the `AggressiveCache.Mode` convention to define the [aggressive cache](https://docs.ravendb.net/7.2/client-api/how-to/setup-aggressive-caching.md) mode.  
  (`AggressiveCacheMode.TrackChanges` or `AggressiveCacheMode.DoNotTrackChanges`)

- DEFAULT: `AggressiveCacheMode.TrackChanges`

```csharp
// Syntax:
public AggressiveCacheMode Mode { get; set; }
```

### AsyncDocumentIdGenerator

- Use the `AsyncDocumentIdGenerator` convention to define the document ID generator method
  used when storing a document without explicitly specifying its `Id`.

- You can override this global ID generator for specific object types using the [RegisterAsyncIdConvention](https://docs.ravendb.net/7.2/client-api/configuration/identifier-generation/type-specific.md) convention.

- DEFAULT:  
  The default document ID generator is the `GenerateDocumentIdAsync` method, which is part of the `HiLoIdGenerator` object within the *DocumentStore*.
  This method implements the [HiLo algorithm](https://docs.ravendb.net/7.2/client-api/document-identifiers/hilo-algorithm.md) to ensure efficient ID generation when storing a document without explicitly specifying its `Id`.

```csharp
// Customize ID generation for all collections
AsyncDocumentIdGenerator = (database, obj) =>
{
    var objectType = obj.GetType().Name;  // e.g., Person, Order, etc.
    var timestamp = DateTime.UtcNow.Ticks; // Get the current timestamp

    // Format the ID as {ObjectType}/{Ticks}
    var id = $"{objectType}/{timestamp}";

    return Task.FromResult(id);
}
```

```csharp
// Syntax:
public Func<string, object, Task<string>> AsyncDocumentIdGenerator { get; set; }
```

### CreateHttpClient

- Use the `CreateHttpClient` convention to modify the HTTP client your client application uses.

- For example, implementing your own HTTP client can be useful when you'd like your clients to provide the server with tracing info.

- If you override the default `CreateHttpClient` convention we advise that you also set the HTTP client type
  correctly using the [HttpClientType](#httpclienttype) convention.

```csharp
CreateHttpClient = handler =>
{
    // Your HTTP client code here, e.g.:
    var httpClient = new MyHttpClient(new HttpClientXRayTracingHandler(new HttpClientHandler()));
    return httpClient;
}
```

```csharp
// Syntax:
public Func<HttpClientHandler, HttpClient> CreateHttpClient { get; set; }
```

### DisableAtomicDocumentWritesInClusterWideTransaction

- EXPERT ONLY:  
  Use the `DisableAtomicDocumentWritesInClusterWideTransaction` convention to disable automatic  
  atomic writes with cluster write transactions.

- When set to `true`, will only consider explicitly-added compare exchange values to validate cluster-wide transactions.

- DEFAULT: `false`

```csharp
// Syntax:
public bool? DisableAtomicDocumentWritesInClusterWideTransaction { get; set; }
```

### DisableTcpCompression

- When setting the `DisableTcpCompression` convention to `true`, TCP data will not be compressed.

- DEFAULT: `false`

```csharp
// Syntax:
public bool DisableTcpCompression { get; set; }
```

### DisableTopologyCache

- By default, the client caches the cluster's topology in `*.raven-cluster-topology` files on disk.  
  When all servers provided in the `DocumentStore.Urls` property are down or unavailable,
  the client will load the topology from the latest file and try to connect to nodes that are not listed in the URL property.

- This behavior can be disabled when setting the `DisableTopologyCache` convention to `true`.  
  In such a case:

  - The client will not load the topology from the cache upon failing to connect to a server.
  - Even if the client is configured to [receive topology updates](#disabletopologyupdates) from the server,
    no topology files will be saved on disk, thus preventing the accumulation of these files.

- DEFAULT: `false`

```csharp
// Syntax:
public bool DisableTopologyCache { get; set; }
```

### DisableTopologyUpdates

- When setting the `DisableTopologyUpdates` convention to `true`,  
  no database topology updates will be sent from the server to the client (e.g. adding or removing a node).

- DEFAULT: `false`

```csharp
// Syntax:
public bool DisableTopologyUpdates { get; set; }
```

### DisposeCertificate

- When setting the `DisposeCertificate` convention to `true`,  
  the `DocumentStore.Certificate` will be disposed of during DocumentStore disposal.

- DEFAULT: `true`

```csharp
// Syntax:
public bool DisposeCertificate { get; set; }
```

### FindClrType

- Use the `FindClrType` convention to define a function that finds the CLR type of a document.

- DEFAULT:  
  The CLR type is retrieved from the `Raven-Clr-Type` property under the `@metadata` key in the document.

```csharp
// The default implementation is:
FindClrType = (_, doc) =>
{
    if (doc.TryGet(Constants.Documents.Metadata.Key, out BlittableJsonReaderObject metadata) &&
        metadata.TryGet(Constants.Documents.Metadata.RavenClrType, out string clrType))
        return clrType;

    return null;
}
```

```csharp
// Syntax:
public Func<string, BlittableJsonReaderObject, string> FindClrType { get; set; }
```

### FindClrTypeName

- Use the `FindClrTypeName` convention to define a function that returns the CLR type name from a given type.

- DEFAULT: Return the entity's full name, including the assembly name.

```csharp
// Syntax:
public Func<Type, string> FindClrTypeName { get; set; }
```

### FindClrTypeNameForDynamic

- Use the `FindClrTypeNameForDynamic` convention to define a function that returns the CLR type name  
  from a dynamic entity.

- DEFAULT: The dynamic entity type is returned.

```csharp
// The dynamic entity's type is returned by default
FindClrTypeNameForDynamic = dynamicEntity => dynamicEntity.GetType()
```

```csharp
// Syntax:
public Func<dynamic, string> FindClrTypeNameForDynamic { get; set; }
```

### FindCollectionName

- Use the `FindCollectionName` convention to define a function that will customize
  the collection name from a given type.

- DEFAULT: The collection name will be the plural form of the type name.

```csharp
// Here the collection name will be the type name separated by dashes
FindCollectionName = type => String.Join("-", type.Name.ToCharArray())
```

```csharp
// Syntax:
public Func<Type, string> FindCollectionName { get; set; }
```

### FindCollectionNameForDynamic

- Use the `FindCollectionNameForDynamic` convention to define a function that will customize the  
  collection name from a dynamic type.

- DEFAULT: The collection name will be the entity's type.

```csharp
// Here the collection name will be some property of the dynamic entity
FindCollectionNameForDynamic = dynamicEntity => dynamicEntity.SomeProperty
```

```csharp
// Syntax:
public Func<dynamic, string> FindCollectionNameForDynamic { get; set; }
```

### FindIdentityProperty

- Use the `FindIdentityProperty` convention to define a function that finds the specified ID property  
  in the entity.

- DEFAULT: The entity's `Id` property serves as the ID property.

```csharp
// If there exists a property with name "CustomizedId" then it will be the entity's ID property 
FindIdentityProperty = memberInfo => memberInfo.Name == "CustomizedId"
```

```csharp
// Syntax:
public Func<MemberInfo, bool> FindIdentityProperty { get; set; }
```

### FindIdentityPropertyNameFromCollectionName

- Use the `FindIdentityPropertyNameFromCollectionName` convention to define a function that customizes
  the entity's ID property from the collection name.

- DEFAULT: Will use the `Id` property.

```csharp
// Will use property "CustomizedId" as the ID property
FindIdentityPropertyNameFromCollectionName = collectionName => "CustomizedId"
```

```csharp
// Syntax:
public Func<string, string> FindIdentityPropertyNameFromCollectionName { get; set; }
```

### FindProjectedPropertyNameForIndex

- Use the `FindProjectedPropertyNameForIndex` convention to define a function that customizes the  
  **projected** field names that will be used in the RQL generated by the client and sent to the server when querying a static index.

- This can be useful when projecting **nested properties** that are not [Stored in the index](https://docs.ravendb.net/7.2/indexes/storing-data-in-index.md).

- The function receives the following input:  
  the index type, the index name, the current path, and the property path that is used in the query.

- DEFAULT: `null`  
  When `FindProjectedPropertyNameForIndex` is set to `null` (or returns `null`),  
  the [FindPropertyNameForIndex](#findpropertynameforindex) convention is used instead.

**Example**:  
Consider the following index, which indexes the nested `School.Id` property from *Student* documents:

#### Index

```csharp
public class Students_BySchoolId : AbstractIndexCreationTask<Student>
{
    public class IndexEntry
    {
        public string Name { get; set; }
        public string SchoolId { get; set; }
    }
    
    public Students_BySchoolId()
    {
        Map = students => from student in students
            select new IndexEntry
            {
                Name = student.StudentName,
                SchoolId = student.School.Id // index nested property
            };
    }
}
```

#### Class

```csharp
public class Student
{
    public string StudentName { get; set; }
    public School School { get; set; }
    // ... other student properties
}

public class School
{
    public string SchoolName { get; set; }
    public string Id { get; set; }
}
```

When querying the index and projecting fields from the matching *Student* documents,  
if the `FindProjectedPropertyNameForIndex` convention is Not set,
the client will use the [FindPropertyNameForIndex](#findpropertynameforindex) convention instead when constructing the RQL sent to the server.

This results in the following RQL query:  
(Note that while the high-level query uses `.Select(student => student.School.Id)`,  
the RQL sent to the server contains `School_Id`)

#### Query

```csharp
// Query the index
var query = session.Query<Students_BySchoolId.IndexEntry, Students_BySchoolId>()
    .Where(x => x.Name == "someStudentName")
    .OfType<Student>()
    // Project only the School.Id property from the Student document in the results
    .Select(student => student.School.Id)
    .ToList();
```

#### RQL

```sql
from index 'Students/BySchoolId'
where Name == "someStudentName"
select School_Id
// Since the FindProjectedPropertyNameForIndex convention was not yet defined,
// the 'School_Id' property name was generated using the FindPropertyNameForIndex convention.
// ('School.Id' was converted to 'School_Id')
```

The RQL generated by the above query projects the `School_Id` field, so the server first attempts to fetch this property from the [Stored index fields](https://docs.ravendb.net/7.2/indexes/storing-data-in-index.md)
(this is the default behavior, learn more in [Projection behavior with a static-index](https://docs.ravendb.net/7.2/indexes/querying/projections.md#projection-behavior-with-a-static-index)).

However, because this property is Not stored in the index, the server then tries to retrieve it from the *Student* document instead.
But the document does not contain a flat `School_Id` field — it contains the nested property `School.Id`,  
and so no results are returned for the `School_Id` field.

To resolve this issue,
set the `FindProjectedPropertyNameForIndex` convention to return the nested property name that the client should use when constructing the RQL query sent to the server:

```csharp
FindProjectedPropertyNameForIndex = (indexedType, indexName, path, prop) => path + prop
```

Now, when using the same query, the RQL sent to the server will contain the nested `School.Id` property name,  
and the query will return results:

#### Query

```csharp
// Query the index
var query = session.Query<Students_BySchoolId.IndexEntry, Students_BySchoolId>()
    .Where(x => x.Name == "someStudentName")
    .OfType<Student>()
    // Project only the School.Id property from the Student document in the results
    .Select(student => student.School.Id)
    .ToList();
```

#### RQL

```sql
from index 'Students/BySchoolId'
where Name == "someStudentName"
select School.Id
// The RQL sent to the server now contains 'School.Id',
// as defined by the FindProjectedPropertyNameForIndex convention.
```

```csharp
// Syntax:
public Func<Type, string, string, string, string> FindProjectedPropertyNameForIndex { get; set; }
```

### FindPropertyNameForDynamicIndex

- Use the `FindPropertyNameForDynamicIndex` convention to define a function that customizes the  
  property name that will be used in the RQL sent to the server when making a dynamic query.

- The function receives the following input:  
  the index type, the index name, the current path, and the property path that is used in the query predicate.

```csharp
// The DEFAULT function:
FindPropertyNameForDynamicIndex = (Type indexedType, string indexedName, string path, string prop) =>
    path + prop
```

```csharp
// Syntax:
public Func<Type, string, string, string, string> FindPropertyNameForDynamicIndex { get; set; }
```

### FindPropertyNameForIndex

- Use the `FindPropertyNameForIndex` convention to define a function that customizes the name of the  
  index-field property that will be used in the RQL sent to the server when querying a static index.

- The function receives the following input:  
  the index type, the index name, the current path, and the property path that is used in the query predicate.

- DEFAULT: `[].` & `.` are replaced by `_`

```csharp
// The DEFAULT function:
FindPropertyNameForIndex = (Type indexedType, string indexedName, string path, string prop) => 
    (path + prop).Replace("[].", "_").Replace(".", "_")
```

```csharp
// Syntax:
public Func<Type, string, string, string, string> FindPropertyNameForIndex { get; set; }
```

### FirstBroadcastAttemptTimeout

- Use the `FirstBroadcastAttemptTimeout` convention to set the timeout for the first broadcast attempt.

- In the first attempt, the request executor will send a single request to the selected node.  
  Learn about the "selected node" in: [Client logic for choosing a node](https://docs.ravendb.net/7.2/client-api/configuration/load-balance/overview.md#client-logic-for-choosing-a-node).

- A [second attempt](#secondbroadcastattempttimeout) will be held upon failure.

- DEFAULT: `5 seconds`

```csharp
FirstBroadcastAttemptTimeout = TimeSpan.FromSeconds(10)
```

```csharp
// Syntax:
public TimeSpan FirstBroadcastAttemptTimeout { get; set; }
```

### GlobalHttpClientTimeout

- Use the `GlobalHttpClientTimeout` convention to set the maximum time the underlying `HttpClient` can spend on a single HTTP request.
  If a request takes longer than this value, the request times out and the client reports an error.  
  This setting does not control how long an idle TCP connection remains open; it limits how long the client waits for an HTTP request to complete.

- This value also serves as the maximum allowed timeout for request-executor timeouts,
  such as [RequestTimeout](#requesttimeout),
  [FirstBroadcastAttemptTimeout](#firstbroadcastattempttimeout),
  [SecondBroadcastAttemptTimeout](#secondbroadcastattempttimeout), and per-request command timeouts.  
  Setting any of these to a value greater than `GlobalHttpClientTimeout` will throw an exception.

- In client code, set `GlobalHttpClientTimeout` to be greater than or equal to the longest request timeout you plan to use.
  For example, if you set `RequestTimeout` or a per-request timeout to 24 hours, `GlobalHttpClientTimeout` must also be at least 24 hours.

- Set the value to `Timeout.InfiniteTimeSpan` to remove this upper-bound restriction.

- DEFAULT: `12 hours`

```csharp
GlobalHttpClientTimeout = TimeSpan.FromHours(6)
```

```csharp
// Syntax:
public TimeSpan GlobalHttpClientTimeout { get; set; }
```

### HttpClientType

- Use the `HttpClientType` convention to set the type of HTTP client you're using.

- RavenDB uses the HTTP type internally to manage its cache.

- If you override the [CreateHttpClient](#createhttpclient) convention to use a non-default HTTP client,  
  we advise that you also set `HttpClientType` so it returns the client type you are actually using.

```csharp
// The type of HTTP client you are using
HttpClientType = typeof(MyHttpClient)
```

```csharp
// Syntax:
public Type HttpClientType { get; set; }
```

### HttpPooledConnectionIdleTimeout

- Available for `.NET Core 3.1` and later.

- Use the `HttpPooledConnectionIdleTimeout` convention to set how long an idle HTTP connection  
  can remain in the connection pool before it is closed.  
  This maps to `SocketsHttpHandler.PooledConnectionIdleTimeout`.

- DEFAULT: `null` — the .NET framework default applies (1 minute).

```csharp
// Syntax:
public TimeSpan? HttpPooledConnectionIdleTimeout { get; set; }
```

### HttpPooledConnectionLifetime

- Available for `.NET Core 3.1` and later.

- Use the `HttpPooledConnectionLifetime` convention to set the maximum lifetime of an HTTP connection  
  in the connection pool.  
  After this duration elapses, the connection is closed and replaced on its next use.  
  This maps to `SocketsHttpHandler.PooledConnectionLifetime`.

- Setting a finite lifetime is useful in environments where DNS records change,  
  as it forces the client to pick up new DNS resolutions periodically.

- DEFAULT: `null` — connections are not recycled based on age.

```csharp
// Syntax:
public TimeSpan? HttpPooledConnectionLifetime { get; set; }
```

### HttpVersion

- Use the `HttpVersion` convention to set the Http version the client will use when communicating  
  with the server.

- DEFAULT:
  - When this convention is explicitly set to `null`, the default HTTP version provided by your .NET framework is used.
  - Otherwise, the default HTTP version is set to `System.Net.HttpVersion.Version20` (HTTP 2.0).

```csharp
// Syntax:
public Version HttpVersion { get; set; }
```

### IdentityPartsSeparator

- Use the `IdentityPartsSeparator` convention to customize the **default ID separator** for document IDs generated automatically by the
  [HiLo algorithm](https://docs.ravendb.net/7.2/client-api/document-identifiers/hilo-algorithm.md).

- The value can be any char except `|` (pipe), which is reserved for identity IDs.

- DEFAULT: `/` (forward slash)

- Applies only to: [HiLo IDs](https://docs.ravendb.net/7.2/server/kb/document-identifier-generation.md#hilo-algorithm-id).

```csharp
// Syntax:
public char IdentityPartsSeparator { get; set; }
```

### LoadBalanceBehavior

### LoadBalancerPerSessionContextSelector

### LoadBalancerContextSeed

- Configure the **load balance behavior** by setting the following conventions:
  - `LoadBalanceBehavior`
  - `LoadBalancerPerSessionContextSelector`
  - `LoadBalancerContextSeed`

- Learn more in the dedicated [Load balance behavior](https://docs.ravendb.net/7.2/client-api/configuration/load-balance/load-balance-behavior.md) article.

### MaxHttpCacheSize

- Use the `MaxHttpCacheSize` convention to set the maximum HTTP cache size.  
  This setting will affect all the databases accessed by the Document Store.

- DEFAULT:

  | System | Usable Memory | Default Value |
  | - | - | - |
  | 64-bit | Lower than or equal to 3GB <br /> Greater than 3GB and Lower than or equal to 6GB <br /> Greater than 6GB | 64MB <br /> 128MB <br /> 512MB |
  | 32-bit | | 32MB |

- **Disabling Caching**:

  - To disable caching globally, set `MaxHttpCacheSize` to zero.
  - To disable caching per session, see: [Disable caching per session](https://docs.ravendb.net/7.2/client-api/session/configuration/how-to-disable-caching.md).

- Note: RavenDB also supports Aggressive Caching.  
  Learn more about this in the [Setup aggressive caching](https://docs.ravendb.net/7.2/client-api/how-to/setup-aggressive-caching.md) article.

```csharp
MaxHttpCacheSize = new Size(256, SizeUnit.Megabytes) // Set max cache size
```

```csharp
MaxHttpCacheSize = new Size(0, SizeUnit.Megabytes) // Disable caching
```

```csharp
// Syntax:
public Size MaxHttpCacheSize { get; set; }
```

### MaxNumberOfRequestsPerSession

- Use the `MaxNumberOfRequestsPerSession` convention to set the maximum number of requests per session.

- DEFAULT: `30`

```csharp
// Syntax:
public int MaxNumberOfRequestsPerSession { get; set; }
```

### Modify serialization of property name

- Different clients use different casing conventions for entity field names. For example:

  | Language | Default casing | Example |
  | - | - | - |
  | C# | PascalCase | OrderLines |
  | Java | camelCase | orderLines |
  | JavaScript | camelCase | orderLines |

- By default, when saving an entity, the naming convention used by the client is reflected in the JSON document properties on the server-side.  
  This default serialization behavior can be customized to facilitate language interoperability.

- **Example**:

  Set `CustomizeJsonSerializer` and `PropertyNameConverter` to serialize an entity's properties as camelCase from a C# client:

```csharp
Serialization = new NewtonsoftJsonSerializationConventions
{
    // .Net properties will be serialized as camelCase in the JSON document when storing an entity
    // and deserialized back to PascalCase
    CustomizeJsonSerializer = s => s.ContractResolver = new CamelCasePropertyNamesContractResolver()
},

// In addition, the following convention is required when
// making a query that filters by a field name and when indexing. 
PropertyNameConverter = memberInfo => FirstCharToLower(memberInfo.Name)
```

```csharp
private string FirstCharToLower(string str) => $"{Char.ToLower(str[0])}{str.Substring(1)}";
```

```csharp
// Syntax:
public ISerializationConventions Serialization { get; set; }
```

### OperationStatusFetchMode

- Use the `OperationStatusFetchMode` convention to set the way an [operation](https://docs.ravendb.net/7.2/client-api/operations/what-are-operations.md) is getting its status when [waiting for completion](https://docs.ravendb.net/7.2/client-api/operations/what-are-operations.md#wait-for-completion).

- DEFAULT:  
  By default, the value is set to `ChangesApi` which uses the WebSocket protocol underneath when a connection is established with the server.

- On some older systems like Windows 7 the WebSocket protocol might not be available due to the OS and .NET Framework limitations.
  To bypass this issue, the value can be changed to `Polling`.

```csharp
OperationStatusFetchMode = OperationStatusFetchMode.ChangesApi // ChangesApi | Polling
```

```csharp
// Syntax:
public OperationStatusFetchMode OperationStatusFetchMode { get; set; }
```

### OptimisticConcurrencyMode

- Use the `OptimisticConcurrencyMode` convention to set the default optimistic concurrency mode for ALL sessions opened under the document store.
  Sessions that do not explicitly set `OptimisticConcurrencyMode` in their `SessionOptions` will inherit this value.

- Learn more about optimistic concurrency modes and how to configure them in [Configure optimistic concurrency](https://docs.ravendb.net/7.2/client-api/session/configuration/how-to-enable-optimistic-concurrency.md).

- DEFAULT: `OptimisticConcurrencyMode.None`

```csharp
// Syntax:
public OptimisticConcurrencyMode OptimisticConcurrencyMode { get; set; }

// Available modes:
public enum OptimisticConcurrencyMode
{
    None,           // Default - no concurrency checks (Last Write Wins)
    Writes,         // Checks modified documents only
    WritesAndReads  // Checks all tracked documents (modified and not modified)
}
```

> **Warning**
>
> The `UseOptimisticConcurrency` boolean convention is obsolete and will be removed in a future major version.  
> Use `OptimisticConcurrencyMode` instead.

### PreserveDocumentPropertiesNotFoundOnModel

- Loading a document using a different model will result in the removal of the missing model properties  
  from the loaded entity, and no exception is thrown.

- Setting the `PreserveDocumentPropertiesNotFoundOnModel` convention to `true`  
  allows the client to check (via [whatChanged](https://docs.ravendb.net/7.2/client-api/session/how-to/check-if-there-are-any-changes-on-a-session.md#get-session-changes)
  or via [WhatChangedFor](https://docs.ravendb.net/7.2/client-api/session/how-to/check-if-entity-has-changed.md#get-entity-changes) methods)
  for the missing properties on the entity after loading the document.

- DEFAULT: `true`

```csharp
// Syntax:
public bool PreserveDocumentPropertiesNotFoundOnModel { get; set; }
```

### ReadBalanceBehavior

- Configure the **read request behavior** by setting the `ReadBalanceBehavior` convention.

- Learn more in the dedicated [Read balance behavior](https://docs.ravendb.net/7.2/client-api/configuration/load-balance/read-balance-behavior.md) article.

### RequestTimeout

- Use the `RequestTimeout` convention to define the global request timeout value for all `RequestExecutors` created per database.

- DEFAULT: `null` (the default HTTP client timeout will be applied - 12h)

```csharp
RequestTimeout = TimeSpan.FromSeconds(90)
```

```csharp
// Syntax:
public TimeSpan? RequestTimeout { get; set; } 
```

### ResolveTypeFromClrTypeName

- Use the `ResolveTypeFromClrTypeName` convention to define a function that resolves the CLR type  
  from the CLR type name.

- DEFAULT: The type is returned.

```csharp
// The type itself is returned by default
ResolveTypeFromClrTypeName = clrType => clrType.GetType()
```

```csharp
// Syntax:
public Func<string, Type> ResolveTypeFromClrTypeName { get; set; }
```

### SaveEnumsAsIntegers

- When setting the `SaveEnumsAsIntegers` convention to `true`,  
  C# `enum` types will be stored and queried as integers, rather than their string representations.

- DEFAULT: `false` (save as strings)

- This convention does not affect values written by the typed `Session.Advanced.Patch` methods.  
  See [SaveEnumsAsIntegersForPatching](#saveenumsasintegersforpatching).

```csharp
// Syntax:
public bool SaveEnumsAsIntegers { get; set; } 
```

### SaveEnumsAsIntegersForPatching

- Use the `SaveEnumsAsIntegersForPatching` convention to control how C# `enum` **values** are written by the typed `Session.Advanced.Patch` methods.

  When set to `true`, enum values are patched as integers.  
  When `false`, they are patched as their string names.

- The convention applies to both command formats produced by the
  [SessionPatchBehavior](#sessionpatchbehavior) convention,  
  JSON Patch and JavaScript patch alike.

- Enum **keys** of a patched dictionary are not affected by this convention.  
  A dictionary key is always written as its string name, such as `"Engine"`.

- This convention is independent of [SaveEnumsAsIntegers](#saveenumsasintegers),
  which governs how enums are stored and queried.

  Set both conventions to the same value so that an enum written by a patch matches the representation used when the document is stored.
  Leaving them inconsistent can store the same field as a string in one document and as an integer in another.

- DEFAULT: `false` (patch as strings)

```csharp
SaveEnumsAsIntegersForPatching = true
```

```csharp
// Syntax:
public bool SaveEnumsAsIntegersForPatching { get; set; }
```

### SecondBroadcastAttemptTimeout

- Use the `SecondBroadcastAttemptTimeout` convention to set the timeout for the second broadcast attempt.

- Upon failure of the [first attempt](#firstbroadcastattempttimeout) the request executor will resend the command to all nodes simultaneously.

- DEFAULT: `30 seconds`

```csharp
SecondBroadcastAttemptTimeout = TimeSpan.FromSeconds(20)
```

```csharp
public TimeSpan SecondBroadcastAttemptTimeout { get; set; } 
```

### SendApplicationIdentifier

- Use the `SendApplicationIdentifier` convention to `true` to enable sending a unique application identifier to the RavenDB Server.

- Setting to *true* allows the server to issue performance hint notifications to the client,
  e.g. during robust topology update requests which could indicate a Client API misuse impacting the overall performance.

- DEFAULT: `true`

```csharp
// Syntax:
public bool SendApplicationIdentifier { get; set; } 
```

### SessionPatchBehavior

- Use the `SessionPatchBehavior` convention to control whether the .NET typed `Session.Advanced.Patch` methods generate RFC 6902 JSON Patch commands or JavaScript patch commands.  
  These methods can set a value, add or remove array items, and add or remove dictionary entries.

- DEFAULT: `SessionPatchBehavior.JsonPatch`

- `SessionPatchBehavior.JsonPatch`:  
  The client generates an RFC 6902 JSON Patch command when the operation, value, and path can be represented as JSON Patch
  and no JavaScript patch command is already queued for the same document.  
  Otherwise, the client falls back to a JavaScript patch command.  
  `RemoveAll` with a predicate is an example of an operation that falls back to JavaScript.  
  `Increment`, `AddOrPatch`, and `AddOrIncrement` always generate JavaScript patch commands and are not controlled by this convention.

  JSON Patch uses stricter removal semantics than JavaScript:

  - Calling array `RemoveAt` with an out-of-range index causes `SaveChanges()` to throw.
  - Removing a dictionary key that does not exist causes `SaveChanges()` to throw.

  With the legacy JavaScript behavior, both operations are no-ops.

- `SessionPatchBehavior.JavaScript`:  
  Generate JavaScript patch commands for all typed `Session.Advanced.Patch` calls.  
  Set this value to opt out of JSON Patch and restore the behavior used before JSON Patch support.

- Regardless of the selected value, C# `enum` values written by these methods are represented according to the
  [SaveEnumsAsIntegersForPatching](#saveenumsasintegersforpatching) convention.

```csharp
SessionPatchBehavior = SessionPatchBehavior.JavaScript
```

```csharp
// Syntax:
public SessionPatchBehavior SessionPatchBehavior { get; set; }
```

- Learn more about the [session patch API](https://docs.ravendb.net/7.2/documents/patching-documents/patch-a-single-document/api-overview.md#session-api).

### ShouldIgnoreEntityChanges

- Set the `ShouldIgnoreEntityChanges` convention to disable entity tracking for certain entities.

- Learn more in [Customize tracking in conventions](https://docs.ravendb.net/7.2/client-api/session/configuration/how-to-disable-tracking.md#customize-tracking-in-conventions).

### TopologyCacheLocation

- Use the `TopologyCacheLocation` convention to change the location of the topology cache files  
  (`*.raven-database-topology` & `*.raven-cluster-topology`).

- Directory existence and writing permissions will be checked when setting this value.

- DEFAULT: `AppContext.BaseDirectory` (The application's base directory)

```csharp
TopologyCacheLocation = @"C:\\RavenDB\\TopologyCache"
```

```csharp
// Syntax:
public string TopologyCacheLocation { get; set; } 
```

### TransformTypeCollectionNameToDocumentIdPrefix

- Use the `TransformTypeCollectionNameToDocumentIdPrefix` convention to define a function that will  
  customize the document ID prefix from the collection name.

- DEFAULT:  
  By default, the document id prefix is determined as follows:

| Number of uppercase letters in collection name | Document ID prefix |
| - | - |
| `<= 1` | Use the collection name with all lowercase letters |
| `> 1` | Use the collection name as is, preserving the original case |

```csharp
// Syntax:
public Func<string, string> TransformTypeCollectionNameToDocumentIdPrefix { get; set; }
```

### UseHttpCompression

- When setting the `UseHttpCompression` convention to `true`,  
  then `Gzip` compression will be used when sending content of HTTP request.

- When the convention is set to `false`, content will not be compressed.

- DEFAULT: `true`

```csharp
// Syntax:
public bool UseHttpCompression { get; set; }
```

### UseHttpDecompression

- When setting the `UseHttpDecompression` convention to `true`,  
  the client can accept compressed HTTP response content and will use zstd/gzip/deflate decompression methods.

- DEFAULT: `true`

```csharp
// Syntax:
public bool UseHttpDecompression { get; set; }
```

### HttpCompressionAlgorithm

- Use this convention to set the HTTP compression algorithm
  (see [UseHttpDecompression](#usehttpcompression) above).

- DEFAULT: `Zstd`
  > **Info:** Default compression algorithm {#default-compression-algorithm}
  >
  > In RavenDB versions up to `6.2`, HTTP compression is set to `Gzip` by default.  
  > In RavenDB versions from `7.0` on, the default has changed and is now `Zstd`.

```csharp
// Syntax:
public HttpCompressionAlgorithm HttpCompressionAlgorithm { get; set; }
```

### WaitForIndexesAfterSaveChangesTimeout

- Use the `WaitForIndexesAfterSaveChangesTimeout` convention to set the default timeout for the
  `DocumentSession.Advanced.WaitForIndexesAfterSaveChanges` method.

- DEFAULT: 15 Seconds

```csharp
WaitForIndexesAfterSaveChangesTimeout = TimeSpan.FromSeconds(10)
```

```csharp
// Syntax:
public TimeSpan WaitForIndexesAfterSaveChangesTimeout { get; set; }
```

### WaitForNonStaleResultsTimeout

- Use the `WaitForNonStaleResultsTimeout` convention to set the default timeout used by the  
  `WaitForNonStaleResults` method when querying.

- DEFAULT: 15 Seconds

```csharp
WaitForNonStaleResultsTimeout = TimeSpan.FromSeconds(10)
```

```csharp
// Syntax:
public TimeSpan WaitForNonStaleResultsTimeout { get; set; }
```

### WaitForReplicationAfterSaveChangesTimeout

- Use the `WaitForReplicationAfterSaveChangesTimeout` convention to set the default timeout for the  
  `DocumentSession.Advanced.WaitForReplicationAfterSaveChanges`method.

- DEFAULT: 15 Seconds

```csharp
WaitForReplicationAfterSaveChangesTimeout = TimeSpan.FromSeconds(10)
```

```csharp
// Syntax:
public TimeSpan WaitForReplicationAfterSaveChangesTimeout { get; set; }
```

## See also

- [Querying](https://docs.ravendb.net/7.2/querying/customize-query.md)
- [Serialization](https://docs.ravendb.net/7.2/client-api/configuration/serialization.md)
- [Load Balancing Client Requests](https://docs.ravendb.net/7.2/client-api/configuration/load-balance/overview.md)
- [Working with Document Identifiers](https://docs.ravendb.net/7.2/client-api/document-identifiers/working-with-document-identifiers.md)
- [Global ID Generation Conventions](https://docs.ravendb.net/7.2/client-api/configuration/identifier-generation/global.md)
- [Type-specific ID Generation Conventions](https://docs.ravendb.net/7.2/client-api/configuration/identifier-generation/type-specific.md)
- [What is a Document Store](https://docs.ravendb.net/7.2/client-api/what-is-a-document-store.md)
