Horizontal Vs Vertical Scaling in MongoDB

Horizontal and vertical scaling are two common strategies used to handle increasing loads or data volumes in databases like MongoDB. MongoDB is a popular open-source, NoSQL database management system that uses a document-oriented data model. It has multiple features like high performance, flexibility, and scalability. In this article, we will talk about its scalability aspect.

Table of Content

  • What is scalability?
  • Horizontal Scaling
  • Vertical Scaling
  • Use Cases
  • Which one to choose?
  • How to do scaling in MongoDB?
  • Difference between of Horizontal and Vertical Scrolling

What is scalability?

Scalability is used to handle large data and heavy traffic on sites. MongoDB, a NoSQL database supports horizontal scaling through sharding and vertical scaling.

Horizontal Scaling

It means scaling out and involves adding more machines or instances to your MongoDB cluster. Each machine in the cluster handles a small amount of the data, distributing the load across multiple servers.

Vertical Scaling

It means scaling up, which involves increasing the resources (CPU, RAM, etc.) of a single machine in your MongoDB deployment. This means upgrading the hardware of your existing server to handle more data and traffic.

Horizontal Scaling

Advantages

  • High performance.
  • Infinite Scalability.
  • Almost no downtime.
  • Increase in fault tolerance.

Disadvantages

  • Increase setup cost.
  • Requires more frequent maintenance.
  • Requires professional for it’s setup as it becomes more complex.

Vertical Scaling

Advantages

  • Simple and easier to maintain.
  • Comparatively cheaper setup.
  • Everything is stored in one machine.

Disadvantages

  • Limited Scalability: There’s a hardware limit to how much you can scale a single server.
  • Higher Costs: High-end servers can be very expensive.
  • Single Point of Failure: If the server fails, the entire database becomes unavailable.

Use Cases

Horizontal Scaling:

  • Large scale applications: Social media platforms, e-commerce websites, and applications with rapidly growing user bases.
  • Geographically distributed systems: Application or services are spread across different geographical locations at low latency.
  • High availability systems: Applications requiring high availability and disaster recovery setups.
  • Man power: You have the people and resources to buy, install, and maintain additional hardware and software

Vertical Scaling:

  • Moderate scale applications: Small to medium size applications with predictable growth.
  • Quicker upgrades: Situations where immediate resource upgrades are necessary without the complexity of sharding.
  • High interval upgrades: Gap between the two upgrades is high, so you do not have to worry about downtime.
  • Simple architectures: Applications with simpler architecture requirements and limited data distribution needs.

Which one to choose?

The choice between horizontal and vertical scaling depends on various factors, including:

  • Data size: For massive datasets, horizontal scaling is typically more suitable.
  • Growth rate: For rapid growth, horizontal scaling offers more flexibility.
  • Setup: Horizontal scaling will be more expensive to setup
  • Budget: Vertical scaling can be more expensive in the long run due to the cost of high-end servers.
  • Complexity: If you have a moderate traffic, vertical scaling might be sufficient.
  • Fault Tolerance: For high fault tolerance, horizontal scaling is advantageous.

How to do scaling in MongoDB?

There are multiple ways you can scale your site using MongoDB.

1. Horizontal Scaling Syntax:

After choosing the shard keys that evenly distributes data and evaluating the data model, shard according to your needs

"sh.addShard("shard_name/shard_hostname:port") "

This adds shards to distribute data across multiple machines.

To enable sharding use the command:

sh.enableSharding()

To shard a particular collection or dataset use:

sh.shardCollection()

2. Vertical Scaling Syntax

( with MongoDB Atlas):

Go to MongoDB Atlas dashboard.

  1. Select cluster.
  2. Click on ‘Modify Cluster’.
  3. Choose a higher configuration for your cluster (e.g., increase RAM, CPU).

This will upgrade the resources of your existing MongoDB server.

Other methods can be

  • Upgrading hardware.
  • Cloud providers like AWS(Amazon Web Services), Azure.
  • Database optimization.
  • Distributed computers.

Steps to Create Application And Installing Module

To create an application using MongoDB:

Step 1: Install MongoDB driver for Node.js

install mongodb


Step 2: Set up your MongoDB connection in your Node.js application.

npm init -y

Step 3: Install the package using the below command

npm install mongodb

The Updated Dependencies in your package.json file is:

After installing the MongoDB driver, your package.json file should include:

"dependencies": {
  "mongodb": "^46.6.1
}

Example: Below is an example to show the scaling behaviour in MongoDB.

JavaScript
// server.js
const { MongoClient } = require('mongodb');

// Connection URI
const uri = 'mongodb://localhost:27017';

// Create a new MongoClient
const client = new MongoClient(uri);

async function main() {
    try {
        // Connect to the MongoDB server
        await client.connect();
        console.log('Connected to MongoDB');

        // Use a specific database
        const database = client.db('mydb');

        // Use a specific collection
        const collection = database.collection('mycollection');

        // Insert a document
        await collection.insertOne({
            name: 'w3wiki'
        });
        console.log('Document inserted');

        // Find documents
        const docs = await collection.find().toArray();
        console.log('Found documents:', docs);
    } catch (error) {
        console.error('Error:', error);
    } finally {
        // Close the connection
        await client.close();
        console.log('Connection closed');
    }
}

main();

Output:

Scaling Behaviour in MongoDB

Difference between of Horizontal and Vertical Scrolling


Horizontal Scaling

Vertical Scaling

Description

Scaling out by increasing more machines or nodes in the MongoDB cluster

Scaling up by increasing or decreasing resources to handle traffic

Usage

(example)

Big e-commerce website where you can increase virtual machines or do sharding

Small sized startup website where you can simply upgrade server side

Complexity

Higher

Lower

Downtime

Almost none

Yes

Expense

Highly expensive

Less expensive than horizontal scaling

Performance

Higher

Lower

Implementation

Takes times and expertise

Does not take much time and expertise



Contact Us