×
Community Blog Achieve Effortless Load Balancing with Zero Code Changes Using ConnectionStringURI on ApsaraDB for MongoDB

Achieve Effortless Load Balancing with Zero Code Changes Using ConnectionStringURI on ApsaraDB for MongoDB

This article explains the importance of using read/write splitting and load balancing with ApsaraDB for MongoDB to enhance system performance.

Why Read/Write Splitting & Load Balancing Matters

📈 Key Pain Points

● Primary Node Overload: Read-heavy workloads slow down critical write operations.

● Costly Scaling: Manual traffic routing requires code refactoring and downtime.

● Downtime Risks: Single-point failures threaten business continuity.

🔥 Why ApsaraDB for MongoDB ConnectionStringURI + readPreference?

✅ At Least 2x Read Throughput: Automatically divert read traffic to secondary and ReadOnly nodes to reach nearly linearly performance scaling.

✅ Zero-Downtime Failover: Seamless primary-secondary switchover.

✅ No Code Changes: Configure once in 5 minutes — no DevOps overhaul.

1. Architecture: How Intelligent Traffic Routing Works

The ApsaraDB for MongoDB Replica Set architecture uses multiple nodes to achieve high availability and read/write separation.

Node Roles & Responsibilities in ApsaraDB for MongoDB Replica Set

1

Node Type Function
Primary Exclusive write node for strong data consistency. Handles all read and write requests as default.
Secondary Real-time data sync; promotes to Primary during failures.
Hidden Disaster recovery node for secondary and ReadOnly nodes.
ReadOnly Dedicated read nodes; balances traffic via ReadOnly Connection String URI.

Connection Address Comparison & Selection Guide

In production environments, it is an enterprise best practice to use ConnectionStringURI addresses to access instances for load balancing and high availability.

For environments with a certain business scale, there are usually read-only nodes, in which case it is recommended to configure ReadOnly Connection String URI addresses to access instances for read-only applications.

Address Type Nodes Included Function Use Case Benefit
ConnectionStringURI All nodes Supporting both read and write operations. General production workloads High Availability, Read/Write Splitting
ReadOnly Connection String URI ReadOnly nodes only Exclusively used for read operations. Analytics/Reporting 100% Read Isolation

Connection Address Format

mongodb://<username>:<password>@<host1>:<port1>,<host2>:<port2>,...,<hostN>:<portN>/<database>?replicaSet=<replicaSet_value>[&authSource=<authenticationDatabase>][&readPreference=<readPreference_value>][&readPreferenceTags=<readonly_Tags>]

Example:
mongodb://root:PassWard@dds-3nse3296743324f42.mongodb.rds.aliyuncs.com:3717,dds-3nse3xxxxxxxxxxxxx.mongodb.rds.aliyuncs.com:3717,dds-3nse3xxxxxxxxxxxxy.mongodb.rds.aliyuncs.com:3717,dds-3nse3xxxxxxxxxxxxz.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-87961907

Steps to Obtain Connection Address

1.  Access the instance list, select the region, and find the desired instance.

2.  Click the instance ID, enter the details page, and configure the whitelist.

Note: Never use 0.0.0.0/0 for production environment.

2

3.  Click the Database Connection from the instance details navigation bar to see endpoint options. You will be able to see all connection addresses as below on the console with sample connection strings.

3

Recommended Connection Methods

Programmatic Connection (by MongoDB Drivers): Recommended! Using official MongoDB drivers for programming languages (like Node.js, Python, Java, etc., as shown below) facilitates the connection with all the necessary parameters, ultimately leading to a more effective and efficient interaction with MongoDB databases in production settings.

4

Mongo Shell Connection: Not recommended. Does not support for certain parameters like readPreference and readPreferenceTagsin ReadOnly ConnectionStringURI.

Reasons Why Mongo Shell Is Not Recommended:

1. Not Built for Production Use:

  • The Mongo Shell is primarily a command-line client intended for development and administrative tasks. It’s not designed for production environments where performance optimization and extensive configurations are required.

2. Limited Connection String Options:

  • The Mongo Shell does not support certain connection string URI parameters that are essential for optimizing data access and performance. For instance, readPreference defines how MongoDB clients route read operations to members of a replica set. Not having this option means users cannot specify whether they want to read from primary, secondary, or other members, leading to potential performance issues.

3. Inefficient Use of Resources:

  • Without the ability to set readPreference, connections may always route queries to the primary node, which can lead to increased load on that node while other nodes remain underutilized. This defeats the purpose of having a distributed database system designed for scalability and fault tolerance.

4. Read Balancing:

  • In environments with multiple replica set members, readPreference allows clients to balance read requests across different nodes, improving performance and reducing latencies. The Mongo Shell’s limitations can lead to uneven workloads and potential bottlenecks.

5. Tag-Based Read Preference:

  • The absence of readPreferenceTags means that users cannot control which secondary nodes to read from based on attributes (tags) assigned to those nodes. This feature is useful for routing operations based on data locality or specified requirements, such as geographic location or node capacity.

6. Lack of Robust Error Handling:

  • While the Mongo Shell can perform many operations, it lacks the advanced error handling and connection management features found in more complete MongoDB drivers and libraries used for applications.

Python Example for Read/Write Splitting & Load Balancing

1. Install the PyMongo driver

pip install pymongo

5

2. Configure the high-availability address (ConnectionStringURI) with flexible parameter use.

6

It is worth noting that the use of readPreference and readPreferenceTags parameters in the connection address can be very flexible, according to specific scenarios, there are many different combinations of the two parameters. You can refer to our documentation guide for more details.

🔍 Parameter Guide >

readPreference=secondary: Read data only from secondary and read-only nodes. This means that when both the secondary and read-only nodes are abnormal, the read will fail, it will not be automatically routed to the primary node.

readPreferenceTags=role:readonly: Read data only from read-only nodes.

3. Connect and write or read data using Python code.

7

4. Review test data and monitor performance enhancements on the console.

8

Compared to the direct connection to the primary node, the ConnectionStringURI address connection mobilizes all of the instance's compute resources to bear the load and automatically performs load balancing, so for a basic ApsaraDB for MongoDB Replica Set instance with only three nodes (Primary node + Secondary node + Hidden node), read performance can be up to 1X faster.

In addition, instance availability can be significantly improved.

3. Simulating HA Failover By Primary-Secondary Switch

1. Run the Python code to continuously read and write data from ApsaraDB for MongoDB.

9

2. Perform primary-secondary switch in the console.

10
11

3. Observe the application for read/write errors.

12

You can see that when we manually switch primary, all writes and reads auto-redirect with zero errors.

With ConnectionStringURI, operations are unaffected by primary-secondary switches, ensuring business continuity and performance improvement.

Conclusion

Using ConnectionStringURI to access ApsaraDB for MongoDB ensures business continuity, high stability, and performance enhancement, making it the best practice for enterprises.

4. Real-World Impact

Ideal Scenarios

● 🛒 E-Commerce Flash Sales: Isolate query traffic during spikes to protect checkout systems.

● 📊 Real-Time Analytics: Offload complex aggregations to ReadOnly nodes.

● 🌍 Global Apps: Use readPreferenceTags for geo-localized reads.

5. You Next Step

Unlock the full potential of your database operations with ApsaraDB for MongoDB. Enhance your system's reliability and speed without any initial cost. Sign up for a free trial today and explore how our solutions can transform your business operations. Or, if you're ready to take the next step, contact us to discuss tailored solutions that meet your specific needs.

13

0 1 0
Share on

ApsaraDB

482 posts | 138 followers

You may also like

Comments

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

Get Started for Free Get Started for Free