---
title: "Document Expiration: Client API"
description: "Enable and configure document expiration for a database using the client API, and schedule a document's deletion by setting the @expires metadata property."
url: "https://docs.ravendb.net/7.2/documents/document-expiration/client-api"
version: "7.2"
language: "csharp"
---

# Document Expiration: Client API

> Client language: C#. Also available for [Java](https://docs.ravendb.net/7.2/documents/document-expiration/client-api.java.md), [Python](https://docs.ravendb.net/7.2/documents/document-expiration/client-api.python.md), [PHP](https://docs.ravendb.net/7.2/documents/document-expiration/client-api.php.md), [Node.js](https://docs.ravendb.net/7.2/documents/document-expiration/client-api.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 **document expiration** feature deletes a document once the time you schedule for it has passed.  
>   Use *document expiration* for documents that are needed only for a limited time, like documents that hold shopping
>   carts, login sessions, or cached data.  
>   Deleting the document triggers features that react to the deletion of documents, like indexing, replication, and ETL tasks.
>
> - To schedule a document's expiration, set the `@expires` [metadata](https://docs.ravendb.net/7.2/client-api/session/how-to/get-and-modify-entity-metadata.md)
>   property of the document to the intended expiration time.
>
> - To enable *document expiration* for a database, send the server an `ExpirationConfiguration` object using the
>   [ConfigureExpirationOperation](#configureexpirationoperation) operation.  
>   The `ExpirationConfiguration` object also sets the frequency at which the *document expiration* feature checks the database
>   for documents whose expiration time has passed.
>
> - To enable and configure *document expiration* using Studio, see
>   [Document Expiration: Studio View](https://docs.ravendb.net/7.2/documents/document-expiration/document-expiration-view.md).
>
> - In this article:
>   - [Expiring documents](#expiring-documents)
>     - [The expiration process](#the-expiration-process)
>   - [Enabling document expiration](#enabling-document-expiration)
>   - [Scheduling a document's expiration](#scheduling-a-document-s-expiration)
>   - [Expiration considerations](#expiration-considerations)
>   - [Syntax](#syntax)
>     - [ConfigureExpirationOperation](#configureexpirationoperation)
>     - [Classes](#classes)

## Expiring documents {#expiring-documents}

Using **document expiration**, you can schedule RavenDB to delete a document at a set time.  
This way, data that is needed only for a limited time is removed once the set time has passed, with no further action
required from your application.

For example:

- A shopping cart that is kept only for a certain time.
- An email link that expires after a few hours.
- The details of a login session.
- Cached data, like data copied from an SQL server.

---

### The expiration process

1. **Enabling document expiration for a database:**  
   *Document expiration* is **disabled** by default.
   See [Enabling document expiration](#enabling-document-expiration) below.

2. **Scheduling a document's expiration:**  
   Add an `@expires` property to the
   [metadata](https://docs.ravendb.net/7.2/client-api/session/how-to/get-and-modify-entity-metadata.md) of the document you want to
   delete, and set the property's value to the intended expiration time.  
   e.g., `"@expires": "2026-12-01T08:00:00.0000000Z"`  
   See [Scheduling a document's expiration](#scheduling-a-document-s-expiration) below.

   > **Note**
   >
   > Some RavenDB features may also add the `@expires` property to documents they create.  
   > Like any other document scheduled for expiration, a document scheduled by one of these features is deleted only if
   > *document expiration* is enabled for the database.
   >
   > - [AI agents](https://docs.ravendb.net/7.2/ai-integration/ai-agents/creating-ai-agents/creating-ai-agents_api.md) add the `@expires` property to
   >   the conversation documents they store, if an expiration period is set for the conversation.  
   >   AI agents also add the `@expires` property to the conversation history documents they store, if an expiration period
   >   is set for history documents in the agent's configuration.
   > - An [embeddings generation task](https://docs.ravendb.net/7.2/ai-integration/generating-embeddings/embedding-collections.md#expiration-policy)
   >   always adds the `@expires` property to the documents of its embeddings cache collection, according to the task's
   >   cache expiration period (90 days by default).

3. **Deleting the scheduled document:**  
   The *document expiration* feature runs periodically (every 60 seconds by default).  
   Each time the feature runs, it checks the database for documents whose expiration time has passed.

   - In the feature's first run after a document's expiration time, the document is deleted.
   - The document may be deleted in a later run if the number of documents due for deletion exceeds the maximum set for
     a single run by [MaxItemsToProcess](#maxitemstoprocess).
   - Like any other deleted document, a document deleted by the *document expiration* feature is replaced by a
     [tombstone](https://docs.ravendb.net/7.2/monitoring/tombstones/overview.md), and its attachments, counters, and time series are deleted with it.

4. **Processing the deletion:**  
   Features that react to the deletion of documents process the deletion.  
   For example:

   - Indexes remove the index entries that refer to the deleted document.
   - The deletion is replicated to the other nodes of the
     [database group](https://docs.ravendb.net/7.2/server/clustering/distribution/distributed-database.md),
     and to the destinations of [external replication](https://docs.ravendb.net/7.2/server/ongoing-tasks/external-replication.md) tasks.
   - [ETL tasks](https://docs.ravendb.net/7.2/server/ongoing-tasks/etl/basics.md) apply the deletion at their destinations.
   - If [revisions](https://docs.ravendb.net/7.2/document-extensions/revisions/overview.md) are enabled for the document's collection, the
     document's revisions are moved to the [Revisions Bin](https://docs.ravendb.net/7.2/studio/database/document-extensions/revisions/revisions-bin.md),
     or deleted if the revisions configuration is set to purge the revisions of deleted documents.

## Enabling document expiration {#enabling-document-expiration}

To enable *document expiration* for a database, send the server an
[ExpirationConfiguration](#expirationconfiguration) object with its `Disabled`
property set to `false`, using the
[ConfigureExpirationOperation](#configureexpirationoperation) operation.

e.g., the following code enables *document expiration*, sets the feature to run every five minutes, and limits the number of
documents processed in each run to 1,000.

```csharp
// Define the expiration configuration
var expirationConfiguration = new ExpirationConfiguration
{
    // Enable document expiration for the database
    Disabled = false,

    // Check the database every 5 minutes for documents whose expiration time has passed
    DeleteFrequencyInSec = 300,

    // Process up to 1,000 documents in each run
    MaxItemsToProcess = 1000
};

// Send the configuration to the server
store.Maintenance.Send(new ConfigureExpirationOperation(expirationConfiguration));
```

> **Note**
>
> On a **secure server**, enabling or configuring the *document expiration* feature requires, like other changes to a database's
> configuration, a client certificate with `Admin` access to the database (or with an `Operator` or `Cluster Admin`
> [security clearance](https://docs.ravendb.net/7.2/server/security/authorization/security-clearance-and-permissions.md)).  
> Setting a document's `@expires` metadata property, on the other hand, is a change to the document, which `Read/Write` access
> permits.  
> See [Setting up Authentication and Authorization](https://docs.ravendb.net/7.2/client-api/setting-up-authentication-and-authorization.md)

The `ExpirationConfiguration` object holds the following settings:

- #### `Disabled`
  Set this property to `false` to enable *document expiration*, or to `true` to disable the feature.  
  The default value for this property is `false`, so sending a new `ExpirationConfiguration` object enables *document
  expiration* unless you explicitly set `Disabled` to `true`.

- #### `DeleteFrequencyInSec`
  Sets the interval, in seconds, between the *document expiration* feature's checks for documents whose expiration time has
  passed.  
  The default value for this property is 60 seconds.
  - **The `DeleteFrequencyInSec` value must be greater than 0:**  
    Sending a value of 0 or less fails with a `RavenException`, whose inner exception is an `InvalidOperationException`.  
    e.g., the following code sends a `DeleteFrequencyInSec` value of 0 and catches the resulting exception.

    ```csharp
    try
    {
        store.Maintenance.Send(new ConfigureExpirationOperation(new ExpirationConfiguration
        {
            Disabled = false,
            DeleteFrequencyInSec = 0
        }));
    }
    catch (RavenException e) when (e.InnerException is InvalidOperationException)
    {
        // The inner exception's message includes:
        // "Expiration delete frequency for database '<database name>' must be greater than 0."
    }
    ```
  - **On a [Community license](https://ravendb.net/buy), the `DeleteFrequencyInSec` value must be at least 129600 (36 hours):**  
    Enabling *document expiration* with a lower value, or without setting `DeleteFrequencyInSec` (so that the 60-second default
    applies), fails with a `LicenseLimitException`.  
    e.g., the code at the beginning of this section, which sets `DeleteFrequencyInSec` to 300, fails on a Community license.

- #### `MaxItemsToProcess`
  Sets the maximum number of documents the *document expiration* feature processes in a single run (each time the feature
  checks the database for documents whose expiration time has passed).  
  By default, a single run can process any number of documents.
  - Each run processes the documents due for deletion in the order of their expiration times, earliest first.  
    Documents that share an expiration time are processed in the order of their document IDs.
  - If the number of documents due for deletion exceeds the set maximum, the documents will be processed over multiple
    consecutive runs.

---

You can also enable *document expiration* when you create a database, by setting the `Expiration` property of the database
record to an `ExpirationConfiguration` object.  
See [Create Database Operation](https://docs.ravendb.net/7.2/client-api/operations/server-wide/create-database.md#create-new-database).

## Scheduling a document's expiration {#scheduling-a-document-s-expiration}

To schedule a document's expiration, set the `@expires` metadata property of the document to the intended expiration time, and
save the document.

> **Warning**
>
> The `@expires` metadata property is reserved for the *document expiration* feature.  
> Do not use it for any other purpose: RavenDB reads any value set for this property as an expiration time.  
> A valid date and time schedules the document's deletion, and any other value makes saving the document fail.

e.g., the following code stores a new shopping cart document and schedules the document's expiration for one hour from now.

```csharp
using (var session = store.OpenSession())
{
    // Store a new document
    var cart = new ShoppingCart { CustomerId = "customers/1-A" };
    session.Store(cart, "shoppingCarts/1-A");

    // Set the document's expiration time to one hour from now, in UTC
    session.Advanced.GetMetadataFor(cart)["@expires"] = DateTime.UtcNow.AddHours(1);

    // Save the document
    session.SaveChanges();
}
```

- #### Setting the expiration time in UTC

  Set the `@expires` property to a UTC `DateTime` value (e.g., `DateTime.UtcNow.AddHours(1)`).  
  The client sends a UTC value with a `Z` suffix, which marks the time as UTC, so the server reads the intended time
  correctly.  
  e.g., `"@expires": "2026-12-01T08:00:00.0000000Z"`

  > **Note**
  >
  > Do not set the property to a local `DateTime` value (e.g., `DateTime.Now.AddHours(1)`).  
  > If you set a local `DateTime` value, the client will send the value without a time zone designator, and the server will
  > read the value as the server machine's local time. If the client machine and the server machine are in different time
  > zones, the document will be deleted at a different time than intended.

- #### Setting an invalid expiration time
  If the value of the `@expires` property is not a valid date and time, `SaveChanges` throws a `RavenException`, and none
  of the session's changes are saved.

- #### Scheduling while *document expiration* is disabled
  Setting the `@expires` property while *document expiration* is disabled for the database still schedules the document's
  expiration:
  - If you enable the feature before the expiration time, the document will be deleted in the feature's first run after
    the expiration time.
  - If the expiration time passes while the feature is disabled, the document will be deleted after the feature is
    enabled, during its first run.
  - In both cases, the document may be deleted in a later run if the number of documents due for deletion exceeds the
    maximum set for a single run by [MaxItemsToProcess](#maxitemstoprocess).

- #### Changing or canceling a scheduled expiration
  To change a document's expiration time, set its `@expires` property to a new time and save the document.  
  To cancel the expiration, remove the `@expires` property from the document's metadata and save the document.  
  e.g., `session.Advanced.GetMetadataFor(cart).Remove("@expires");`

## Expiration considerations {#expiration-considerations}

- #### Deletion delays
  A document is deleted in the *document expiration* feature's first run after the document's expiration time, not at the
  exact moment the expiration time passes.
  - The deletion may be delayed by up to the interval between runs (set by
    [DeleteFrequencyInSec](#deletefrequencyinsec), 60 seconds by default).
  - The deletion may be delayed further if the number of documents due for deletion exceeds the maximum set for a single run
    by [MaxItemsToProcess](#maxitemstoprocess).

- #### Documents remain available until they are deleted
  A document whose expiration time has passed is not hidden from your application.  
  Until the document is deleted, loading or querying can still return the document, and indexes still hold the
  document's entries.

- #### Conflicted documents
  A document that is in [conflict](https://docs.ravendb.net/7.2/server/clustering/replication/replication-conflicts.md) is deleted only if all
  its conflicting versions have an `@expires` property, and the expiration time of all these versions has passed.
  - A document remains in conflict only if the conflict is not resolved automatically: by default, RavenDB resolves
    conflicts to the most recently modified version of the document (see
    [Conflict Detection](https://docs.ravendb.net/7.2/server/clustering/replication/replication-conflicts.md#conflict-detection)).

- #### Reverting documents to revisions
  When you [revert a document to a revision](https://docs.ravendb.net/7.2/document-extensions/revisions/revert-documents-to-revisions/revert-documents-to-specific-revisions.md)
  (or [revert documents to a specific time](https://docs.ravendb.net/7.2/document-extensions/revisions/revert-documents-to-revisions/revert-documents-to-specific-time.md)),
  the reverted document gets the content of the revision **without** the revision's `@expires` property, even if the revision
  holds this property.
  - The `@expires` property is omitted from the reverted document because the revision's expiration time was set when
    the revision was created, and has usually already passed by the time of the revert.  
    Keeping the property would delete the reverted document right after the revert.
  - Since the `@expires` property is omitted, the reverted document will no longer be scheduled for deletion unless you set
    its `@expires` property again.

- #### Exporting and importing documents
  By default, [export and import](https://docs.ravendb.net/7.2/client-api/smuggler/what-is-smuggler.md) operations include documents whose
  expiration time has passed.  
  To leave these documents out, set the `IncludeExpired` option of the export or import operation to `false`.  
  Imported documents keep their `@expires` property: if *document expiration* is enabled for the destination database,
  imported documents whose expiration time has passed will be deleted in the feature's first run after the import.

- #### Compare-exchange items
  Compare-exchange items can also be scheduled for expiration by an `@expires` property in their metadata.  
  Their expiration is handled separately, not by the *document expiration* feature.  
  See [Compare-Exchange Expiration](https://docs.ravendb.net/7.2/compare-exchange/cmpxchg-expiration.md)

## Syntax {#syntax}

### ConfigureExpirationOperation

Sends an `ExpirationConfiguration` object to the server, to enable or disable *document expiration* for a database and
configure the feature.

```csharp
public ConfigureExpirationOperation(ExpirationConfiguration configuration)
```

Usage:

```csharp
// Sync
ConfigureExpirationOperationResult result =
    store.Maintenance.Send(new ConfigureExpirationOperation(expirationConfiguration));

// Async
ConfigureExpirationOperationResult asyncResult =
    await store.Maintenance.SendAsync(new ConfigureExpirationOperation(expirationConfiguration));
```

| Parameter | Type | Description |
| - | - | - |
| **configuration** | [ExpirationConfiguration](#expirationconfiguration) | The *document expiration* configuration to apply to the database. |

| Return value | |
| - | - |
| [ConfigureExpirationOperationResult](#configureexpirationoperationresult) | Contains `RaftCommandIndex`. |

### Classes

#### ExpirationConfiguration

##### `ExpirationConfiguration`

**Defines the *document expiration* configuration of a database.**

```csharp
class ExpirationConfiguration
{
    bool Disabled
    long? DeleteFrequencyInSec
    long? MaxItemsToProcess
}
```

| Property | Type | Description |
| - | - | - |
| **Disabled** | `bool` | Set to `false` to enable *document expiration* for the database, or to `true` to disable the feature.<br />The default value is `false`. |
| **DeleteFrequencyInSec** | `long?` | The interval, in seconds, between the feature's checks for documents whose expiration time has passed.<br />The value must be greater than 0.<br />If `null`, the default value of 60 seconds applies.<br />On a Community license, the value must be at least 129600 (36 hours). See [Enabling document expiration](#enabling-document-expiration). |
| **MaxItemsToProcess** | `long?` | The maximum number of documents the feature processes in a single run.<br />If `null`, a single run can process any number of documents. |

#### ConfigureExpirationOperationResult

##### `ConfigureExpirationOperationResult`

**The result of sending a `ConfigureExpirationOperation` operation to the server.**

```csharp
class ConfigureExpirationOperationResult
{
    long? RaftCommandIndex
}
```

| Property | Type | Description |
| - | - | - |
| **RaftCommandIndex** | `long?` | The Raft index of the command that applied the configuration. |

## See also

- [How to Get and Modify Metadata](https://docs.ravendb.net/7.2/client-api/session/how-to/get-and-modify-entity-metadata.md)
- [Document Expiration: Studio View](https://docs.ravendb.net/7.2/documents/document-expiration/document-expiration-view.md)
