- Error code
- server-selection-timeout
- Product
- MongoDB
- Versions
- Current MongoDB drivers (Node.js, Python, Java, C#, Go); any server version
- Category
- Replication & Connectivity
- Last reviewed
- 24 October 2026
On this page
What it means
A server selection timeout means your driver could not find a suitable MongoDB server for the operation within serverSelectionTimeoutMS (30 seconds by default): no server answered, or none of those that answered could take the operation, such as no primary for a write.
Before every operation a driver picks a server from its view of the deployment, the topology. Writes need the primary; reads need a server that matches the read preference. If no suitable server appears within serverSelectionTimeoutMS (default 30,000 milliseconds, from the connection string options documentation), the driver gives up and raises its server selection error. There is no MongoDB server error code: the server was never reached, or never offered what the operation needed. Each driver names the error differently: Node.js MongoServerSelectionError, Python ServerSelectionTimeoutError, Java MongoTimeoutException, C# TimeoutException, Go ServerSelectionError.
Read the topology description
Most drivers attach their view of the deployment to the error: PyMongo after Topology Description:, Java and C# after Client view of cluster state is, Go after current topology:. The Node.js driver keeps it on the error's reason property and, when a server reported an error, uses that error's text as the message (which is why the documented form reads connect ECONNREFUSED). Read it in this order:
- Topology type: Unknown means nothing has answered yet; ReplicaSetNoPrimary means members answered but none is primary; Single is a direct connection; Sharded is mongos.
- Each server's type: Unknown with an error means the driver could not connect or its last check failed; a known type (such as RSSecondary) means that server answered.
- Each server's error:
Connection refusedorECONNREFUSEDmeans nothing is listening at that host and port; a time-out usually means a firewall or an IP access list is dropping the connection; a TLS or certificate error means the client and server disagree about TLS; a name resolution error means the host name does not resolve from the client. - The host list: if the servers listed are not the ones in your connection string, the replica set has replaced your seeds with the names in its own configuration, and the client must be able to resolve those too. PyMongo says this directly:
Could not reach any servers in [...]. Replica set is configured with internal hostnames or IPs?
PyMongo also states the case when the servers answered: No primary available for writes (a replica set without a primary) or No replica set members available for replica set name "rs1" (the replicaSet option does not match the set's real name).
Common causes
- The mongod or mongos is not running, or listens on a different host or port than the connection string says.
- The server is bound to localhost only, or a firewall, security group or Atlas IP access list does not allow the client's address.
- The client resolves localhost to the IPv6 address ::1 while the server listens only on IPv4 (documented for Node.js 17 and later).
- The replicaSet name in the connection string does not match the set, or the set's member host names (for example inside Docker) cannot be resolved from the client.
- The replica set has no primary (election, or a majority of members down) and the operation is a write or a primary read.
- TLS is required by the server but not enabled in the client, or the certificate is not trusted.
Diagnose it
Read-only These mongosh commands only read data, indexes, statistics and server state (find, aggregate without $out or $merge, getIndexes, stats, currentOp, rs.status). They do not change data, users or settings, so they are safe to run first.
Print the full error, including the topology description (Python)
from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError
client = MongoClient(uri, serverSelectionTimeoutMS=5000)
try:
client.admin.command("ping")
except ServerSelectionTimeoutError as e:
print(e) # reason, Timeout, then Topology Description The reason and the topology description. Read the topology type and each server's type and error as described above. In Node.js, log err.reason for the same information.
Is the port reachable from the client host?
# PowerShell
Test-NetConnection m1.example.net -Port 27017
# Linux or macOS
nc -vz m1.example.net 27017 A successful TCP connection means the network path is open; a failure or time-out points to a stopped server, a bind setting, a firewall or an IP access list.
Ask one server directly what it is
mongosh "mongodb://m1.example.net:27017/?directConnection=true" --eval "db.hello()" The server's hello reply: setName (compare it with your replicaSet option), hosts (the names clients must resolve), isWritablePrimary and primary. If this connects but the application does not, compare the two connection strings.
Does the replica set have a primary?
rs.status().members.map(m => ({ name: m.name, state: m.stateStr, health: m.health })) Exactly one PRIMARY is expected. No PRIMARY explains timeouts for writes and primary reads while secondaries still answer.
How to fix it
Each fix is labelled with what it changes. Try read-only checks and the least invasive fix first, and test changes outside production.
Make the server reachable at the address in the connection string
Changes configurationStart the server if it is stopped, check its port, and bind it to an interface the client can reach (keeping authentication and TLS on when it is reachable from other hosts). On Atlas, add the client's address to the project's IP access list.
Use the right replica set name and resolvable member names
Client or network sideSet replicaSet to the value of setName from db.hello(). If the members are configured with names the client cannot resolve (for example container names), make those names resolvable from the client; for a single-node test set-up in Docker the documentation describes directConnection=true as an option.
mongodb://m1.example.net:27017,m2.example.net:27017,m3.example.net:27017/?replicaSet=rs0
# development only, single node in Docker
mongodb://localhost:27017/?directConnection=true
Connect over IPv4 when localhost resolves to IPv6 (Node.js)
Client or network sideThe Node.js troubleshooting guide documents connect ECONNREFUSED ::1:27017 when the client uses IPv6 and the server IPv4, and gives family: 4 as a fix (or use 127.0.0.1 in the connection string, or enable IPv6 on the server).
const client = new MongoClient("mongodb://localhost:27017", { family: 4 })
Enable TLS when the server requires it
Client or network sideAdd tls=true (and the CA file if the certificate is not publicly trusted). mongodb+srv connection strings turn TLS on by default.
mongodb://m1.example.net:27017,m2.example.net:27017/?replicaSet=rs0&tls=true&tlsCAFile=/etc/ssl/mongo-ca.pem
Examples
Node.js: nothing listening on localhost
Not reproduced here: no MongoDB server is installed for this site. The form is the one in the Node.js driver's connection troubleshooting page (shown there with a placeholder address); the driver's MongoServerSelectionError takes its message from the server error it recorded (src/error.ts). Without a recorded error the message is "Server selection timed out after 30000 ms" (src/sdam/topology.ts).
const { MongoClient } = require("mongodb")
const client = new MongoClient("mongodb://localhost:27017")
await client.db("shop").command({ ping: 1 })
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
Python: the replicaSet name does not match
Not reproduced here: no MongoDB server is installed for this site. The wording is built by _error_message() in PyMongo's topology_shared.py and the raise in synchronous/topology.py; the topology description follows TopologyDescription.__repr__ and is shortened. The host and set names are illustrative.
client = MongoClient("mongodb://m1.example.net:27017/?replicaSet=rs1") # the set is named rs0
client.shop.orders.find_one()
pymongo.errors.ServerSelectionTimeoutError: No replica set members available for replica set name "rs1", Timeout: 30s, Topology Description: <TopologyDescription id: ..., topology_type: ReplicaSetNoPrimary, servers: []>
Java: the primary is not reachable
Not reproduced here: no MongoDB server is installed for this site. The text follows the sample on the Java driver's connection troubleshooting page and the format string in BaseCluster.java; older driver versions include "after 30000 ms" in the first sentence.
MongoClient client = MongoClients.create("mongodb://localhost:27017/?replicaSet=rs0");
client.getDatabase("shop").getCollection("orders").find().first();
com.mongodb.MongoTimeoutException: Timed out while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=REPLICA_SET, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}}, ...]
How to prevent it
Keep connection strings in configuration, list all members (or use mongodb+srv) with the correct replicaSet name, and check connectivity from each new client environment before deploying.
Log the full error, including the topology description or Node.js reason, so the cause can be read from the first occurrence, and monitor that the replica set always has a primary.
Common questions
What does "Server selection timed out after 30000 ms" mean?
The driver tried for 30 seconds (the default serverSelectionTimeoutMS) to find a server it could use and found none. Read the topology description to see whether servers were unreachable or simply unsuitable, such as no primary.
How do I fix MongoServerSelectionError: connect ECONNREFUSED?
Nothing accepted the connection at that address: start the server, check the port and bind setting, and on Node.js 17 or later check whether localhost resolved to ::1 while the server listens on IPv4.
Should I just increase serverSelectionTimeoutMS?
Only if elections or slow start-ups regularly take longer than the timeout. A longer timeout does not fix an unreachable or misconfigured server; it only makes the error arrive later.
Learn more on CodeWithSQL
Official documentation
- Connection string options (serverSelectionTimeoutMS, replicaSet, directConnection)
- Node.js driver: connection troubleshooting
- Java driver: connection troubleshooting
- Server selection for reads
Last technically reviewed 24 October 2026; examples and diagnostics run on MongoDB 8.0 documentation and source (error_codes.yml r8.0.0); not run locally. Codes and code names are checked against MongoDB's error_codes.yml (8.0); no MongoDB server was available, so the examples were not run locally.