Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Database administration

How to Set Up MySQL Master-Master Replication on Two VPS Servers

By Freedom251 Team · · 11 min read

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

You can configure two VPS servers as a bidirectional MySQL replication pair by enabling binary logging and GTIDs on both, giving each server a unique server_id, and creating one replication channel in each direction. On current MySQL 8.0 releases, use CHANGE REPLICATION SOURCE TO with SOURCE_AUTO_POSITION=1.

This topology is asynchronous circular replication, not automatic conflict resolution. Keep one node as the active writer unless your application has a tested design for concurrent writes, fencing, and conflict handling.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What “master-master” means in current MySQL

“Master-master” is the older name for two MySQL sources that replicate from one another. In this guide, node A has a replication channel reading from node B, and node B has a channel reading from node A. Each server can therefore act as a source and a replica.

MySQL replication is asynchronous by default. A transaction can commit on the source before the peer has received and applied it, so the pair can temporarily show different data. A network interruption can leave each node with transactions the other has not seen. Circular replication does not merge conflicting rows, choose a winner, or roll back unsafe writes.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

The safest operational pattern is single writer, ready standby: applications write to one node, while the second receives changes and can be promoted after the first is fenced or unavailable. True multi-writer operation requires application-level ownership rules and tests for partitions, retries, duplicate keys, and failover.

Prerequisites and a safe starting point

  • Two supported MySQL installations, with compatible versions, storage engines, and database schemas.
  • Stable connectivity between the VPS instances over a private network, VPN, or a firewall-restricted MySQL port. Do not expose replication credentials to the public internet unnecessarily.
  • Unique DNS names or fixed private addresses for node A and node B, synchronized clocks, and sufficient disk for binary and relay logs.
  • Binary logging enabled on both servers. Each server must retain the binary-log events needed by its peer to catch up.
  • A consistent initial dataset. Existing databases should be copied with a consistent snapshot or logical backup; a new deployment should create the schema before channels start.
  • A dedicated replication account on each server with only the privileges required by the installed MySQL version.
  • An independent backup and a rollback plan. Replication keeps mistakes and accidental deletes moving between servers; it is not a backup.

Before production writes are enabled, decide which node is allowed to write, how the application discovers the current writer, and how you will fence the old writer during a failure. A manual promotion procedure is better than allowing both nodes to accept traffic without a tested conflict policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the MySQL configuration baseline

Use a unique positive integer for server_id on every server. The following values are examples: 101 for node A and 102 for node B. The values only need to be unique within the replication topology.

Node A example

[mysqld]
server_id=101
log_bin=/var/lib/mysql/binlog
relay_log=/var/lib/mysql/relay-bin
log_replica_updates=ON
gtid_mode=ON
enforce_gtid_consistency=ON
auto_increment_increment=2
auto_increment_offset=1

Node B example

[mysqld]
server_id=102
log_bin=/var/lib/mysql/binlog
relay_log=/var/lib/mysql/relay-bin
log_replica_updates=ON
gtid_mode=ON
enforce_gtid_consistency=ON
auto_increment_increment=2
auto_increment_offset=2

Choose log and relay-log locations with enough capacity and monitor them. log_replica_updates keeps transactions received through replication in the local binary log, which is appropriate for a circular topology and helps the peer obtain events after a role change. Apply the settings in the server configuration used by your distribution, then restart MySQL when the configuration requires it.

On MySQL 8.0.26 and later, the startup option that prevents automatic channel startup is skip_replica_start. Older releases use the older skip_slave_start spelling. Use the option that matches your release while you are seeding data and configuring channels.

Enable GTIDs correctly

GTIDs identify transactions independently of a particular binary-log file and position. With GTIDs enabled on both nodes, SOURCE_AUTO_POSITION=1 allows a rejoining node to request the transactions it is missing instead of requiring hand-maintained file and position values.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a new installation, set gtid_mode=ON and enforce_gtid_consistency=ON on both nodes before creating the channels. For an existing non-GTID topology, do not simply change one server and restart it. A safe conversion requires both servers to be made read-only, replication to be allowed to catch up, and all non-GTID transactions to be cleared from the topology before the servers are stopped and restarted with GTID mode enabled. Follow the conversion sequence for your exact MySQL release, because a server cannot accept non-GTID transactions once the final GTID state is enforced.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

After enabling GTIDs, take a new backup. Backups and binary logs containing transactions without GTIDs may not be usable to restore or initialize a GTID-enabled server.

Create reciprocal replication accounts

Node B needs an account that node A can use, and node A needs an account that node B can use. Create each account locally on the server that will be the source of that connection. Restrict the account host to the peer’s private address or a narrowly scoped network rather than using an unrestricted host pattern.

Account on node A for connections from node B

CREATE USER 'repl_from_a'@'10.0.0.12' IDENTIFIED BY 'use-a-secret-manager';
GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'repl_from_a'@'10.0.0.12';

Account on node B for connections from node A

CREATE USER 'repl_from_b'@'10.0.0.11' IDENTIFIED BY 'use-a-secret-manager';
GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'repl_from_b'@'10.0.0.11';

Replace the example addresses with the actual private addresses. Privilege names and authentication requirements can vary by supported release, so verify the minimum replication privileges for your installed version. Store passwords in a secret manager, rotate them under a change procedure, and use TLS options supported by your deployment when traffic crosses an untrusted network.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Seed both VPS servers with identical data

Replication assumes the starting data is consistent. If node A contains rows that node B does not, or the same primary key contains different values, the first incoming transaction can fail or create an application-visible divergence.

  1. Stop or quiesce application writes, or otherwise obtain a transactionally consistent snapshot.
  2. Take a physical snapshot or logical backup using a method appropriate for your storage engine and workload.
  3. Restore that snapshot on the other node, including schemas, required users, and table definitions.
  4. Confirm that both nodes have the same schema and that all tables intended for replication use compatible storage engines.
  5. Keep the replication channels stopped until the restore is complete and the backup represents the intended starting point.

For a cold start, create the schema on both nodes before starting either channel. Do not use a stale dump from before the final schema migration and then expect replication to repair structural differences.

Configure the channel from node A to node B

In the commands below, “A to B” means node B reads transactions from node A. Run the commands on node B, because the replica stores the source connection information.

STOP REPLICA;
CHANGE REPLICATION SOURCE TO
  SOURCE_HOST='node-a.example.internal',
  SOURCE_PORT=3306,
  SOURCE_USER='repl_from_a',
  SOURCE_PASSWORD='use-a-secret-manager',
  SOURCE_AUTO_POSITION=1;
START REPLICA;

On MySQL versions before 8.0.23, the equivalent statement is CHANGE MASTER TO, and the start command is START SLAVE. The newer names are preferred on current 8.0 releases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Configure the reciprocal channel from node B to node A

Run the reciprocal configuration on node A. Node A will read node B’s binary log and apply transactions that it does not already have in its GTID set.

STOP REPLICA;
CHANGE REPLICATION SOURCE TO
  SOURCE_HOST='node-b.example.internal',
  SOURCE_PORT=3306,
  SOURCE_USER='repl_from_b',
  SOURCE_PASSWORD='use-a-secret-manager',
  SOURCE_AUTO_POSITION=1;
START REPLICA;

Use the actual private hostname or address, and ensure the firewall permits the source connection on the MySQL port. A channel should be stopped before replacing its source definition so an old connection or stale credentials cannot remain active.

Prevent AUTO_INCREMENT collisions

If both servers can insert into the same tables, the default auto_increment_increment of 1 can generate the same next value on both nodes. Set the increment to 2 on both servers and use different offsets:

Server auto_increment_increment auto_increment_offset Generated sequence
Node A 2 1 Odd values
Node B 2 2 Even values

These are server-wide settings. They affect every AUTO_INCREMENT column on that server, not just one table, and session-level overrides can change behavior for a particular connection. Check all tables and application connection settings before relying on this scheme.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Offsets prevent generated-key collisions; they do not resolve two updates to the same existing row, conflicting unique values, or transactions that were already inserted with overlapping IDs. If a table uses application-generated keys, UUIDs, or another allocator, document that scheme separately and test it during failover.

Define a write policy before going live

Recommended: one active writer

Direct application writes to one node and keep the peer replicating as a standby. During a failure, fence or isolate the old writer, promote the peer, and then move application traffic. This avoids most conflict classes while retaining a second VPS for recovery.

Multi-writer only with explicit safeguards

If both nodes must accept writes, define table ownership or key-space ownership, deterministic retry behavior, and a rule for transactions that touch shared rows. Test simultaneous updates, duplicate keys, network partitions, application reconnects, and a node returning after an outage. AUTO_INCREMENT offsets alone are not a multi-writer conflict strategy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Fence during a network partition

When the link between nodes fails, each server may continue accepting writes and diverge. Use an external leader decision, a fencing mechanism, or an application-level lock so only one side remains writable. Do not promote both nodes merely because each still accepts local connections.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate both replication threads

On each node, inspect the channel after starting it:

SHOW REPLICA STATUSG

Confirm that the receiver and applier threads are running, the last-error fields are empty, and the retrieved and executed GTID sets advance. On older releases, use the equivalent status command and older thread field names.

Run a disposable, non-production test schema only after the initial data is synchronized:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. On node A, insert a uniquely identifiable test row and verify that it appears on node B.
  2. On node B, insert a different test row and verify that it appears on node A.
  3. Record transaction identifiers and timestamps so an operator can distinguish delayed delivery from a missing transaction.
  4. Remove the test data according to the same writer policy you will use in production.

Also test an intentional promotion: stop application writes to the active node, fence it, direct the application to the peer, and verify that new connections use the promoted writer. Rejoining the old node should use a consistent re-provisioning process or GTID auto-positioning, not an unexamined restart of stale channels.

Backups, monitoring, and capacity

Maintain backups independently of replication, including a fresh backup after GTID mode is enabled. A replicated delete, corrupted transaction, or application mistake can reach both nodes before anyone notices.

Monitor both VPS instances for:

  • Stopped receiver or applier threads and non-empty last-error fields.
  • Increasing replication lag and GTID sets that stop advancing.
  • Binary-log and relay-log growth, approaching disk limits, and failed log rotation.
  • Expired or invalid TLS certificates when encrypted replication is used.
  • Divergent row counts or checksums for important tables.
  • Unexpected changes in the current-writer or fencing state.

Set retention and rotation according to the time needed to recover a disconnected node. Deleting binary logs too aggressively can leave a peer unable to catch up; retaining them indefinitely can exhaust a VPS disk.

Failure modes and recovery decisions

Duplicate-key or row conflicts

Stop one writer and preserve the error, binary logs, and status output. Common causes are concurrent writes to the same logical row, reused server_id values, or unsafe key generation. Compare the conflicting data and repair it from a known-good backup or controlled SQL before restarting replication.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Errant transactions

An errant transaction is a transaction present in one GTID set that should not be applied to the other server. Do not skip an error casually. Identify the transaction, determine whether its data must be retained, and repair the affected data before using a controlled GTID correction procedure.

Network partition

Treat a partition as a split-brain incident, not as a harmless delay. Fence one side, preserve both nodes’ logs, and decide which transaction history is authoritative. Re-provisioning the losing side may be safer than attempting to merge unknown concurrent writes.

Version mismatch

Use a supported MySQL compatibility path and test upgrades before changing one member of the pair. Statement names, startup options, authentication defaults, and replication compatibility can differ between releases.

Storage exhaustion

Replication can stop when binary or relay logs cannot be written. Free space only after confirming the logs are no longer required for a peer’s recovery objective, then correct retention and alerting so the condition does not recur.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How this design compares with other replication choices

Architecture Write model Consistency behavior Operational implications
Circular asynchronous replication Best operated with one active writer; both nodes can technically be sources Transactions are applied asynchronously and can lag or diverge during a partition Uses standard MySQL servers, but requires fencing, conflict procedures, backups, and rejoin drills
Semisynchronous replication Usually still organized around a designated writer A commit waits for at least one replica to acknowledge receipt and logging; it is not synchronous commit on both nodes Can reduce the loss window, but adds acknowledgement and timeout behavior. The documented default for rpl_semi_sync_master_timeout is 10,000 milliseconds
Synchronous replication associated with NDB Cluster Uses a different clustered architecture Synchronous behavior rather than ordinary asynchronous source-to-replica delivery Not a drop-in setting for the two ordinary MySQL VPS configuration described here

Classic circular replication is most practical when two VPS servers must provide standby capacity and the application can enforce a single writer. Requirements for simultaneous multi-primary writes or synchronous consistency justify evaluating a clustering architecture separately rather than stretching this topology beyond its safety envelope.

Operational checklist

  • Each node has a unique server_id, binary logging, durable relay-log storage, and enough disk.
  • GTID mode and GTID consistency are enabled consistently, or an existing topology has completed a documented conversion.
  • Both nodes started from a consistent dataset.
  • Each reciprocal replication account is restricted, credentialed securely, and tested over the private network.
  • Both channels use the current syntax for the installed version and SOURCE_AUTO_POSITION=1.
  • AUTO_INCREMENT offsets are documented for every server that can generate keys.
  • The application has one declared writer or a tested multi-writer conflict design.
  • Promotion, fencing, backup restoration, and rejoin have been rehearsed.
  • Alerts cover thread stoppage, lag, GTID stagnation, log growth, certificate expiry, and data divergence.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Database administrationGTIDHigh AvailabilityMySQLReplicationVPS

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.