Error
Error Code: 279

MongoDB Error 279: Client Connection Lost

📦 MongoDB
📋

Description

Error 279, 'Client Disconnect', indicates that a client application unexpectedly lost its connection to the MongoDB server. This typically occurs when the network connection is interrupted, the client application terminates abruptly, or the server becomes unavailable.
💬

Error Message

Client Disconnect
🔍

Known Causes

4 known causes
⚠️
Unstable Network Connection
The client's network path to the MongoDB server experienced an interruption, such as a firewall blocking traffic, a router failure, or general network instability.
⚠️
Client Application Termination
The client application either crashed, was forcibly closed, or explicitly shut down its connection to MongoDB without proper session termination.
⚠️
MongoDB Server Unavailability
The MongoDB server unexpectedly shut down, restarted, became overloaded, or was otherwise unresponsive, leading to active client connections being dropped.
⚠️
Connection Timeouts
Either the client or the MongoDB server closed an idle connection due to configured timeout settings, such as `socketTimeoutMS` or application-level timeouts.
🛠️

Solutions

4 solutions available

1. Check Network Connectivity and Firewall Rules easy

Verify that the MongoDB server is reachable from the client machine and that no firewalls are blocking the connection.

1
From the client machine experiencing the error, try to ping the MongoDB server's IP address or hostname.
ping your_mongodb_server_ip_or_hostname
2
Attempt to connect to the MongoDB server using the `mongo` shell from the client machine. This helps isolate if the issue is with your application or a general network problem.
mongo --host your_mongodb_server_ip_or_hostname --port 27017
3
Review firewall rules on both the client and server machines. Ensure that the MongoDB port (default is 27017) is open for inbound connections on the server and outbound connections on the client.
For Linux (ufw):
sudo ufw status
sudo ufw allow 27017/tcp

For Windows Firewall:
Open 'Windows Defender Firewall with Advanced Security' and check inbound/outbound rules for port 27017.
4
If using cloud providers (AWS, Azure, GCP), check their respective security group or network access control list (NACL) rules to ensure the MongoDB port is allowed.
Consult your cloud provider's documentation for specific instructions on managing security groups/NACLs.

2. Inspect MongoDB Server Logs for Disconnect Reasons medium

Examine the MongoDB server's log files to identify the specific reason for client disconnections.

1
Locate the MongoDB server log file. The default location varies by operating system and installation method. Common locations include:
- Linux: `/var/log/mongodb/mongod.log`
- Windows: `C:\Program Files\MongoDB\Server\<version>\log\mongod.log`
- macOS: `/usr/local/var/log/mongodb/mongo.log`
See instruction for typical paths.
2
Search the log file for entries related to client disconnections around the time the error occurred. Look for messages containing keywords like 'disconnect', 'connection closed', 'client disconnected', or error codes.
tail -f /var/log/mongodb/mongod.log | grep 'disconnect'

Or use a text editor to search for relevant terms.
3
Analyze the log messages for specific causes. Common causes indicated in logs include:
- Network interruptions
- Client application crashes or restarts
- Server-side issues like resource exhaustion or unhandled exceptions
- MongoDB server restarts or shutdowns
Example log entry indicating a client disconnect due to network issues:
'2023-10-27T10:30:00.123+0000 I NETWORK  [conn123] connection from 192.168.1.100:54321 closed: socket error code 104'

3. Review Client Application Connection Management medium

Ensure the client application properly handles connections, including retries and timeouts, and that it's not prematurely closing connections.

1
Examine the connection string or configuration used by your client application. Verify that the host, port, and authentication details are correct.
Example connection string (Node.js):
const uri = "mongodb://username:password@host:port/database?retryWrites=true&w=majority";
2
Implement or verify connection pooling in your application. Connection pooling can improve performance and resilience by reusing existing connections instead of establishing new ones for every operation.
Example (Node.js with Mongoose):
const mongoose = require('mongoose');
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });
3
Configure appropriate connection timeouts and socket timeouts in your MongoDB driver. This prevents the application from holding onto connections that are no longer valid.
Example (Node.js with Mongoose):
mongoose.connect(uri, {
  serverSelectionTimeoutMS: 5000, // Timeout after 5s instead of 30s
  connectTimeoutMS: 10000 // Connect timeout in ms
});
4
Implement retry logic for connection attempts and operations. If a connection is lost, your application should attempt to reconnect gracefully.
Example (conceptual retry logic):
async function performOperationWithRetry(operation) {
  let retries = 3;
  while (retries > 0) {
    try {
      return await operation();
    } catch (error) {
      if (error.code === 279 && retries > 1) {
        console.log(`Connection lost, retrying... (${retries - 1} attempts left)`);
        await new Promise(resolve => setTimeout(resolve, 1000 * (4 - retries))); // Exponential backoff
        retries--;
      } else {
        throw error;
      }
    }
  }
}

4. Monitor Server Resources and Health advanced

Ensure the MongoDB server has sufficient resources (CPU, memory, disk I/O) and is not experiencing performance degradation that could lead to connection instability.

1
Monitor the MongoDB server's CPU utilization. High CPU usage can make the server unresponsive and lead to dropped connections.
Use system monitoring tools like `top`, `htop` (Linux/macOS), or Task Manager (Windows).
2
Monitor the server's RAM usage. If the server is running out of memory, it can lead to swapping and significant performance degradation.
Use system monitoring tools like `free -h` (Linux), `top` (macOS), or Resource Monitor (Windows).
3
Check disk I/O performance. Slow disk operations, especially during writes, can cause the server to lag and drop connections.
Use tools like `iostat` (Linux) or Resource Monitor (Windows).
4
Use MongoDB's built-in performance monitoring tools, such as `db.serverStatus()` and `db.stats()`, to identify potential bottlenecks.
Connect to the MongoDB shell and run:
`db.serverStatus()`
`db.stats()`
5
If using MongoDB Atlas, leverage the Atlas monitoring dashboards for detailed insights into server performance and resource utilization.
Navigate to the 'Metrics' tab in your MongoDB Atlas project.
🔗

Related Errors

5 related errors