Skip to main content

Document Expiration: Client API

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

  2. Scheduling a document's expiration:
    Add an @expires property to the metadata 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 below.

    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 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 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.
    • Like any other deleted document, a document deleted by the document expiration feature is replaced by a tombstone, 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, and to the destinations of external replication tasks.
    • ETL tasks apply the deletion at their destinations.
    • If revisions are enabled for the document's collection, the document's revisions are moved to the Revisions Bin, or deleted if the revisions configuration is set to purge the revisions of deleted documents.

Enabling document expiration​

To enable document expiration for a database, send the server an ExpirationConfiguration object with its Disabled property set to false, using the 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.

// 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));

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

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.

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

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.

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.

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"

    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.
  • 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​

  • 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, 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.
  • 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 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).
  • Reverting documents to revisions​

    When you revert a document to a revision (or revert documents to a specific time), 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 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

Syntax​

ConfigureExpirationOperation​

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

public ConfigureExpirationOperation(ExpirationConfiguration configuration)

Usage:

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

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

ParameterTypeDescription
configurationExpirationConfigurationThe document expiration configuration to apply to the database.
Return value
ConfigureExpirationOperationResultContains RaftCommandIndex.

Classes​

ExpirationConfiguration​

Defines the document expiration configuration of a database.

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

PropertyTypeDescription
DisabledboolSet to false to enable document expiration for the database, or to true to disable the feature.
The default value is false.
DeleteFrequencyInSeclong?The interval, in seconds, between the feature's checks for documents whose expiration time has passed.
The value must be greater than 0.
If null, the default value of 60 seconds applies.
On a Community license, the value must be at least 129600 (36 hours). See Enabling document expiration.
MaxItemsToProcesslong?The maximum number of documents the feature processes in a single run.
If null, a single run can process any number of documents.

In this article