Skip to content

How do I troubleshoot Amazon DocumentDB change streams failures?

7 minute read
Content level: Advanced
0

I'm using Amazon DocumentDB change streams, but I'm experiencing failures such as missing events, read errors, expired resume tokens, or the stream stopping unexpectedly. I want to identify and resolve the root cause of my change streams issues.

Short description

The change streams feature in Amazon DocumentDB (with MongoDB compatibility) provides a time-ordered sequence of change events that occur within your cluster's collections. Applications use change streams to subscribe to data changes on individual collections for use cases such as change notification, full-text search with Amazon OpenSearch Service, and analytics with Amazon Redshift. Change stream events are ordered as they occur on the cluster and are stored for 3 hours (by default) after the event has been recorded.

Change streams failures are typically caused by one of the following:

  • Change streams not being explicitly enabled on the collection or database
  • Resume tokens expiring beyond the retention window
  • Incorrect read preference settings (connecting to a replica instead of the primary)
  • Oversized events exceeding the 16 MB limit
  • Long-running write operations stalling the stream
  • Network or connection drops closing the underlying cursor

Identify your specific error or symptom from the following scenarios, and then follow the corresponding steps to troubleshoot further.

Resolution

Change streams not enabled

You receive the following error when attempting to open a change stream:

MongoServerError: modifyChangeStreams has not been run for this collection/database/cluster

Change streams are disabled by default in Amazon DocumentDB. You must explicitly enable them for each collection or database before calling watch().

To enable change streams for the specific collection:

db.adminCommand({
    modifyChangeStreams: 1,
    database: "myDatabase",
    collection: "myCollection",
    enable: true
})

To enable for all collections in a database:

db.adminCommand({
    modifyChangeStreams: 1,
    database: "myDatabase",
    collection: "",
    enable: true
})

To enable for all collections in all databases:

db.adminCommand({
    modifyChangeStreams: 1,
    database: "",
    collection: "",
    enable: true
})

Verify the current state:

db.adminCommand({listChangeStreams: 1})

Note: Replace myDatabase and myCollection with your own values.

Resume token expired (events purged)

When you attempt to resume a change stream using resumeAfter with a previously saved token, the cursor either:

  • Returns no events and tryNext() returns null indefinitely
  • Throws an error indicating the resume token was not found
  • Starts from the current point instead of from the saved position, resulting in missed events

Change stream events are retained for a limited duration. The default retention is 3 hours. If your application was offline longer than the retention window, the resume token references events that have already been deleted from the change stream log.

  1. To increase the retention period (maximum 7 days), update it in the AWS Management Console or run the following command:

    aws docdb modify-db-cluster-parameter-group \
        --db-cluster-parameter-group-name myParameterGroup \
        --parameters "ParameterName=change_stream_log_retention_duration,ParameterValue=86400,ApplyMethod=immediate"

    Note: The value is in seconds. 86400 = 24 hours. The maximum value is 604800 (7 days).

  2. If the resume token is already expired, use startAtOperationTime (Amazon DocumentDB 4.0+) to resume from a known timestamp instead. The startAtOperationTime and resumeAfter options are mutually exclusive:

    stream = coll.watch(start_at_operation_time=timestamp)

    Alternatively, on Amazon DocumentDB 5.0 (Engine Patch Version 3.0.11800 and later), use postBatchResumeToken to resume more efficiently. Unlike a regular resume token, postBatchResumeToken corresponds to the oplog entry the change stream has scanned up to on the server. Resuming with postBatchResumeToken skips scanning of unmatched oplog entries and avoids CPU spikes.

  3. To prevent token expiry in the future, implement checkpoint persistence for resume tokens. Store the latest resume token in a durable store. This allows your application to recover quickly after restarts without exceeding the retention window.

Reading from a replica instance (incorrect read preference)

On Amazon DocumentDB 4.0 and lower versions, opening a change stream on a replica (reader) instance returns an error or the cursor hangs indefinitely with no events returned. For these versions, change streams can be opened only from the primary instance.

Event size exceeds 16 MB

When reading from a change stream, you receive the following error if the event exceeds the maximum payload size of 16 MB:

DocumentTooLarge: BSON document too large (17825951 bytes) - the connected server supports BSON document sizes up to 16793598 bytes.

Or, when an update causes the document to exceed 16 MB, you receive:

DocumentTooLarge: Resulting document after update is larger than 16777216

If the total size of a change stream event (change data + full document when using fullDocument: "updateLookup") exceeds 16 MB, the read fails. Amazon DocumentDB enforces a 16 MB maximum BSON document size.

To resolve this issue:

  • Avoid storing documents larger than 16 MB in collections monitored by change streams. Consider restructuring large documents by splitting them into smaller sub-documents across related collections.

  • Switch from fullDocument: "updateLookup" to the default mode. This returns only the changed fields instead of the full document. Fetch the full document separately if needed:

    # Default mode - only returns change delta
    stream = coll.watch()
    
    # Instead of:
    stream = coll.watch(full_document='updateLookup')

Long-running write operations stalling events

You observe the following symptoms:

  • cursor.tryNext() returns null repeatedly

  • cursor.next() blocks indefinitely with the warning:

    Warning: If there are no documents in the batch, next will block. Use tryNext if you want to check if there are any documents without waiting.
    

Here, the change stream appears frozen with no new events and no error is thrown. A long-running write operation such as updateMany or deleteMany temporarily stalls the writing of change stream events until the operation completes.

To resolve this issue:

  • Break large bulk write operations into smaller batches.

  • Use tryNext() instead of next() to avoid indefinite blocking:

    let doc = cursor.tryNext()
    if (doc !== null) {
        processEvent(doc)
    }
  • Set appropriate timeouts on your change stream cursor using maxAwaitTimeMS.

Duplicate events after resume / CPU spike on resume

You observe the following symptoms:

  • Duplicate records appearing in downstream systems after resuming a change stream following an application crash or unexpected shutdown
  • A spike in CPU usage when resuming with an old resume token
  • Degraded database performance during change stream resume
  • Same events processed multiple times in your application

When you resume a change stream with a regular resume token, the database must scan all the oplog entries between the token's timestamp and the current time. If the time gap is large or there are many unmatched oplog entries, this generates many internal queries, each scanning a small period of time. This causes a spike in CPU usage and degrades database performance.

Additionally, if your application saves the resume token infrequently (for example, only every N events), and a crash occurs between checkpoints, events between the last saved token and the crash point are re-delivered when the stream resumes. This causes duplicate processing.

To resolve this issue:

  1. Use postBatchResumeToken instead of per-event resume tokens (Amazon DocumentDB 5.0, Engine Patch Version 3.0.11800 and later). Unlike a regular resume token that always corresponds to an oplog entry reflecting an actual event, postBatchResumeToken corresponds to the oplog entry the change stream has scanned up to on the server, which is not necessarily a matching change. Resuming with the last postBatchResumeToken skips the scanning of unmatched oplog entries, avoiding CPU spikes.

    output = db.command({
        "aggregate": "myCollection",
        "pipeline": [{"$changeStream": {}}],
        "cursor": {"batchSize": 1}
    })
    
    post_batch_resume_token = output['cursor']['postBatchResumeToken']
    stream = db.watch(full_document='updateLookup', resume_after=post_batch_resume_token)

    Note: Replace myCollection with your collection name.

  2. Persist the resume token after every event to minimize the duplication window.

  3. Implement idempotent processing by using the event's _id or documentKey as a deduplication key, and use upserts instead of inserts in downstream systems.

Related information

Using change streams with Amazon DocumentDB

Event-driven programming with Amazon DocumentDB and Java

Monitoring Amazon DocumentDB with CloudWatch

Connecting to Amazon DocumentDB as a replica set

AWS
SUPPORT ENGINEER

published 2 months ago233 views