Skip to content

[MongoDB Replication] Fix resumeTokens going back in time on busy change streams #301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/sweet-years-tickle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@powersync/service-module-mongodb': patch
'@powersync/lib-service-mongodb': patch
'@powersync/service-core': patch
'@powersync/service-image': patch
---

[MongoDB Replication] Fix resumeTokens going back in time on busy change streams.
10 changes: 10 additions & 0 deletions modules/module-mongodb/src/replication/ChangeStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -947,6 +947,16 @@ export class ChangeStream {
timestamp: changeDocument.clusterTime!,
resume_token: changeDocument._id
});
if (batch.lastCheckpointLsn != null && lsn < batch.lastCheckpointLsn) {
// Checkpoint out of order - should never happen with MongoDB.
// If it does happen, we throw an error to stop the replication - restarting should recover.
// Since we use batch.lastCheckpointLsn for the next resumeAfter, this should not result in an infinite loop.
// This is a workaround for the issue below, but we can keep this as a safety-check even if the issue is fixed.
// Driver issue report: https://jira.mongodb.org/browse/NODE-7042
throw new ReplicationAssertionError(
`Change resumeToken ${(changeDocument._id as any)._data} (${timestampToDate(changeDocument.clusterTime!).toISOString()}) is less than last checkpoint LSN ${batch.lastCheckpointLsn}. Restarting replication.`
);
}

if (waitForCheckpointLsn != null && lsn >= waitForCheckpointLsn) {
waitForCheckpointLsn = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class MongoErrorRateLimiter implements ErrorRateLimiter {
// Could be fail2ban or similar
this.setDelay(120_000);
} else {
this.setDelay(30_000);
this.setDelay(5_000);
}
}

Expand Down