How to implement reconnecting in Payload CMS if the db connection is disconnected? #16182
-
|
After a long time of inactivity of the Payload CMS queries to the database, I see an error on every new request to the database: Restarting the Payload instance helps resolve this issue. But it would still be great to have automatic reconnection to the database if the connection is disconnected. Maybe there is an option to enable automatic reconnection, instead of throwing an error? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
|
Hey @MurzNN absolutely there is! I took a quick breeze through the mongo docs and it looks like there is a solution. For reference: https://www.mongodb.com/docs/manual/reference/connection-string-options/ Payload passes
If you're running behind a proxy (AWS, nginx, etc.) that closes idle TCP connections after a timeout, you may also need to set If none of the above helps, it's worth checking whether the MongoDB server (or Atlas) has an idle connection timeout configured on its side. |
Beta Was this translation helpful? Give feedback.
-
|
If the MongoDB connection drops after inactivity, that's the driver's // payload.config.js
module.exports = {
mongo: {
uri: process.env.MONGO_URI,
options: {
connectOptions: {
serverSelectionTimeoutMS: 30000, // default is 30s
autoReconnect: true,
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
},
},
},
};Also make sure your MongoDB server isn't killing idle connections - set |
Beta Was this translation helpful? Give feedback.
If the MongoDB connection drops after inactivity, that's the driver's
serverSelectionTimeoutMSkicking in. Payload just forwards whatever you put inconnectOptions, so bump that timeout and enableautoReconnect:Also make sure your MongoDB server isn't killing idle connections - set
maxIdleTimeMS: 0if you control the server, or use a connection pooler like ProxySQL/Atlas. If you're on a cloud provider, check their idle timeout setti…