Document Expiration: Client API
-
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
@expiresmetadata property of the document to the intended expiration time. -
To enable document expiration for a database, send the server an
ExpirationConfigurationobject using the ConfigureExpirationOperation operation.
TheExpirationConfigurationobject 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.
-
In this article:
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
-
Enabling document expiration for a database:
Document expiration is disabled by default. See Enabling document expiration below. -
Scheduling a document's expiration:
Add an@expiresproperty 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
@expiresproperty 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
@expiresproperty to the conversation documents they store, if an expiration period is set for the conversation.
AI agents also add the@expiresproperty 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
@expiresproperty to the documents of its embeddings cache collection, according to the task's cache expiration period (90 days by default).
- AI agents add the
-
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.
-
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:
-
DisabledSet this property to
falseto enable document expiration, or totrueto disable the feature.
The default value for this property isfalse, so sending a newExpirationConfigurationobject enables document expiration unless you explicitly setDisabledtotrue. -
DeleteFrequencyInSecSets 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
DeleteFrequencyInSecvalue must be greater than 0:
Sending a value of 0 or less fails with aRavenException, whose inner exception is anInvalidOperationException.
e.g., the following code sends aDeleteFrequencyInSecvalue 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
DeleteFrequencyInSecvalue must be at least 129600 (36 hours):
Enabling document expiration with a lower value, or without settingDeleteFrequencyInSec(so that the 60-second default applies), fails with aLicenseLimitException.
e.g., the code at the beginning of this section, which setsDeleteFrequencyInSecto 300, fails on a Community license.
-
-
MaxItemsToProcessSets 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.
- Each run processes the documents due for deletion in the order of their expiration times, earliest first.
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
@expiresproperty to a UTCDateTimevalue (e.g.,DateTime.UtcNow.AddHours(1)).
The client sends a UTC value with aZsuffix, 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
DateTimevalue (e.g.,DateTime.Now.AddHours(1)).
If you set a localDateTimevalue, 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
@expiresproperty is not a valid date and time,SaveChangesthrows aRavenException, and none of the session's changes are saved. -
Scheduling while document expiration is disabled
Setting the
@expiresproperty 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
@expiresproperty to a new time and save the document.
To cancel the expiration, remove the@expiresproperty 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
@expiresproperty, 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
@expiresproperty, even if the revision holds this property.- The
@expiresproperty 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
@expiresproperty is omitted, the reverted document will no longer be scheduled for deletion unless you set its@expiresproperty again.
- The
-
Exporting and importing documents
By default, export and import operations include documents whose expiration time has passed.
To leave these documents out, set theIncludeExpiredoption of the export or import operation tofalse.
Imported documents keep their@expiresproperty: 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
@expiresproperty 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));
| Parameter | Type | Description |
|---|---|---|
| configuration | ExpirationConfiguration | The document expiration configuration to apply to the database. |
| Return value | |
|---|---|
| ConfigureExpirationOperationResult | Contains RaftCommandIndex. |
Classes
- ExpirationConfiguration
- ConfigureExpirationOperationResult
ExpirationConfiguration
Defines the document expiration configuration of a database.
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.The default value is false. |
| DeleteFrequencyInSec | long? | 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. |
| MaxItemsToProcess | long? | The maximum number of documents the feature processes in a single run. If null, a single run can process any number of documents. |
ConfigureExpirationOperationResult
The result of sending a ConfigureExpirationOperation operation to the server.
class ConfigureExpirationOperationResult
{
long? RaftCommandIndex
}
| Property | Type | Description |
|---|---|---|
| RaftCommandIndex | long? | The Raft index of the command that applied the configuration. |