All articles
Storage & coordinationDesign analysis

Data Balance for database

Preface

For a distributed data system, the word “balance” has two meanings: first, data balance, which refers to the relatively balanced physical distribution of data among different storage units. The second is workload balance, which refers to the balance of the running load, meaning that the pressure of data writing and querying assigned to various working units should not differ too much. These two different levels of balance affect each other, but in the real production environment, the system status can be rather complex, so it is difficult to provide a definitive guarantee or principle for the problem like: “what kind of data distribution can bring better load balance?” Even experienced DBAs or developers cannot provide a standard answer to such a question. This article has an insight of the Balance mechanism design of four popular databases: Elasticsearch, Clickhouse, MongoDB, and Milvus, to briefly describe the general practices and trade-offs of database systems under the topic of Data Balance.

Process of Data Balance: Migration

Data balance is a migration process, that is, moving a shard or tablet of data set from one storage node to another. This process needs to be transparent to users and mostly follows the principle of “up first, down later”. Taking MongoDB as an example, the process of migrating Range is as follows:

  1. The balancer issues a Move Range instruction to the source shard.
  2. The source shard moves the existing range, and during the data transfer process, new incoming writes are still handled by the source. This part of the data becomes new_data_during_migration.
  3. The destination shard continuously receives copied existing data until all existing data is copied to the destination node.
  4. The destination starts the sync process, copying new_data_during_migration to its own shard.
  5. When the sync process is complete, the source shard updates meta on config databases and finally deletes its local data.

Figure 1View full-size image

In an “Up first Down second” process like this, theoretically, the client is completely unaware of backend changes, and there are no interruptions or failures in write/query operations, let alone data loss. However, in a production environment, various problems may arise.

Potential Issues with Balance

Performance Impact

The balance operation clearly affects system performance. Even without considering CPU consumption, the significant IO bandwidth pressure caused by copying data will noticeably degrade performance. To address this issue, MongoDB restricts each shard to balance only one range at a time, and the total number of ranges balanced across the cluster simultaneously cannot exceed half the number of shards.

MongoDB can conduct parallel data migrations, but a shard can only participate in one migration at a time. For a sharded cluster with n shards, MongoDB can conduct a maximum of n/2 (rounded down) simultaneous migrations.

Elasticsearch (ES) handles performance impact more finely by setting cluster.routing.allocation.cluster_concurrent_rebalance to control the maximum concurrent balance operations for the entire cluster. The higher this parameter is configured, the shorter the time taken for balancing, but the more noticeable impact on resources and foreground queries.

It’s also important to note that the performance impact of balance is directly related to its granularity. For MongoDB, the balance unit is a Range (Chunk), with a default size of only 128MB. However, for Elasticsearch, balance occurs only at the shard level, with the balance target being shard equilibrium. Therefore, the granularity is coarser, and since shards can be very large, reaching GB levels, the resource consumption during data migration is also greater.

Balance Oscillation

Balance oscillation refers to the inability of balance actions to converge, constantly attempting to balance but never reaching a balanced state. In such cases, there are often repeated migrations for a balance unit, as documented in issues like the balance oscillation problem in early versions of Milvus recorded at https://github.com/milvus-io/milvus/issues/21189. The root cause of this problem lies in unstable balance bases and an overly sensitive Auto Balance mechanism. Unstable balance bases refer to continuous changes in the distribution of balance units due to ongoing writes/compactions. The balancing mechanism may be based on a transient intermediate state for balancing, and as this state changes, the overly sensitive balancer may initiate balancing again, leading to repeated movements of the balance unit without convergence.

For such cases, both ES and MongoDB use thresholds to reduce sensitivity. ES uses cluster.routing.allocation.balance.threshold to control the minimum balance benefit. If the benefit of a balance operation is not greater than this parameter value, the balance operation is considered not worthwhile. MongoDB specifies the maximum and minimum ratio of Range (Chunk) sizes, floating between 2 and 8 times for different-sized collections. Only when the ratio between the largest and smallest exceeds this specified value will balancing be triggered.

Resource Peak Occupancy Increase

Balance consumes resources mainly in terms of IO bandwidth and disk (and possibly memory). Since only after the final step of migration is completed can data be deleted from the source, this doubles the system’s disk/memory usage during balance. Particularly, some databases may use lazy delete for balanced data to expedite the balance process, further increasing peak resource occupancy. For example, MongoDB’s _waitForDelete setting allows the balancer to start the next balance task immediately without waiting for data deletion.

In early versions of Milvus, there were instances of balance causing a doubling of memory consumption and excessive write traffic leading to OOM issues.

What Are the Criteria for Balance?

The additional costs and risks of balance are high, and a heavily unbalanced cluster may perform poorly in terms of performance and stability. Therefore, establishing a comprehensive, stable, and predictable balance criteria is fundamental to the balance mechanism. In setting a unified standard, Elasticsearch and Milvus alike use scores/weights as the sole balance criterion. Taking ES’s weight calculation as an example, it primarily considers four variables: shard count, index shard count, disk usage, and write load. The values of these variables determine the intent of balance.

For example, the larger the weight of disk_usage, the more ES tends to equalize disk usage across nodes, while suppressing the other three indicators. In other words, to achieve disk usage equality, ES may allocate a large number of "small shards" to some nodes while others have only a few "large shards."

It’s important to distinguish between the parameters of shard number and index shard number. For index shard number, the official explanation is to “balance the number of shards per index across nodes.”

In practice, the combined use of these two parameters is crucial, and Milvus encounters issues covered by this design in production environments.

(Note: Milvus’s Balance Unit is a segment, while ES uses Shard; these are equivalent in the context of this balance topic.)

(Note: Milvus’s tables are referred to as Collections, and tables in ES are referred to as Indexes; these are also equivalent.)

Actual Issue in Production Environment: Imbalance of Shard/Segment Counts

Figure 2View full-size image

Imbalanced Data Distribution After Restart

During the troubleshooting process in a cloud environment in March 2023, an issue arose where there was an order of magnitude difference in data distribution between instances. As shown in the figure above, the number of segments on 4 nodes ranged from 70 to 110, while on another 4 nodes, the number of segments was only between 15 and 20. Due to the extremely imbalanced data distribution, there was a significant difference in query load, affecting overall performance.

The root cause of this issue lies in the settings of the balance parameters collection_segment (or index_shard) being set too high, while the weights of node_segment (or node_shard) were set too low. This led to the premature termination of balance due to differences in the startup order of nodes in the cloud environment.

Figure 3View full-size image

Simply put, from the perspective of each collection as shown in the diagram, the current state is balanced. This is because each collection has only one segment on each node. Therefore, if the weights of the nodes are set improperly, the balancer will remain indifferent to this situation. However, if the weights of the nodes are set too high and the weights of the collection segments (or index shards) are set too low, it may lead to the following scenario: even though the segment counts are balanced across the four nodes, all shards of each collection are concentrated on one node, which can easily result in workload hotspots.

Figure 4View full-size image

Is AutoBalance necessary?

Not necessarily. For example, ClickHouse does not support Auto Balance. ClickHouse handles unbalanced distributed tables in two ways:

  1. For tables that are still being written to, users can add new shards and increase the write_weight of the new shard, so that new writes are directed to the new shard until a balanced state is achieved. This approach may make the new shard a hotspot for writes and is therefore only suitable for use when there is not too much writing pressure. Additionally, it is ineffective for existing data.
  2. For existing unbalanced data, ClickHouse supports manually balancing partitions. This involves manually relocating partitions from nodes with too much data to other nodes. This approach may consume fewer resources but is more cumbersome and requires the distributed table to be partitioned; otherwise, this method cannot be used.

Summary

this article starts from the process of database balance, introduces the potential costs of data balance, and the strategies adopted by different databases in balancing the cost and effectiveness of balance. It also describes the impact of different reference index weights on the balance effect based on problems encountered in production environments. Finally, it compares ClickHouse’s approach to the balance topic with that of other three databases.

Overall, the author generally agrees with ClickHouse’s attitude towards the balance topic, namely that balance issues are not critical. In most cases encountered in practical production environments, situations of extreme imbalance can be resolved with RoundRobin, alerts, and manual intervention by DBAs. The tolerable level of imbalance does not justify introducing too much system complexity to address it, especially for large-scale systems. For example, in the case of Elasticsearch (ES), the background auto-balance mechanism can easily lead to unexpected consequences due to various issues, and the complex basis and parameters for balance decisions often make them incomprehensible to DBAs, introducing additional complications.

Reference

— MrPresent-Han