How to Fix MongoDB Error 222 (CloseChangeStream)

Published
Length
3 min read

Luis Felipe Dias

All posts

The database raises mongodb error 222 when the server must close an active change stream. You fix this CloseChangeStream error by catching the event and reopening the stream from a token. Apps use change streams to watch real-time data changes across collections or databases. When the cluster state shifts or a collection drops, the server halts the cursor. Your app must handle this signal and restart the stream cleanly. Root causes of mongodb error 222 in production In the official error spe

Your coding agents run with your access.

Claude Code reaches prod with a developer's credentials, and approval prompts get clicked through. hoop.dev checks every query, masks sensitive data, and holds risky changes for a human.

The database raises mongodb error 222 when the server must close an active change stream. You fix this CloseChangeStream error by catching the event and reopening the stream from a token.

Apps use change streams to watch real-time data changes across collections or databases. When the cluster state shifts or a collection drops, the server halts the cursor. Your app must handle this signal and restart the stream cleanly.

Root causes of mongodb error 222 in production

In the official error spec, code 222 maps to the CloseChangeStream name. The database engine sends this signal when it cannot keep a change stream cursor open. This happens during normal cluster operations or schema changes.

A common trigger is a collection drop or rename while a stream watches that resource. When the target collection changes, the server invalidates the stream and closes the cursor. Shard splits, chunk moves, or primary stepdowns also force the engine to close open streams.

Permission changes during an active session can also stop a stream. MongoDB grants access through roles that define allowed actions on specific resources. A role applies to its defined database and can grant access down to a collection level. If an admin revokes the changeStream action from a user role, the active stream stops.

Network drops between the client driver and the replica set also play a role. If a node steps down during maintenance, the server closes streams tied to that node. Understanding whether a schema change, cluster event, or role change caused the closure guides your fix.

How to diagnose and fix CloseChangeStream safely

Start by checking your server logs and app error logs around the timestamp of the failure. Look for collection drop events, shard balancing tasks, or replica set elections at that exact time. These log entries show why the engine sent the CloseChangeStream signal.

Next, check the database roles assigned to the app user. The built-in read role provides read access to all non-system collections in its database. It includes actions like find, listCollections, listIndexes, dbStats, collStats, and changeStream. It does not allow insert, update, remove, or dropCollection actions.

MongoDB Authentication & Authorization + End-to-End Encryption: architecture patterns and best practices

Continue reading? Get the full guide.

Free. No spam. Unsubscribe anytime.

Never grant write roles or admin permissions just to fix a broken change stream. The readWrite role adds actions like insert, update, remove, createCollection, and dropCollection. Your stream consumer only needs the read role to watch data changes safely. Keep user permissions small to protect production data.

Next, update your app logic to handle stream closures cleanly. Store the resume token from each change event your app processes. When code 222 arrives, inspect the last event for an invalidate notification. If a collection dropped, decide if the app should wait or stop watching.

If a cluster election or network blip caused the error, open a new change stream. Pass the saved resume token so the stream picks up right where it stopped. This prevents missed events and keeps your data pipeline running without manual restarts.

Preventing data leaks during change stream debugging

When teams debug broken change streams, engineers often query production collections to inspect recent documents. Raw documents often hold sensitive fields like emails, phone numbers, card numbers, or national IDs. Running broad read queries in production exposes this private data to human eyes.

Teams should apply dynamic data masking on read queries during debugging sessions. Masking rewrites matched fields like emails and card numbers in query results before returning them. Engineers can check document structure and resume tokens while keeping sensitive customer fields protected.

Check MongoDB commands and documents on the wire

MongoDB roles and SCRAM login decide who opens a session. They do not check single commands or redact sensitive fields inside returned documents. With hoop.dev, you run an open-source proxy, a sidecar for your MongoDB, inline in the MongoDB wire protocol. On every command an AI agent or engineer runs against production, hoop.dev decides to pass, mask, block, or hold it for human review.

Before a command runs, hoop.dev guardrails check its effect and refuse banned drops or writes with MongoDB error code 13, or hold risky commands for approval. On the way back, hoop.dev data masking rewrites sensitive fields in returned documents in memory, and every verdict is logged. See the open-source code on GitHub.

Frequently asked questions

What does CloseChangeStream mean in MongoDB?

CloseChangeStream is the official name for error code 222 in the database engine. It means the server closed an active change stream cursor due to an internal event or invalidation.

Which role do I need to run a MongoDB change stream?

The built-in read role grants the changeStream action on non-system collections in its database. You do not need the readWrite role to watch a collection for changes.

How do I resume a change stream after error 222?

Save the resume token from each change event in your app state. When the stream closes, start a new stream using that token to read from the last point.

The query runs. The emails stay hidden.