MongoDB

Fix “MongooseError: Operation buffering timed out after 10000ms”

Fix “MongooseError: Operation buffering timed out after 10000ms”
On this page
  1. What “buffering timed out after 10000ms” means
  2. Cause 1: Queries run before the connection is ready
  3. Cause 2: The connection itself fails
  4. Cause 3: Two copies of Mongoose
  5. Cause 4: Serverless functions and tests
  6. Fail fast: turn buffering off
  7. Don’t just raise the timeout
  8. Quick checklist
  9. See the connection state while you debug
  10. When the error appears in an app that was working
  11. A connection module you can reuse
  12. Frequently asked questions about “buffering timed out after 10000ms”
  13. Oh hi there 👋It’s nice to meet you.
  14. Sign up to receive awesome content in your inbox.

Your API hangs for ten seconds and then fails with MongooseError: Operation `users.find()` buffering timed out after 10000ms. The message is confusing because it talks about “buffering”, not about a connection. But that is exactly what it means: Mongoose was holding your query, waiting for a database connection that never became ready. This guide explains why, with every error reproduced on Mongoose 9.12, and shows the fix for each cause.

What “buffering timed out after 10000ms” means

Mongoose lets you call model functions such as User.find() before the connection is ready. It stores, or buffers, those operations and runs them once connected. This is convenient, but it hides connection problems: if the connection never succeeds, the query simply waits. After bufferTimeoutMS, 10,000 milliseconds by default, Mongoose gives up and throws this error.

Why Mongoose reports buffering timed outA query that runs before the connection is ready waits in Mongoose’s buffer; if no connection arrives within 10 seconds, it fails.Your codeUser.find()MongoosebufferMongoDBnot connectedUser.find()no connection yetwaits in bufferup to 10 secondsbuffering timed outafter 10000msawait mongoose.connect()connect firstUser.find()connection readyquery sentresults returned
The query waits in Mongoose’s buffer for a connection; with none after 10 seconds, it fails.

In testing, running a query without connecting at all produced the error exactly, and the connection state confirmed the cause:

MongooseError: Operation `users.find()` buffering timed out after 10000ms

mongoose.connection.readyState   // 0  (0 = disconnected, 1 = connected, 2 = connecting)

So the real question is always: why is there no connection? There are four common answers.

Cause 1: Queries run before the connection is ready

The most common cause is starting the server, or running a script, without waiting for mongoose.connect():

// ❌ connect is not awaited, and its errors are not handled
mongoose.connect(process.env.MONGODB_URI);
app.listen(5000);

// ❌ a script that queries immediately and never connects
const users = await User.find();

Connect first, then start accepting requests:

// ✅ server.js
import 'dotenv/config';
import mongoose from 'mongoose';
import app from './app.js';

try {
  await mongoose.connect(process.env.MONGODB_URI);
  console.log('MongoDB connected');
  app.listen(process.env.PORT ?? 5000, () => console.log('API ready'));
} catch (err) {
  console.error('Could not connect to MongoDB:', err.message);
  process.exit(1);
}

If the connection fails, the app now stops immediately with a clear message instead of accepting requests that will all time out. One-off scripts, such as seeders and migrations, need the same await mongoose.connect() at the top and await mongoose.disconnect() at the end.

Cause 2: The connection itself fails

If connect() can’t reach the database and its error is ignored, every later query buffers and times out. Awaiting the connection reveals the true error. In testing, pointing at a port with no database gave:

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27999

That is a different, more useful error. Check these in order:

  • Is MONGODB_URI defined? Log typeof process.env.MONGODB_URI. If it is undefined, your .env file isn’t loaded: import dotenv/config before anything else, and check the file is in the folder you run the app from.
  • Is the connection string valid? Special characters in the password, such as @ or #, must be URL-encoded. The MongoDB connection string checker finds these mistakes.
  • Is local MongoDB running? See fixing MongooseServerSelectionError: ECONNREFUSED.
  • Using MongoDB Atlas? Add your current IP address under Network Access. On hosting platforms with changing IPs, allow the platform’s addresses. A paused free cluster must be resumed first.

Cause 3: Two copies of Mongoose

A subtle cause: your models are registered on one copy of Mongoose, while a different copy made the connection. The copy holding your models is never connected, so its queries buffer forever. This happens when:

  • a shared package or a second project folder has its own node_modules/mongoose;
  • a monorepo installs two different Mongoose versions;
  • you create a separate connection with mongoose.createConnection() but define models with mongoose.model(), which belong to the default connection.

Check with npm ls mongoose: it should list exactly one copy. With createConnection(), define models on that connection instead:

const conn = await mongoose.createConnection(process.env.MONGODB_URI).asPromise();
const User = conn.model('User', userSchema);   // ✅ model belongs to the connection that is open

Cause 4: Serverless functions and tests

In serverless environments, such as Vercel or AWS Lambda, each cold start runs your code fresh, and a handler can run before a connection exists. Cache the connection promise and await it in every handler:

let connecting;
export function connectDB() {
  connecting ??= mongoose.connect(process.env.MONGODB_URI);
  return connecting;
}

export default async function handler(req, res) {
  await connectDB();
  res.json(await User.find().limit(20).lean());
}

In tests, connect in beforeAll and disconnect in afterAll. A test file that imports models but never connects produces exactly this timeout.

Fail fast: turn buffering off

You can make Mongoose report a missing connection immediately instead of after ten seconds:

mongoose.set('bufferCommands', false);

In testing, the same query then failed in 0 ms with a much clearer message:

MongooseError: Cannot call `orders.find()` before initial connection is complete if `bufferCommands = false`.

This is useful in development, because the mistake shows up instantly and names the real problem. If you prefer to keep buffering, you can shorten the wait with mongoose.set('bufferTimeoutMS', 3000).

Don’t just raise the timeout

A common “fix” is increasing bufferTimeoutMS or serverSelectionTimeoutMS. That only makes users wait longer for the same failure. Raise timeouts only when the database is genuinely reachable but slow to accept connections, which is rare. Fix the missing connection instead.

Quick checklist

  1. Is await mongoose.connect(…) called, and finished, before any query or app.listen?
  2. Does awaiting it reveal a connection error? Fix that error first.
  3. Is process.env.MONGODB_URI defined where the app runs?
  4. On Atlas, is your IP allowed, and is the cluster running?
  5. Does npm ls mongoose show a single copy?
  6. Are models defined on the connection that is actually open?

See the connection state while you debug

Mongoose emits events as its connection changes. Logging them shows immediately whether a connection was ever made:

mongoose.connection.on('connected', () => console.log('MongoDB connected'));
mongoose.connection.on('disconnected', () => console.warn('MongoDB disconnected'));
mongoose.connection.on('error', (err) => console.error('MongoDB error:', err.message));

In testing against a port with no database, the events were connecting, then disconnected, and connect() rejected with MongooseServerSelectionError. The connected event never fired, which is the whole story behind the buffering timeout.

When the error appears in an app that was working

The same message can appear hours after a successful start. If the database becomes unreachable, because of a network problem, an Atlas maintenance restart or a paused cluster, Mongoose keeps trying to reconnect in the background and buffers new operations meanwhile. Requests made during that window wait and then time out. This is expected behaviour; what matters is that your app recovers by itself when the database returns, which Mongoose handles, and that users get a quick, honest error instead of a ten-second hang.

A health check route makes the state visible to you and to your hosting platform’s monitoring:

app.get('/health', (req, res) => {
  const dbReady = mongoose.connection.readyState === 1;
  res.status(dbReady ? 200 : 503).json({ status: dbReady ? 'ok' : 'database unavailable' });
});

Combined with a shorter serverSelectionTimeoutMS, for example 5000, failed connections surface in seconds rather than the default thirty.

A connection module you can reuse

Putting the connection logic in one file keeps every entry point, the server, scripts and tests, consistent:

// db.js
import mongoose from 'mongoose';

export async function connectDB(uri = process.env.MONGODB_URI) {
  if (!uri) throw new Error('MONGODB_URI is not set');
  if (mongoose.connection.readyState === 1) return mongoose.connection;
  await mongoose.connect(uri, { serverSelectionTimeoutMS: 5000 });
  return mongoose.connection;
}

export const disconnectDB = () => mongoose.disconnect();

The explicit check for a missing MONGODB_URI turns the most common deployment mistake into an instant, readable error. Import connectDB wherever your code starts: await it before app.listen(), at the top of seed scripts, and in your tests’ setup. With one place that connects, there is one place to look when something goes wrong.

Frequently asked questions about “buffering timed out after 10000ms”

Why does it take exactly 10 seconds to fail?

Mongoose waits bufferTimeoutMS, 10,000 milliseconds by default, for a connection before giving up on a buffered operation.

Why does it work locally but fail after deployment?

Usually the environment variable isn’t set on the server, or MongoDB Atlas doesn’t allow the server’s IP address. Await the connection and log its error to see which.

Should I disable bufferCommands in production?

It is a reasonable choice: errors appear immediately instead of after a delay. Just make sure the app connects before it starts handling requests.

Does this error mean my query is slow?

No. The query was never sent to MongoDB. It was waiting for a connection. Slow queries produce different errors and are fixed with indexes.

Can I use mongoose.connect without await?

You can, because Mongoose buffers operations until it connects. But if the connection fails, you won’t see why, and every query will time out. Awaiting it, or adding a .catch(), surfaces the real error.

Is buffering timed out the same as a connection timeout?

No. A connection timeout comes from the driver failing to reach the server. Buffering timed out comes from Mongoose giving up on an operation that was waiting for a connection. The second is usually a symptom of the first.

Do I need to connect in every file that uses a model?

No. Connect once when the app starts. Every model defined with mongoose.model() shares that default connection.

logo

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox.

We don’t spam! Read our privacy policy for more info.

Saurabh

Saurabh Pathak is an AI engineer and MERN stack developer, and the founder of mernstackdev.com. He builds open-source projects such as the Haat gateway and MCP safety tooling, and he writes hands-on tutorials on React, Node.js, MongoDB and AI agents. He cares most about code that works in production.