Fix “MongooseError: Operation buffering timed out after 10000ms”
On this page
- What “buffering timed out after 10000ms” means
- Cause 1: Queries run before the connection is ready
- Cause 2: The connection itself fails
- Cause 3: Two copies of Mongoose
- Cause 4: Serverless functions and tests
- Fail fast: turn buffering off
- Don’t just raise the timeout
- Quick checklist
- See the connection state while you debug
- When the error appears in an app that was working
- A connection module you can reuse
- Frequently asked questions about “buffering timed out after 10000ms”
- Oh hi there 👋It’s nice to meet you.
- 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.
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_URIdefined? Logtypeof process.env.MONGODB_URI. If it isundefined, your.envfile isn’t loaded: importdotenv/configbefore 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 withmongoose.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
- Is
await mongoose.connect(…)called, and finished, before any query orapp.listen? - Does awaiting it reveal a connection error? Fix that error first.
- Is
process.env.MONGODB_URIdefined where the app runs? - On Atlas, is your IP allowed, and is the cluster running?
- Does
npm ls mongooseshow a single copy? - 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.




