MONGODB SHARDING
admin
2023-04-13 13:02:13
0

Sharding Introduction

Sharding is a method for storing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput operations.

Purpose of Sharding

Database systems with large data sets and high throughput applications can challenge the capacity of a single server. High query rates can exhaust the CPU capacity of the server. Larger data sets exceed the storage capacity of a single machine. Finally, working set sizes larger than the system’s RAM stress the I/O capacity of disk drives.

To address these issues of scales, database systems have two basic approaches: vertical scaling andsharding.

Vertical scaling adds more CPU and storage resources to increase capacity. Scaling by adding capacity has limitations: high performance systems with large numbers of CPUs and large amount of RAM are disproportionately more expensive than smaller systems. Additionally, cloud-based providers may only allow users to provision smaller instances. As a result there is apractical maximum capability for vertical scaling.

Sharding, or horizontal scaling, by contrast, divides the data set and distributes the data over multiple servers, or shards. Each shard is an independent database, and collectively, the shards make up a single logical database.

MONGODB SHARDING


Diagram of a large collection with data distributed across 4 shards.


Sharding addresses the challenge of scaling to support high throughput and large data sets:

  • Sharding reduces the number of operations each shard handles. Each shard processes fewer operations as the cluster grows. As a result, shared clusters can increase capacity and throughput horizontally.

    For example, to insert data, the application only needs to access the shard responsible for that records.

  • Sharding reduces the amount of data that each server needs to store. Each shard stores less data as the cluster grows.

    For example, if a database has a 1 terabyte data set, and there are 4 shards, then each shard might hold only 256GB of data. If there are 40 shards, then each shard might hold only 25GB of data.

Sharding in MongoDB

MongoDB supports sharding through the configuration of a sharded clusters.

MONGODB SHARDING


Diagram of a sample sharded cluster for production purposes. Contains exactly 3 config servers, 2 or more mongos query routers, and at least 2 shards. The shards are replica sets.


Sharded cluster has the following components: shards, query routers and config servers.

Shards store the data. To provide high availability and data consistency, in a production sharded cluster, each shard is areplica set [1]. For more information on replica sets, see Replica Sets.

Query Routers, or mongos instances, interface with client applications and direct operations to the appropriate shard or shards. The query router processes and targets operations to shards and then returns results to the clients. A sharded cluster can contain more than one query router to divide the client request load. A client sends requests to one query router. Most sharded cluster have many query routers.

Config servers store the cluster’s metadata. This data contains a mapping of the cluster’s data set to the shards. The query router uses this metadata to target operations to specific shards. Production sharded clusters have exactly 3 config servers.

[1] For development and testing purposes only, each shard can be a single mongod instead of a replica set. Do not deploy production clusters without 3 config servers.

Data Partitioning

MongoDB distributes data, or shards, at the collection level. Sharding partitions a collection’s data by the shard key.

Shard Keys

To shard a collection, you need to select a shard key. A shard key is either an indexed field or an indexed compound field that exists in every document in the collection. MongoDB divides the shard key values into chunks and distributes the chunksevenly across the shards. To divide the shard key values into chunks, MongoDB uses either range based partitioning andhash based partitioning. SeeShard Keys for more information.


Range Based Sharding

For range-based sharding, MongoDB divides the data set into ranges determined by the shard key values to provide range based partitioning. Consider a numeric shard key: If you visualize a number line that goes from negative infinity to positive infinity, each value of the shard key falls at some point on that line. MongoDB partitions this line into smaller, non-overlapping ranges called chunks where a chunk is range of values from some minimum value to some maximum value.

Given a range based partitioning system, documents with “close” shard key values are likely to be in the same chunk, and therefore on the same shard.

MONGODB SHARDING


Diagram of the shard key value space segmented into smaller ranges or chunks.



Hash Based Sharding

For hash based partitioning, MongoDB computes a hash of a field’s value, and then uses these hashes to create chunks.

With hash based partitioning, two documents with “close” shard key values are unlikely to be part of the same chunk. This ensures a more random distribution of a collection in the cluster.

MONGODB SHARDING


Diagram of the hashed based segmentation.



Performance Distinctions between Range and Hash Based Partitioning

Range based partitioning supports more efficient range queries. Given a range query on the shard key, the query router can easily determine which chunks overlap that range and route the query to only those shards that contain these chunks.

However, range based partitioning can result in an uneven distribution of data, which may negate some of the benefits of sharding. For example, if the shard key is a linearly increasing field, such as time, then all requests for a given time range will map to the same chunk, and thus the same shard. In this situation, a small set of shards may receive the majority of requests and the system would not scale very well.

Hash based partitioning, by contrast, ensures an even distribution of data at the expense of efficient range queries. Hashed key values results in random distribution of data across chunks and therefore shards. But random distribution makes it more likely that a range query on the shard key will not be able to target a few shards but would more likely query every shard in order to return a result.



Maintaining a Balanced Data Distribution

The addition of new data or the addition of new servers can result in data distribution imbalances within the cluster, such as a particular shard contains significantly more chunks than another shard or a size of a chunk is significantly greater than other chunk sizes.

MongoDB ensures a balanced cluster using two background process: splitting and the balancer.

Splitting

Splitting is a background process that keeps chunks from growing too large. When a chunk grows beyond a specified chunk size, MongoDB splits the chunk in half. Inserts and updates triggers splits. Splits are a efficient meta-data change. To create splits, MongoDB does not migrate any data or affect the shards.

MONGODB SHARDING


Diagram of a shard with a chunk that exceeds the default chunk size of 64 MB and triggers a split of the chunk into two chunks.



Balancing

The balancer is a background process that manages chunk migrations. The balancer runs in all of the query routers in a cluster.

When the distribution of a sharded collection in a cluster is uneven, the balancer process migrates chunks from the shard that has the largest number of chunks to the shard with the least number of chunks until the collection balances. For example: if collection users has 100 chunks on shard 1 and 50 chunks on shard 2, the balancer will migrate chunks from shard 1 to shard 2 until the collections achieves balance.

The shards manage chunk migrations as a background operation. During migration, all requests for a chunks data address the “origin” shard.

In a chunk migration, the destination shard receives all the documents in the chunk from the origin shard. Then, the destination shard captures and applies all changes made to the data during migration process. Finally, the destination shard updates the metadata regarding the location of the on config server.

If there’s an error during the migration, the balancer aborts the process leaving the chunk on the origin shard. MongoDB removes the chunks data from the origin shard after the migration completes successfully.

MONGODB SHARDING


Diagram of a collection distributed across three shards. For this collection, the difference in the number of chunks between the shards reaches the migration thresholds (in this case, 2) and triggers migration.



Adding and Removing Shards from the Cluster

Adding a shard to a cluster creates an imbalance since the new shard has no chunks. While MongoDB begins migrating data to the new shard immediately, it can take some time before the cluster balances.

When removing a shard, the balancer migrates all chunks from to other shards. After migrating all data and updating the meta data, you can safely remove the shard.

上一篇:mongodb shard

下一篇:linux 下安装mongodb

相关内容

热门资讯

徐巧芯剖析赖清德:最怕自己丢掉... 海峡导报综合报道 大罢免投票一周年纪念活动26日举行,台北市长蒋万安出席并怒轰,民进党一年过后仍没有...
中国红十字会总会紧急向广东调拨... 记者从中国红十字会总会了解到,针对台风“红霞”给广东造成的灾情,中国红十字会总会启动四级应急响应,紧...
这些少年,正被“毒蛋”围猎 李梦抽了几口电子烟,吐出了白色的烟雾,有一股浓烈的水果香味。随后,她看着自己握电子烟的手,跟身边人说...
蒋万安号召“倒阁”,卢秀燕认为... 海峡导报综合报道 台北市长蒋万安27日抛出震撼议题,表示多名民代向他提议推动“倒阁”,要求台行政机构...
特朗普将在白宫会见两位重要客人 俄乌战争仍未结束,美伊冲突又有升级风险。在此背景下,美国总统特朗普将在白宫接见乌克兰和以色列领导人。...
新租客打扫卧室柜子上掉落4万元... 近日,莲前西路某小区内,张倩签下一套房子的租赁合同。当天上午,她带着12岁的大女儿周馨怡和11岁的小...
六部门通告:禁止涉军队退役报废... 关于禁止涉军队退役报废装备销售活动的通告近年来,部分经营者在线上线下公开销售涉及我军退役报废装备(指...
九寨沟景区发生泥石流,部分道路... 7月26日,九寨沟风景名胜区管理局发布泥石流灾害通报:2026年7月26日15时50分,九寨沟景区局...
空调26度不凉是什么原因 从空调内部元器件来说,不凉的原因有可能是温度传感器出现故障了,也有可能是空调压缩机或者铜管出现问题,...
鲸鸿动能携手香港国际机场、鸿蒙...   2026 年 7 月 25 日,十余位鸿蒙车主组成的车队从珠海出发,经港珠澳大桥通关抵达香港国际...