---
title: "Client API: Subscribing to Store Events"
description: "Events* let you run custom logic in response to operations made on a DocumentStore"
url: "https://docs.ravendb.net/6.2/client-api/how-to/subscribe-to-store-events"
version: "6.2"
---

# Client API: Subscribing to Store Events

> 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."

## Client API: Subscribing to Store Events

> **Note**
>
> - **Events** let you run custom logic in response to operations made on a `DocumentStore`
>   or a `Session`.  
>   An event is invoked when the selected action runs on an entity, or when a query is made.
>
> - Subscribing to an event at the `DocumentStore` level subscribes to that event in all
>   subsequent sessions.  
>   E.g., to invoke an event after `SaveChanges()` is called by any subsequent session, use:  
>   `store.OnAfterSaveChanges += OnAfterSaveChangesEvent;`
>
> - Subscribing to an event in a `Session` is valid for that session only.  
>   E.g., to invoke an event after `SaveChanges()` is called by this session only, use:  
>   `session.Advanced.OnAfterSaveChanges += OnAfterSaveChangesEvent;`  
>   Read more about session events [here](https://docs.ravendb.net/6.2/client-api/session/how-to/subscribe-to-events.md).
>
> - In this article:
>   - [Store events](#store-events)
>     - [OnBeforeRequest](#onbeforerequest)
>     - [OnSucceedRequest](#onsucceedrequest)
>     - [AfterDispose](#afterdispose)
>     - [BeforeDispose](#beforedispose)
>     - [RequestExecutorCreated](#requestexecutorcreated)
>     - [OnSessionCreated](#onsessioncreated)
>     - [OnFailedRequest](#onfailedrequest)
>     - [OnTopologyUpdated](#ontopologyupdated)
>   - [Store/Session events](#storesession-events)
>   - [Unsubscribing from an event](#unsubscribing-from-an-event)
>   - [Syntax](#syntax)

## Store events {#store-events}

You can subscribe to the following events only at the store level, not within a session.  
Subscribe to the request and topology events (`OnBeforeRequest`, `OnSucceedRequest`,
`OnFailedRequest`, and `OnTopologyUpdated`) before you call `store.Initialize()`.

### `OnBeforeRequest`

This event is invoked by sending a request to the server, before the request is actually sent.  
See its [arguments](#event-arguments) in the Syntax section below.

```csharp
private void OnBeforeRequestEvent(object sender, BeforeRequestEventArgs args);
```

#### Example: block requests to a forbidden URL

```csharp
private void OnBeforeRequestEvent(object sender, BeforeRequestEventArgs args)
{
    var forbiddenURL = new Regex("/databases/[^/]+/docs");

    if (forbiddenURL.IsMatch(args.Url) == true)
    {
        // action to be taken if the URL is forbidden
    }
}
```

Subscribe to the event:

```csharp
store.OnBeforeRequest += OnBeforeRequestEvent;
```

### `OnSucceedRequest`

This event is invoked by receiving a successful reply from the server.  
See its [arguments](#event-arguments) in the Syntax section below.

```csharp
private void OnSucceedRequestEvent(object sender, SucceedRequestEventArgs args);
```

#### Example: act on a successful request

```csharp
private void OnSucceedRequestEvent(object sender, SucceedRequestEventArgs args)
{
    if (args.Response.IsSuccessStatusCode == true)
    {
        // action to be taken after a successful request
    }
}
```

Subscribe to the event:

```csharp
store.OnSucceedRequest += OnSucceedRequestEvent;
```

### `AfterDispose`

This event is invoked immediately after a document store is disposed of.  
The `args` parameter has no contents for this event.

```csharp
private void AfterDisposeEvent(object sender, EventArgs args);
```

Subscribe to the event:

```csharp
store.AfterDispose += AfterDisposeEvent;
```

### `BeforeDispose`

This event is invoked immediately before a document store is disposed of.  
The `args` parameter has no contents for this event.

```csharp
private void BeforeDisposeEvent(object sender, EventArgs args);
```

Subscribe to the event:

```csharp
store.BeforeDispose += BeforeDisposeEvent;
```

### `RequestExecutorCreated`

This event is invoked when a Request Executor is created, letting you subscribe to the
various events of that request executor.

```csharp
private void RequestExecutorCreatedEvent(object sender, RequestExecutor args);
```

Subscribe to the event:

```csharp
store.RequestExecutorCreated += RequestExecutorCreatedEvent;
```

### `OnSessionCreated`

This event is invoked after a session is created, letting you, for example, change session
configurations.  
See its [arguments](#event-arguments) in the Syntax section below.

```csharp
private void OnSessionCreatedEvent(object sender, SessionCreatedEventArgs args);
```

#### Example: configure a new session

```csharp
private void OnSessionCreatedEvent(object sender, SessionCreatedEventArgs args)
{
    args.Session.MaxNumberOfRequestsPerSession = 100;
}
```

Subscribe to the event:

```csharp
store.OnSessionCreated += OnSessionCreatedEvent;
```

### `OnFailedRequest`

This event is invoked when a request to a node has failed. Use it, for example, to track and log
failed requests.  
See its [arguments](#event-arguments) in the Syntax section below.

```csharp
private void OnFailedRequestEvent(object sender, FailedRequestEventArgs args);
```

#### Example: log every failed request

```csharp
private void OnFailedRequestEvent(object sender, FailedRequestEventArgs args)
{
    Logger($"Failed request for database '{args.Database}' ('{args.Url}')", args.Exception);
}
```

Subscribe to the event:

```csharp
store.OnFailedRequest += OnFailedRequestEvent;
```

### `OnTopologyUpdated`

This event is invoked by a topology update (e.g. when a node is added), after the topology
is updated.  
See its [arguments](#event-arguments) in the Syntax section below.

```csharp
private void OnTopologyUpdatedEvent(object sender, TopologyUpdatedEventArgs args);
```

You can also use this event to rewrite the URLs the client will use: change the `Url` of any
node in `args.Topology.Nodes`, and the client will route its requests to the new address.  
This is useful when the node URLs registered in the cluster are not the addresses reachable
from where the client runs.  
A common case is a cluster whose nodes use hostnames that resolve only inside the cluster's
network, while an external client must reach those same nodes through publicly reachable
hostnames.  
You can then map each internal hostname to its public counterpart, so the client connects
through reachable addresses.  
RavenDB invokes your `OnTopologyUpdated` handler on every topology update, so your URL mapping
is re-applied to each new topology the client receives.

#### Example: remap node URLs

```csharp
void OnTopologyUpdatedEvent(object sender, TopologyUpdatedEventArgs args)
{
    foreach (var node in args.Topology.Nodes)
    {
        // Map each node's internal hostname to one reachable from this client
        node.Url = node.Url.Replace("internal.example.com", "public.example.com");
    }
}
```

Subscribe to the event:

```csharp
store.OnTopologyUpdated += OnTopologyUpdatedEvent;
```

## Store/Session events {#store-session-events}

You can subscribe to the following events both at the store level and in a session.

> **Note**
>
> - Subscribing to an event in a session limits the scope of the subscription to that session.
> - Subscribing to an event at the store level is inherited by all subsequent sessions.

- [OnBeforeStore](https://docs.ravendb.net/6.2/client-api/session/how-to/subscribe-to-events.md#onbeforestore)
- [OnAfterSaveChanges](https://docs.ravendb.net/6.2/client-api/session/how-to/subscribe-to-events.md#onaftersavechanges)
- [OnBeforeDelete](https://docs.ravendb.net/6.2/client-api/session/how-to/subscribe-to-events.md#onbeforedelete)
- [OnBeforeQuery](https://docs.ravendb.net/6.2/client-api/session/how-to/subscribe-to-events.md#onbeforequery)
- [OnBeforeConversionToDocument](https://docs.ravendb.net/6.2/client-api/session/how-to/subscribe-to-events.md#onbeforeconversiontodocument)
- [OnAfterConversionToDocument](https://docs.ravendb.net/6.2/client-api/session/how-to/subscribe-to-events.md#onafterconversiontodocument)
- [OnBeforeConversionToEntity](https://docs.ravendb.net/6.2/client-api/session/how-to/subscribe-to-events.md#onbeforeconversiontoentity)
- [OnAfterConversionToEntity](https://docs.ravendb.net/6.2/client-api/session/how-to/subscribe-to-events.md#onafterconversiontoentity)
- [OnSessionDisposing](https://docs.ravendb.net/6.2/client-api/session/how-to/subscribe-to-events.md#onsessiondisposing)

## Unsubscribing from an event {#unsubscribing-from-an-event}

To stop responding to an event, detach the handler with the `-=` operator, passing the same
method you subscribed with:

```csharp
store.OnFailedRequest -= OnFailedRequestEvent;
```

The request and topology events (`OnBeforeRequest`, `OnSucceedRequest`, `OnFailedRequest`,
and `OnTopologyUpdated`) can be subscribed and unsubscribed only before you call
`store.Initialize()`, so they cannot be unsubscribed at runtime.  
All other events on this page can be unsubscribed at any time.

## Syntax {#syntax}

### Events

```csharp
public event EventHandler<BeforeRequestEventArgs> OnBeforeRequest
public event EventHandler<SucceedRequestEventArgs> OnSucceedRequest
public event EventHandler AfterDispose
public event EventHandler BeforeDispose
public event EventHandler<RequestExecutor> RequestExecutorCreated
public event EventHandler<SessionCreatedEventArgs> OnSessionCreated
public event EventHandler<FailedRequestEventArgs> OnFailedRequest
public event EventHandler<TopologyUpdatedEventArgs> OnTopologyUpdated
```

### Event arguments

#### BeforeRequestEventArgs

```csharp
class BeforeRequestEventArgs
{
    string Database
    string Url
    HttpRequestMessage Request
    int AttemptNumber
}
```

| Property | Type | Description |
| - | - | - |
| **Database** | `string` | The database name |
| **Url** | `string` | The database URL |
| **Request** | `HttpRequestMessage` | The request intended to be sent to the server |
| **AttemptNumber** | `int` | The number of attempts made to send the request |

#### SucceedRequestEventArgs

```csharp
class SucceedRequestEventArgs
{
    string Database
    string Url
    HttpResponseMessage Response
    HttpRequestMessage Request
    int AttemptNumber
}
```

| Property | Type | Description |
| - | - | - |
| **Database** | `string` | The database name |
| **Url** | `string` | The database URL |
| **Response** | `HttpResponseMessage` | The response returned from the server |
| **Request** | `HttpRequestMessage` | The original request sent to the server |
| **AttemptNumber** | `int` | The number of attempts made to send the request |

#### FailedRequestEventArgs

```csharp
class FailedRequestEventArgs
{
    string Database
    string Url
    Exception Exception
    HttpResponseMessage Response
    HttpRequestMessage Request
}
```

| Property | Type | Description |
| - | - | - |
| **Database** | `string` | The database name |
| **Url** | `string` | The database URL |
| **Exception** | `Exception` | The exception raised by the failed request |
| **Response** | `HttpResponseMessage` | The response returned from the server |
| **Request** | `HttpRequestMessage` | The original request sent to the server |

#### SessionCreatedEventArgs

```csharp
class SessionCreatedEventArgs
{
    InMemoryDocumentSessionOperations Session
}
```

| Property | Type | Description |
| - | - | - |
| **Session** | `InMemoryDocumentSessionOperations` | The created session |

#### TopologyUpdatedEventArgs

```csharp
class TopologyUpdatedEventArgs
{
    Topology Topology
    string Reason
}
```

| Property | Type | Description |
| - | - | - |
| **Topology** | `Topology` | The updated topology |
| **Reason** | `string` | The reason for the topology update |

#### Topology

```csharp
class Topology
{
    long Etag
    List<ServerNode> Nodes
    List<ServerNode> Promotables
}
```

| Property | Type | Description |
| - | - | - |
| **Etag** | `long` | The topology version |
| **Nodes** | `List<ServerNode>` | The list of cluster member nodes |
| **Promotables** | `List<ServerNode>` | The list of promotable nodes |
