MongoDB Cluster Connection Issues and Configuration Improvements

MongoDB Cluster Connection Issues and Configuration Improvements

This case examines the MongoDB connection configuration in a cluster environment based on an incident caused by an AWS EKS deployment overlapping with a MongoDB Atlas version upgrade.AWS EKS deployment and MongoDB Atlas version upgrade1. Unexpected incident

1. Unexpected incident

While deploying a system using MongoDB Atlas to AWS EKS, connections to some MongoDB clusters did not complete, so the new WAS failed to start normally. It was not that an error occurred immediately and the process terminated. The application waited during initialization and was unable to process actual requests.

As Kubernetes Health Check and the deployment procedure proceeded in this state, existing service instances were terminated, which caused the incident to expand. In this response, we analyzed the cause with a focus on the MongoDB connection process rather than Health Check itself. Upon reviewing the events at the time of the incident, we found that a MongoDB Atlas version upgrade was in progress at the same time as the deployment.

2. Atlas version upgrade overlapped with the deployment timing

A MongoDB cluster consists of multiple members, and during maintenance or a version upgrade, the availability of some members may temporarily change. If the Primary is affected, a new Primary may also be elected. This is a normal state change that must be considered in cluster operations, and the driver must be able to identify the topology and select an available server.

In this case, the initial connection time of the new WAS overlapped with the node transition timing in Atlas. The existing WAS already had a connection pool and topology information, and if Atlas had been in a normal state, the new WAS would most likely have connected as usual. Therefore, we did not attribute the cause simply to Atlas maintenance. Because maintenance, failover, and Primary changes can occur in a cluster environment, a new application must also be able to tolerate a state in which some members are unavailable.

We also considered the possibility that connection issues with some cluster members had been masked without causing a service outage. If a connection could be made to another available member, the problem might not have surfaced until the node transition caused by the update overlapped with the new WAS's initial connection and appeared as a startup problem.

3. Identifying the issue with the time taken to determine connection failure

The MongoDB Java Driver has a default connection-related timeout, but the default value does not mean that it is suitable for the service's startup and fault-tolerance requirements. During the initial connection, DNS lookup, TCP connection, and TLS processing, topology discovery, and server selection occur sequentially. If the waits at each stage overlap, the WAS may remain in the startup state longer than expected.

The focus of the analysis was not "Why did a particular node temporarily become unavailable?" but rather "Why was the new WAS unable to determine connection success or failure within an appropriate amount of time in that situation?". Accordingly, we explicitly configured the connection timeout and server selection policy.

4. Configuration applied to the actual production environment

4.1 Adjusting the JVM DNS cache duration

spec:
  template:
    spec:
      containers:
        - name: serviceName
          env:
            - name: JAVA_TOOL_OPTIONS
              value: "-Dsun.net.inetaddr.ttl=5" 

In JAVA_TOOL_OPTIONS in deployment.yml, we applied `-Dsun.net.inetaddr.ttl=5`. This setting ensures that the JVM does not retain DNS lookup results for a long time so that changes in the cluster address or DNS status can be reflected relatively quickly. Because `sun.net.inetaddr.ttl` is a System Property that depends on the JDK implementation, you should verify whether it is supported by the JDK in use. In this case, we passed only this property to the JVM as a System Property, without using a separate Security Property.

4.2 Configuring MongoDB Client timeouts and read/write policies

public class MongoCustomConfig
        extends AbstractMongoClientConfiguration {

    @Override
    public MongoClient mongoClient() {
        //
        return getUriMongoClient();
    }

    @Override
    public MongoTemplate mongoTemplate(
            MongoDatabaseFactory databaseFactory,
            MappingMongoConverter converter) {
        //
        MongoTemplate mongoTemplate =
                new MongoTemplate(databaseFactory, converter);

        // [데이터 안정성] 과반수 노드 복제 확인으로 Primary 이탈 시 데이터 롤백 가능성 감소
        mongoTemplate.setWriteConcern(WriteConcern.MAJORITY);

        // [읽기 가용성] Primary 우선, 전환 중에는 Secondary 조회 허용
        mongoTemplate.setReadPreference(
                ReadPreference.primaryPreferred());

        return mongoTemplate;
    }

    private MongoClient getUriMongoClient() {
        //
        ConnectionString connectionString =
                new ConnectionString(dbUri);

        MongoClientSettings settings =
            MongoClientSettings.builder()
                .applyConnectionString(connectionString)
                .applyToSocketSettings(socketBuilder ->
                    socketBuilder
                        // TCP 초기 연결 대기 시간 제한
                        .connectTimeout(3, TimeUnit.SECONDS)

                        // 연결 후 응답 대기 시간 제한
                        .readTimeout(5, TimeUnit.SECONDS)
                )
                .applyToClusterSettings(clusterBuilder ->
                    clusterBuilder
                        // 사용 가능한 Replica Set 노드 탐색 대기 시간 제한
                        .serverSelectionTimeout(
                            5, TimeUnit.SECONDS)
                )
                // MongoDB 버전 변경 시 API 호환성 확인
                .serverApi(ServerApi.builder()
                    .version(ServerApiVersion.V1)
                    .strict(true)
                    .deprecationErrors(true)
                    .build())
                .build();

        return MongoClients.create(settings);
    }
}

5. Purpose of applying each setting

`connectTimeout`limits the time spent waiting to establish a TCP connection with each individual server. In this environment, it was set to 3 seconds so that the client would not wait too long for an unreachable server. `readTimeout`limits the time spent waiting for a server response after a connection is established and was set to 5 seconds. If normal queries frequently exceed this value, the queries and indexes should be reviewed before increasing the Timeout.

`serverSelectionTimeout`limits the time the driver spends finding a server in the current cluster to process a request. It was set to 5 seconds to account for Primary transitions or the temporary departure of some members. The three Timeouts have different targets. `connectTimeout` controls the connection to an individual server, `serverSelectionTimeout`controls server selection within the cluster, and `readTimeout` controls the wait for a response after connection. The 3-second and 5-second values used here are tailored to the operating environment and are not recommended values for every system.

`WriteConcern.MAJORITY`determines a write to be successful when it has been replicated to a majority of members, reducing the risk of data rollback during failover. `ReadPreference.primaryPreferred()`prioritizes data freshness for normal reads while allowing reads from a Secondary during a brief period when the Primary is unavailable. However, large-volume bulk and batch readswhere distributing the load from the Primary is important may use `secondaryPreferred` or another separate read policy. Read Preference should be selected according to the characteristics of the service. The strict/deprecationErrors settings in Server API V1 are not failover features, but they help identify API compatibility issues when the server version changes.

6. Expanding the scope to other maintenance tasks

While reviewing this case, we also considered maintenance situations other than version upgrades. When actual disk space reclamation is required after deleting a large amount of data, operations such as `compact` may be considered depending on the environment and version. The key point is not a specific maintenance feature, but that the roles or availability of cluster members may change during an operation. Version upgrades, Primary transitions, and node maintenance can all appear to the application as the temporary inability to connect to some servers.

Therefore, rather than handling exceptions for each individual operation, it is important to configure the connection policy so that the service either continues operating when some cluster members are excluded or fails clearly within a specified time.

7. Expanded impact during Health Check and deployment

The new WAS had not completed its MongoDB connection when the Kubernetes Health Check and deployment proceeded, causing the existing service to be terminated and expanding the scope of the outage. However, in the actual response, the Health Check settings were not changed. The direct improvement targetswere the MongoDB connection Timeout, server selection, DNS cache, and read/write policies.

8. Results of applying the settings and lessons from the case

The same problem has not recurred since the settings were applied. However, because this was a rare condition that occurs only when deployment overlaps with changes in cluster status, the absence of recurrence alone cannot conclusively establish the effectiveness. The key improvement was to explicitly define the policy for the connection wait time the service can tolerate and for changes in cluster status rather than relying only on the driver's and JVM's default behavior.

Although this incident occurred in Atlas, the lesson is not limited to Atlas. In MongoDB systems composed of multiple members, such as a Replica Set, maintenance, failover, and Primary changes can temporarily make some members unavailable. Using a high-availability database does not mean that the application's availability is automatically guaranteed. The client must be able to select an appropriate server and determine success or failure within a limited time. To achieve this, it is necessary to review the connection Timeout, server selection, DNS cache, and Read/Write policies together.

Daniel(K)

Site footer