Modern applications often need to react to database changes as soon as they happen. For example, an e-commerce application may need to update an order dashboard when an order is created, notify a customer when payment status changes, or synchronize customer information with another system.
MongoDB provides Change Streams to help developers build these real-time features without continuously polling database collections.
However, a change stream consumer does not always run continuously. Applications can restart because of deployments, server failures, network interruptions, container restarts, or unexpected exceptions. If a consumer stops and starts again without remembering its previous position, it may miss changes that occurred while it was offline.
MongoDB addresses this problem through resume tokens. A resume token identifies a position in a change stream and allows an application to continue consuming events from a previously processed point.
This article explains how MongoDB Change Streams work, how to store resume tokens, how to restore a change stream after an application restart, and how to handle situations where the required history is no longer available.
What Are MongoDB Change Streams?
MongoDB Change Streams allow applications to subscribe to changes in database collections, databases, or an entire MongoDB deployment.
Instead of repeatedly querying a collection to check whether something has changed, an application opens a change stream and waits for notifications.
Change Streams are available for replica sets and sharded clusters. They rely on MongoDB's replication infrastructure and provide a supported alternative to manually reading the oplog.
For example, consider an order management application with an Orders collection.
{
"_id": 101,
"customerId": 5001,
"status": "Pending",
"totalAmount": 2500
}When the order status changes, MongoDB can generate a change event.
{
"_id": {
"_data": "resume-token-value"
},
"operationType": "update",
"ns": {
"db": "ShopDB",
"coll": "Orders"
},
"documentKey": {
"_id": 101
},
"updateDescription": {
"updatedFields": {
"status": "Completed"
},
"removedFields": []
}
}The event contains information about the operation, the affected document, and the fields that changed.
The event's _id field contains the resume token. It is different from the _id of the actual order document.
An application can save this token and use it when reopening the change stream.
What Is a MongoDB Resume Token?
A resume token is a unique BSON document generated by MongoDB to identify a position in a change stream.
Every change event includes a resume token in its _id field.
For example:
{
"_id": {
"_data": "82635019A0000000012B042C0100296E5A1004AB1154ACACD849A48C61756D70D3B21F"
},
"operationType": "insert",
"clusterTime": {
"$timestamp": {
"t": 1790000000,
"i": 1
}
}
}The application should store the complete resume token rather than extracting only its _data value.
Resume tokens are opaque identifiers. Their internal format can change between MongoDB versions, so applications should not attempt to construct, decode, or modify them for normal processing.
The token acts like a bookmark. When the application restarts, it passes the previously stored token to MongoDB to continue receiving changes.
For example, the following sequence illustrates the process:
The application opens a change stream.
MongoDB sends a change event.
The application processes the event successfully.
The application saves the event's resume token.
The application stops or restarts.
The application opens a new change stream using the saved token.
MongoDB returns subsequent changes.
This approach helps prevent events from being missed during normal application restarts, provided the required oplog history is still available.
Why Change Streams Need Resume Tokens
Consider an application that consumes order changes and sends notifications to customers.
Without resume tokens, the application may open a new change stream after every restart and receive only changes occurring after the new stream starts.
Imagine the following situation:
Time | Event |
|---|---|
10:00 AM | Application starts consuming changes |
10:05 AM | Order 101 is updated |
10:06 AM | Application processes the event |
10:07 AM | Application saves the resume token |
10:08 AM | Application crashes |
10:10 AM | Order 102 is updated |
10:12 AM | Application restarts |
If the application opens a completely new stream without a resume token, it may not receive the update that occurred at 10:10 AM.
With a saved resume token, the application can continue from its previous position and receive changes that occurred after the saved event.
This is especially important for:
Order processing systems.
Payment status synchronization.
Real-time dashboards.
Notification services.
Search index synchronization.
Data replication between applications.
Event-driven microservices.
Resume tokens make change stream consumers more resilient to interruptions.
Create a MongoDB Change Stream Using C#
The MongoDB .NET/C# Driver provides Watch() and WatchAsync() methods for consuming change streams.
Install the MongoDB driver package:
dotnet add package MongoDB.DriverCreate a simple model for the Orders collection:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
public class Order
{
[BsonId]
public int Id { get; set; }
public int CustomerId { get; set; }
public string Status { get; set; } = string.Empty;
public decimal TotalAmount { get; set; }
}Connect to MongoDB and retrieve the collection:
using MongoDB.Driver;
var client = new MongoClient(
"mongodb://localhost:27017");
var database = client.GetDatabase("ShopDB");
var collection = database.GetCollection<Order>(
"Orders");Now open a change stream:
using var cursor = await collection.WatchAsync();
while (await cursor.MoveNextAsync())
{
foreach (var change in cursor.Current)
{
Console.WriteLine(
$"Operation: {change.OperationType}");
Console.WriteLine(
$"Order: {change.DocumentKey}");
}
}The application waits for database changes and processes the events as they arrive.
The cursor remains active until it is closed, invalidated, or interrupted by a connection or deployment problem.
This basic example does not persist resume tokens. If the application terminates, it cannot reliably continue from its last successfully processed event.
To support application restarts, the application must save the resume token in durable storage.
Store Resume Tokens in MongoDB
A common approach is to maintain a separate collection for change stream checkpoints.
For example, create a collection named ChangeStreamCheckpoints.
A checkpoint document can look like this:
{
"_id": "OrdersConsumer",
"resumeToken": {
"_data": "82635019A0000000012B042C0100296E5A1004AB1154ACACD849A48C61756D70D3B21F"
},
"updatedAt": "2026-12-01T10:15:00Z"
}The _id identifies the consumer, while resumeToken stores the complete MongoDB token.
A separate checkpoint collection is useful because it keeps stream-processing state independent of the business documents.
Create a checkpoint model:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
public class ChangeStreamCheckpoint
{
[BsonId]
public string ConsumerId { get; set; } = string.Empty;
[BsonElement("resumeToken")]
public BsonDocument? ResumeToken { get; set; }
public DateTime UpdatedAt { get; set; }
}Create the checkpoint collection:
var checkpointCollection =
database.GetCollection<ChangeStreamCheckpoint>(
"ChangeStreamCheckpoints");Add a method to save the resume token:
async Task SaveCheckpointAsync(
IMongoCollection<ChangeStreamCheckpoint> checkpoints,
string consumerId,
BsonDocument resumeToken)
{
var filter = Builders<ChangeStreamCheckpoint>.Filter
.Eq(x => x.ConsumerId, consumerId);
var update = Builders<ChangeStreamCheckpoint>.Update
.Set(x => x.ResumeToken, resumeToken)
.Set(x => x.UpdatedAt, DateTime.UtcNow);
await checkpoints.UpdateOneAsync(
filter,
update,
new UpdateOptions { IsUpsert = true });
}The IsUpsert option creates the checkpoint document if it does not already exist.
Every successfully processed event can update this checkpoint.
When the application restarts, it retrieves the latest saved token and uses it to reopen the stream.
Resume a Change Stream After Application Restart
The MongoDB .NET Driver supports the ResumeAfter property through ChangeStreamOptions.
First, retrieve the previously stored checkpoint:
var checkpoint =
await checkpointCollection
.Find(x => x.ConsumerId == "OrdersConsumer")
.FirstOrDefaultAsync();
var options = new ChangeStreamOptions();
if (checkpoint?.ResumeToken != null)
{
options.ResumeAfter = checkpoint.ResumeToken;
}Next, open the change stream:
using var cursor = await collection.WatchAsync(
options: options);When a resume token is available, MongoDB continues returning changes after the operation identified by that token.
If no checkpoint exists, the application opens a new stream from the current starting point.
This is an important distinction. Starting a new stream without a token does not automatically retrieve historical changes that happened before the stream was opened.
For production systems, initial synchronization and change stream consumption should be designed together.
Build a Complete Change Stream Consumer
The following example combines checkpoint retrieval, change stream creation, event processing, and resume token persistence.
It uses an order collection and a separate checkpoint collection.
using MongoDB.Bson;
using MongoDB.Driver;
public class OrderChangeConsumer
{
private readonly IMongoCollection<Order> _orders;
private readonly IMongoCollection<ChangeStreamCheckpoint>
_checkpoints;
private const string ConsumerId = "OrdersConsumer";
public OrderChangeConsumer(
IMongoDatabase database)
{
_orders = database.GetCollection<Order>("Orders");
_checkpoints =
database.GetCollection<ChangeStreamCheckpoint>(
"ChangeStreamCheckpoints");
}
public async Task StartAsync(
CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
var checkpoint =
await _checkpoints
.Find(x => x.ConsumerId == ConsumerId)
.FirstOrDefaultAsync(
cancellationToken);
var options = new ChangeStreamOptions
{
MaxAwaitTime = TimeSpan.FromSeconds(5)
};
if (checkpoint?.ResumeToken != null)
{
options.ResumeAfter =
checkpoint.ResumeToken;
}
using var cursor =
await _orders.WatchAsync(
options: options,
cancellationToken:
cancellationToken);
while (await cursor.MoveNextAsync(
cancellationToken))
{
foreach (var change in cursor.Current)
{
await ProcessChangeAsync(
change,
cancellationToken);
await SaveCheckpointAsync(
change.ResumeToken,
cancellationToken);
}
}
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
break;
}
catch (MongoException ex)
{
Console.WriteLine(
$"MongoDB change stream error: {ex.Message}");
await Task.Delay(
TimeSpan.FromSeconds(5),
cancellationToken);
}
}
}
private async Task ProcessChangeAsync(
ChangeStreamDocument<Order> change,
CancellationToken cancellationToken)
{
switch (change.OperationType)
{
case ChangeStreamOperationType.Insert:
Console.WriteLine(
$"New order: {change.DocumentKey}");
break;
case ChangeStreamOperationType.Update:
Console.WriteLine(
$"Order updated: {change.DocumentKey}");
break;
case ChangeStreamOperationType.Replace:
Console.WriteLine(
$"Order replaced: {change.DocumentKey}");
break;
case ChangeStreamOperationType.Delete:
Console.WriteLine(
$"Order deleted: {change.DocumentKey}");
break;
}
await Task.CompletedTask;
}
private async Task SaveCheckpointAsync(
BsonDocument resumeToken,
CancellationToken cancellationToken)
{
var filter =
Builders<ChangeStreamCheckpoint>.Filter
.Eq(x => x.ConsumerId, ConsumerId);
var update =
Builders<ChangeStreamCheckpoint>.Update
.Set(x => x.ResumeToken, resumeToken)
.Set(x => x.UpdatedAt, DateTime.UtcNow);
await _checkpoints.UpdateOneAsync(
filter,
update,
new UpdateOptions { IsUpsert = true },
cancellationToken);
}
}This example demonstrates the basic consumer structure. A production implementation should also include appropriate error classification, logging, monitoring, idempotent event processing, and a defined recovery strategy for history-loss errors.
The important part is the order of operations:
Receive a change event.
Process the event successfully.
Save its resume token.
Continue consuming the stream.
The checkpoint is updated only after processing succeeds.
This ordering helps avoid losing an event when the application crashes before processing it.
However, it can result in the same event being processed more than once. That behavior must be handled through idempotent processing.
Join the conversation! Your thoughts help the community grow.