MongoDB и адекватная репликация с Replica Set
Устанавливаем, запускаем и проверяем работоспособность сервера
Основной задачей в данный момент является настройка репликации.
MongoDB в отличии от MySQL поддерживает 2 формы репликации:
— реплисеты (Replica Sets)
— ведущий-ведомый (Master-Slave)
Подробности можно узнать на официальном сайте
Обыкновенная настройка Master-Slave не интересна да и не рекомендуется разработчиками. Я хочу проверить реплисеты. Для этого указываю имя реплики для всего сервера, раскоментровав отвечающую за это строку
Перезапускаю сервер для применения изменений.
Есть вероятность, что этот шаг можно было пропустить, так как при создании инстансов вручную указывается одно и тоже имя реплики для каждого процесса. Если кто то попробует — напишите в коментариях о результате
В нашем тестовом окружении необходимо запустить 3 экземпляра сервера. 3 это минимум, необходимый для «правильной» реплики: один из серверов выступает исключительно в роли арбитра и не принимает на себя никакие данные.
Он всего лишь помогает выбрать сервер, который будет PRIMARY. Это его свойство позволяет использовать в качестве арбитра сервер с минимальными ресурсами.
Для имитирования ситуации с 3 разными серверами я создам 3 процесса mongod c отдельным портом и базой:
Создание самих баз и установка необходимого владельца:
Этот сервер будет PRIMARY (Мастер)
Этот сервер будет SECONDARY (слейв)
Этот сервер будет арбитром, не принимающим данных
Подключаемся к основному серверу и настраиваем реплику из консоли mongo
Для проверки подключимся к оставшимся серверам и посмотрим их статус
Видим, что сервер видит реплику и его статус SECONDARY
Аналогично видим, что этот инстанс является частью реплики FirstReplica и выступает в качестве арбитра
Вроде как завелось. Теперь попробую создать реальные условия:
Инициируем «падение» PRIMARY сервера:
Я прибил процесс, на котором висел PRIMARY сервер. Нет процесса — нет доступа к серверу.
Вернёмся к арбитру и проверим состояние реплики:
Видно, что главный сервер недоступен («stateStr» : «(not reachable/healthy)»), а сервер с id 1 стал PRIMARY
Теперь инициируем «поднятие» основного мастера:
И снова интересуемся у арбитра как там дела у сервачков:
Как видно выше сервер после возвращения из даунтайма снова принялся за свои обязанности, став мастером всей реплики. В этом ему помогает арбитр.
На этом простом примере мы рассмотрели создание простой репликации с особенностями, присущими программному продукту MongoDB. Следует учесть, что в данном случае реплика была создана до начала работ с базой данных.
Если имеется уже настроенный продакшн-сервер, то метод создания реплики может отличаться. Обязательно потренеруйтесь в тестовом окружении.
В заключении — очистка всего нашего хозяйства:
Так как я запускал процессы вручную, то и останавливать их нужно самостоятельно.
Для этого воспользуемся db.shutdownServer()
Видим что сервер выключился и в репликации он переключился на SECONDARY
Аналогично останавливаем и остальные, но сначала арбитра, а потом наш SECONDARY
Проверяем
Нет процессов mongod, только наш, который их ищет 🙂
Если базы, которые мы создали для теста более не нужны — их тоже можно удалить. Более того, они не так уж мало занимают
Удаляем и снова проверяем
Так лучше. Люблю порядок на сервере
MongoDB и адекватная репликация с Replica Set : 5 комментариев
Доброго времени суток!
Подскажите, обязательно ли делать отдельный узел-арбитр?
Судя по этому туториалу http://37yonub.ru/articles/mongo-replica-set-docker-localhost арбитр и primary могут быть на одном узле. Или это ошибка?
Еще такой вопрос — как правильно общаться с кластером? Я могу писать только в primary и читать из любого, так?
DNS для записи это mongodb://localhost:27117/?replicaSet=TestMongoReplicaSet&connect=direct
DNS для чтения может быть такой mongodb://localhost:27117,localhost:27217,localhost:27317/?replicaSet=TestMongoReplicaSet&connect=direct
Добрый день. Начнем с того что приведённый вами туториал тоже написан каким то пользователем.
Опираться в данном случае необходимо на официальную документацию
Эта документация гласит что арбитр сам по себе не обязателен. Реплику можно построить и без него.
Далее про чтение/запись.
Запись производится только на Primary.
Чтение так же производится с Primary, но при определённых конфигурациях реплики читать можно напрямую с Secondary. Необходимо выполнить разрешение на мастере с указание ID того секондари, с которого хотите читать.
По поводу «общения» с кластером как указал выше всё проходит через Primary до тех пор пока не настроете иначе
Да, с этим разобрался. Арбитр не принимает трафик, только выбирает кому быть PRIMARY.
А как приложение, использующее кластер монго, работает со сменой PRIMARY сервера?
mongodb://localhost:27117,localhost:27217/?replicaSet=TestMongoReplicaSet&connect=direct&readPreference=secondary
используем DNS со всеми перечисленными репликами и драйвер сам подбирает что есть PRIMARY и пишет туда? Я проверил, вроде работает. Правда есть небольшой промежутой времени (5-10 секунд) с ошибкой «NotMaster» — наверно арбитр назначает primary не сразу.
Вопрос о смене Primary/Secondary немного не по адресу. Это к прогерам которые работают с драйверами
На практике смена Primary происходит меньше секунды в реплике из трёх инстансов Primary/Secondary/Arbiter
О каком DNS идёт речь если у вас везде используется localhost? Не понял вопроса, уточните
Опечатка, DSN (connesion string).
Спасибо за подсказки )) дальше буду разбираться с драйверами )
Добавить комментарий Отменить ответ
Для отправки комментария вам необходимо авторизоваться.
Установка и настройка MongoDB на Debian, а также ReplicaSet и пара других мелочей
Это руководство описывает пошаговую установку и настройку реплики из 3 узлов mongoDB на базе движка WiredTiger. А также несколько полезных мелочей для людей, впервые столкнувшихся с MongoDB.
Важное уточнение:
Немного о движке WiredTiger
Engine WiredTiger — новый движок mongoDB, использующийся по умолчанию вместо MMAP, начиная с версии 3.4. Хорош тем, что работает с данными на уровне коллекций и отдельных документов, а не полностью базой. Также устраняет проблему Global lock по вышеуказанной причине, из-за чего и был выбран в продакшен.
Установка OS и компонентов
Ставим Debian любой удобной вам версии, у меня использовался 8.6.0.
Для упрощения масштабирования узлов и баз данных, рекомендую использовать lvm.
Из компонентов понадобится только ssh для более удобного доступа к серверу.
Установка MongoDB.
У меня используется бесплатная Community Edition, руководство будет на её основе.
По необходимости допишу Enterpise версию, т.к. она тоже крутилась и разбиралась.
Данное руководство описывается для варианта 3-х серверов (master, slave, arbiter).
Копируем репозиторий и сохраняем изменения.
Обновляем список доступных пакетов
Повторяем процедуру для 3(трех) серверов,
На этом первоначальная настройка завершена.
Теперь переходим к настройке mongoDB.
Настройка и добавление серверов в Replica Set
В начале было слово
Давайте для начала разберемся, что такое replica set.
Replica Set — это кластер серверов MongoDB, реализующий механизм репликации master-slave и автоматическое переключение между ними. Это рекомендуемый механизм репликации от разработчиков MongoDB. ссылка на офф. документацию.
Мы используем механизм репликации, приведенный на картинке:
мастер, два вторичных и арбитр.
Primary — основной сервер mongoDB.
Secondary — точные копии баз(ы) данных с real-time синхронизацией.
Arbiter — сервер выбора вторичной реплики с высшим приоритетом, которая станет главной в случае падения сервера.
ОЧЕНЬ ВАЖНО:
Arbiter отвечает только за выборы преемника, сам стать преемником он не может, поэтому рекомендуется отдавать под арбитра минимальные ресурсы.
ЕЩЁ БОЛЕЕ ВАЖНО:
Технически можно вообще жить без арбитра, однако с ним выборы будут происходить в разы быстрее, соответственно время простоя будет минимизировано. Плюс есть ненулевая вероятность потерять ReplicaSet целиком.
Primary
Настройки пишем в файл /etc/mongod.conf У меня файл выглядит следующим образом:
Указываемые значения переменных:
dbPath — путь к базе данных. При указании на пустое место, создаст там базы. При разворачивании бэкапа подцепит существующую.
journal — включает журналирование.
replSetName — название реплики. Должно быть идентичным у всех узлов внутри реплики.
bindIp — список адресов, с которых можно принимать соединения по порту 27017.
Далее для конфигурирования я использовал саму mongoDB:
попадаем внутрь и первым делом проверяем статус:
Начальный статус должен быть 0 — startup. Означает что узел не является членом ни одной реплики.
Инициализируем реплику.
Выполняем в MongoShell на первичном узле
Сразу после добавления в реплику узел будет в статусе 5 — Startup2, это означает что он присоединился к реплике и в данный момент синхронизируется. Может занять продолжительное время.
Добавляем следующие узлы:
Статусы в rs.status() будут:
1 — Primary
2 — Secondary
7 — Arbiter
Приоритеты
Первый:
Необходимо проставить приоритеты (цифры member id берем из статуса):
Чем выше цифра приоритета, тем ниже сам приоритет при выборе Primary узла.
Второй:
Добавляем узлы с заранее прописанным приоритетом:
Проверяем что все узлы доступны и выставлены с правильными приоритетами:
В моем случае конфиги и статусы приобрели следующий вид:
При добавлении узла в уже существующую реплику она какое-то время будет недоступна в связи с синхронизацией.
На этом установка и настройка MongoDB в режиме ReplicaSet завершена и можно с чистой совестью наполнять базу данными.
Другие полезные команды
Сбрасывание PRIMARY. Смена первичного узла и переназначение приоритетов
60 секунд — время, в течение которого сервер, с которого запущено выполнение команды, не может стать Primary; 40 секунд — время перевыборов нового Primary.
30 секунд — время отключения Primary и перевыборы. Выполнение команды допустимо с любого из серверов mongoDB.
Узел, с которого запущена команда, в течение 60 секунд не сможет стать Primary.
/var/lib/mongodb/ — Тут лежат файлы баз.
Восстановление из дампа:
Восстанавление базы в каталог по умолчанию. Если файл в с таким именем есть, то он перезаписывается:
Восстановление всех баз из указанного каталога:
Восстановление отдельной таблицы(коллекции):
Создание дампа
создание бэкапа всех баз в папку Backup:
создание бэкапа отдельной базы:
создание бэкапа отдельной таблицы:
Запуск от имени root, создание бэкапа указанной базы в указанный каталог + текущая дата:
ReplicationВ¶
A replica set in MongoDB is a group of mongod processes that maintain the same data set. Replica sets provide redundancy and high availability, and are the basis for all production deployments. This section introduces replication in MongoDB as well as the components and architecture of replica sets. The section also provides tutorials for common tasks related to replica sets.
Redundancy and Data AvailabilityВ¶
Replication provides redundancy and increases data availability. With multiple copies of data on different database servers, replication provides a level of fault tolerance against the loss of a single database server.
In some cases, replication can provide increased read capacity as clients can send read operations to different servers. Maintaining copies of data in different data centers can increase data locality and availability for distributed applications. You can also maintain additional copies for dedicated purposes, such as disaster recovery, reporting, or backup.
Replication in MongoDBВ¶
A replica set is a group of mongod instances that maintain the same data set. A replica set contains several data bearing nodes and optionally one arbiter node. Of the data bearing nodes, one and only one member is deemed the primary node, while the other nodes are deemed secondary nodes.
The primary node receives all write operations. A replica set can have only one primary capable of confirming writes with write concern; although in some circumstances, another mongod instance may transiently believe itself to also be primary. [ 1 ] The primary records all changes to its data sets in its operation log, i.e. oplog. For more information on primary node operation, see Replica Set Primary.
The secondaries replicate the primary’s oplog and apply the operations to their data sets such that the secondaries’ data sets reflect the primary’s data set. If the primary is unavailable, an eligible secondary will hold an election to elect itself the new primary. For more information on secondary members, see Replica Set Secondary Members.
In some circumstances (such as you have a primary and a secondary but cost constraints prohibit adding another secondary), you may choose to add a mongod instance to a replica set as an arbiter. An arbiter participates in elections but does not hold data (i.e. does not provide data redundancy). For more information on arbiters, see Replica Set Arbiter.
An arbiter will always be an arbiter whereas a primary may step down and become a secondary and a secondary may become the primary during an election.
Asynchronous ReplicationВ¶
Secondaries replicate the primary’s oplog and apply the operations to their data sets asynchronously. By having the secondaries’ data sets reflect the primary’s data set, the replica set can continue to function despite the failure of one or more members.
For more information on replication mechanics, see Replica Set Oplog and Replica Set Data Synchronization.
Slow OperationsВ¶
Starting in version 4.2 (also available starting in 4.0.6), secondary members of a replica set now log oplog entries that take longer than the slow operation threshold to apply. These slow oplog messages:
The profiler does not capture slow oplog entries.
Replication Lag and Flow ControlВ¶
Replication lag refers to the amount of time that it takes to copy (i.e. replicate) a write operation on the primary to a secondary. Some small delay period may be acceptable, but significant problems emerge as replication lag grows, including building cache pressure on the primary.
Automatic FailoverВ¶
When a primary does not communicate with the other members of the set for more than the configured electionTimeoutMillis period (10 seconds by default), an eligible secondary calls for an election to nominate itself as the new primary. The cluster attempts to complete the election of a new primary and resume normal operations.
The replica set cannot process write operations until the election completes successfully. The replica set can continue to serve read queries if such queries are configured to run on secondaries while the primary is offline.
Lowering the electionTimeoutMillis replication configuration option from the default 10000 (10 seconds) can result in faster detection of primary failure. However, the cluster may call elections more frequently due to factors such as temporary network latency even if the primary is otherwise healthy. This can result in increased rollbacks for w : 1 write operations.
Your application connection logic should include tolerance for automatic failovers and the subsequent elections. Starting in MongoDB 3.6, MongoDB drivers can detect the loss of the primary and automatically retry certain write operations a single time, providing additional built-in handling of automatic failovers and elections:
Starting in version 4.4, MongoDB provides mirrored reads to pre-warm electable secondary members’ cache with the most recently accessed data. Pre-warming the cache of a secondary can help restore performance more quickly after an election.
To learn more about MongoDB’s failover process, see:
Read OperationsВ¶
Read PreferenceВ¶
By default, clients read from the primary [ 1 ]; however, clients can specify a read preference to send read operations to secondaries.
Asynchronous replication to secondaries means that reads from secondaries may return data that does not reflect the state of the data on the primary.
For information on reading from replica sets, see Read Preference.
Data VisibilityВ¶
Depending on the read concern, clients can see the results of writes before the writes are durable:
For operations in a multi-document transaction, when a transaction commits, all data changes made in the transaction are saved and visible outside the transaction. That is, a transaction will not commit some of its changes while rolling back others.
Until a transaction commits, the data changes made in the transaction are not visible outside the transaction.
However, when a transaction writes to multiple shards, not all outside read operations need to wait for the result of the committed transaction to be visible across the shards. For example, if a transaction is committed and write 1 is visible on shard A but write 2 is not yet visible on shard B, an outside read at read concern «local» can read the results of write 1 without seeing write 2.
For more information on read isolations, consistency and recency for MongoDB, see Read Isolation, Consistency, and Recency.
Mirrored ReadsВ¶
Mirrored reads reduce the impact of primary elections following an outage or planned maintenance. After a failover in a replica set, the secondary that takes over as the new primary updates its cache as new queries come in. While the cache is warming up performance can be impacted.
Starting in version 4.4, mirrored reads pre-warm the caches of electable secondary replica set members. To pre-warm the caches of electable secondaries, the primary mirrors a sample of the supported operations it receives to electable secondaries.
The size of the subset of electable secondary replica set members that receive mirrored reads can be configured with the mirrorReads parameter. See Enable/Disable Support for Mirrored Reads for further details.
Mirrored reads do not affect the primary’s response to the client. The reads that the primary mirrors to secondaries are «fire-and-forget» operations. The primary doesn’t await responses.
Supported OperationsВ¶
Mirrored reads support the following operations:
Enable/Disable Support for Mirrored ReadsВ¶
Change the Sampling Rate for Mirrored ReadsВ¶
To change the sampling rate for mirrored reads, set the mirrorReads parameter to a number between 0.0 and 1.0 :
Mirrored Reads MetricsВ¶
Starting in MongoDB 4.4, the serverStatus command and the db.serverStatus() shell method return mirroredReads metrics if you specify the field in the operation:
TransactionsВ¶
Starting in MongoDB 4.0, multi-document transactions are available for replica sets.
Until a transaction commits, the data changes made in the transaction are not visible outside the transaction.
However, when a transaction writes to multiple shards, not all outside read operations need to wait for the result of the committed transaction to be visible across the shards. For example, if a transaction is committed and write 1 is visible on shard A but write 2 is not yet visible on shard B, an outside read at read concern «local» can read the results of write 1 without seeing write 2.
Change StreamsВ¶
Starting in MongoDB 3.6, change streams are available for replica sets and sharded clusters. Change streams allow applications to access real-time data changes without the complexity and risk of tailing the oplog. Applications can use change streams to subscribe to all data changes on a collection or collections.
Additional FeaturesВ¶
Replica sets provide a number of options to support application needs. For example, you may deploy a replica set with members in multiple data centers, or control the outcome of elections by adjusting the members[n].priority of some members. Replica sets also support dedicated members for reporting, disaster recovery, or backup functions.
MongoDB Replication
Overview
How does replication work in MongoDB?
Replication exists primarily to offer data redundancy and high availability. We maintain the durability of data by keeping multiple copies or replicas of that data on physically isolated servers. That’s replication: the process of creating redundant data to streamline and safeguard data availability and durability.
Replication allows you to increase data availability by creating multiple copies of your data across servers. This is especially useful if a server crashes or if you experience service interruptions or hardware failure.
If your data only resides in a single database, any of these events would make accessing the data impossible. But thanks to replication, your applications can stay online in case of database server failure, while also providing disaster recovery and backup options.
With MongoDB, replication is achieved through a replica set. Writer operations are sent to the primary server (node), which applies the operations across secondary servers, replicating the data.
If the primary server fails (through a crash or system failure), one of the secondary servers takes over and becomes the new primary node via election. If that server comes back online, it becomes a secondary once it fully recovers, aiding the new primary node.
How do I enable replication in MongoDB?
To start, you’ll need MongoDB installed on three or more nodes. Each of the nodes in the cluster will need to be able to communicate with the others over a standard port (27017 by default). Additionally, each replica set member needs to have a hostname that is resolvable from the others.
Overview: Network Connectivity
Establish a virtual private network. Ensure that your network topology routes all traffic between members within a single site over the local area network.
Configure access control to prevent connections from unknown clients to the replica set.
Configure networking and firewall rules so that incoming and outgoing packets are permitted only on the default MongoDB port and only from within your deployment. See the IP Binding considerations.
Ensure that each member of a replica set is accessible by way of resolvable DNS or hostnames.
1: Start each member of the replica set with the appropriate options.
2: Connect a mongo shell to one of the mongod instances.
From the same machine where one of the mongod is running, start the mongo shell. To connect to the mongod listening to localhost on the default port of 27017, simply issue:
Depending on how you installed MongoDB and set up your environment, you may need to specify the path to the mongo binary.
3: Initiate the replica set.
MongoDB initiates a replica set, using the default replica set configuration.
4: View the replica set configuration.
Use rs.conf() to display the replica set configuration object:
The replica set configuration object resembles the following:
5: Ensure that the replica set has a primary.
Use rs.status() to identify the primary in the replica set.
How does MongoDB detect replication lag?
Replication lag is a delay in data being copied to a secondary server after an update on the primary server. Short windows of replication lag are normal, and should be considered in systems that choose to read the eventually-consistent secondary data. Replication lag can also prevent secondary servers from assuming the primary role if the primary goes down.
If you want to check your current replication lag:
In a Mongo shell connected to the primary, call the rs.printSlaveReplicationInfo() method.
This returns the syncedTo value for each member, which shows the time when the last oplog entry was written to the secondary server.
Replication lag can be due to several things, including:
Network Latency: Check your ping and traceroute to see if there is a network routing issue or packet loss. See: ping diagonistic documentation, troubleshooting replica sets.
Disk Throughput: Sometimes the secondary server is unable to flush data to disk as rapidly as the primary. This is common on multi-tenant systems, especially if the system accesses disk devices over an IP network. System-level tools, like vmstat or iostat can help you find out more. See: production notes, mongostat.
Concurrency: Long-running operations on the primary can block replications. Set up your write concern so that write operations don’t return if replication can’t keep up with the load. Alternatively, check slow queries and long-running operations via the database profiler. See: Write Concern.
Appropriate Write Concern: If the primary requires a large amount of writes (due to a bulk load operation or a sizable data ingestion), the secondaries may not be able to keep up with the changes on the oplog. Consider setting your write concern to “majority” in order to ensure that large operations are properly replicated.
What is the difference between replication and sharding?
Replication: The primary server node copies data onto secondary server nodes. This can help increase data availability and act as a backup, in case if the primary server fails.
Sharding: Handles horizontal scaling across servers using a shard key. This means that rather than copying data holistically, sharding copies pieces of the data (or “shards”) across multiple replica sets. These replica sets work together to utilize all of the data.
Think of it like a pizza. With replication, you are making a copy of a complete pizza pie on every server. With sharding, you’re sending pizza slices to several different replica sets. Combined together, you have access to the entire pizza pie.
Replication and sharding can work together to form something called a sharded cluster, where each shard is replicated in turn to preserve the same high availability.
What is the benefit of replication?
Replication has several benefits. It increases data availability and reliability thanks to there being multiple live copies of your data.
Replication is also helpful in case of an event like hardware failure or a server crash. Rather than suffer downtime (or, even worse, losing your data entirely), replication ensures your data is safely protected across multiple servers. If you have distributed analytics teams, you can effectively collaborate on business intelligence projects.
Does replication affect latency?
Replication does not meaningfully affect read or write latency to primary servers. Application latency can be improved in cases where it makes sense to read data from replica set secondary nodes, provided you’re okay showing customers eventually-consistent data.
Conclusion
Rather than having to configure and manage everything yourself, you can always use MongoDB Atlas. It streamlines and automates your replica sets, making the process effortless for you. MongoDB Atlas can also deploy globally sharded replica sets with few clicks, enabling data locality, disaster recovery, and multi-region deployments.



