{
  "source_file": "0930",
  "source_platform": "Dev.to",
  "author": "Nishikanta Ray",
  "title_listed": "Master–Slave (Primary–Replica) Replication",
  "keywords": "",
  "domain": "数据处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://dev.to/nishikantaray/master-slave-primary-replica-replication-5210",
  "publish_date": "2025-11-28",
  "corpus_stage": "",
  "notes": "",
  "id": "87d8ce5e935f",
  "collected_at": "2026-10-02T14:05:10",
  "title": "Master–Slave (Primary–Replica) Replication - DEV Community",
  "body_markdown": "If you’re building a modern application that needs speed, availability, and fault tolerance,\nMongoDB replication\nis one of the easiest and most powerful features you can use.\n📌 What Is Master–Slave (Primary–Replica) Replication?\nReplication ensures you have\nmultiple copies\nof your data across different servers.\nIn MongoDB:\nThe\nPrimary\nnode handles all writes.\nSecondary\nnodes replicate data from the primary and handle reads (optional).\nIf the primary fails, MongoDB automatically promotes a secondary → new primary.\nThis setup is known as a\nReplica Set\n, which is MongoDB’s improved version of the old master–slave architecture.\n⭐ Why Do We Need Master–Slave (Primary–Replica) Architecture?\nMaster–slave replication exists because\none single database server cannot handle everything reliably, efficiently, and safely\n. Splitting responsibilities between a\nmaster (primary)\nand\nslaves (replicas)\nsolves several real-world problems.\n📐 MongoDB Replication Architecture\n+-----------------+\n|\nPrimary\n|\n<---\nWrite\n&\nRead\n+-----------------+\n/\n\\\n/\n\\\n+-----------------+\n+-----------------+\n|\nSecondary\n1\n|\n|\nSecondary\n2\n|\n+-----------------+\n+-----------------+\nRead\nOnly\nRead\nOnly\nEnter fullscreen mode\nExit fullscreen mode\n⭐ What Is Slave Replication (Explained Like You’re 5)\nSlave replication means:\nOne database is the\nmaster\n→ accepts all writes\nOther databases are\nslaves/replicas\n→ copy whatever master does\nReplicas stay almost up-to-date with the master\nThink of it like a\nteacher (master)\nwriting on the board, and\n3 students (slaves/replicas)\ncopying everything in real time.\nSometimes students copy late → this is\nreplication lag\n.\n🔁 How Slave Replication Actually Works (Technical Flow)\nBelow is the internal flow, no fluff:\n1. Master records every write into a log\nMySQL → Binary Log (binlog)\nMongoDB → Oplog\nPostgreSQL → WAL Log\nExample log entry:\nUPDATE\nproducts\nSET\nstock\n=\n50\nWHERE\nid\n=\n101\nEnter fullscreen mode\nExit fullscreen mode\n2. Slaves read these logs continuously\nA slave says:\n➡️ “Master, give me the next log entry after position X.”\n3. Slaves apply the changes locally\nWhatever operation appears in the log:\nINSERT\nUPDATE\nDELETE\n…slaves replay them in the same order.\n4. After applying logs → slave becomes synced\nThis cycle repeats\nnon-stop\n.\n⏳ Replication Delay (Lag): Why It Happens\nSlaves may fall behind due to:\nSlow network\nHeavy load on slave\nLarge write burst on master\nSlow disk I/O\nComplex queries running on slave\nWhen the slave is behind, it shows\nold data\ntemporarily.\n🛠️ How Systems Handle Delays\n1️⃣ Read-from-master for critical operations\nApps often use:\nNormal read → from replica (fast)\nCritical read (e.g., after update) → from master\nThis avoids stale data issues.\n2️⃣ “Read-your-own-write” rules\nIf a user writes something (POST/UPDATE):\nYou route that user’s next read to the master only\nUntil replica catches up\nFrameworks like Rails, Laravel, Django already support this.\n3️⃣ Monitoring replication lag\nTools measure:\nreplication_lag\n=\nslave_last_applied_timestamp\n-\nmaster_timestamp\nEnter fullscreen mode\nExit fullscreen mode\nIf lag > X seconds:\n→ temporarily stop sending reads to that replica\n4️⃣ Write concerns (MongoDB)\nMongoDB allows:\n{\nwriteConcern\n:\n{\nw\n:\n\"\nmajority\n\"\n}\n}\nEnter fullscreen mode\nExit fullscreen mode\nMeaning:\n→ Write is successful only when\nmost\nreplicas have it\nThis reduces risk of data inconsistency.\n5️⃣ Semi-Sync Replication (MySQL / PostgreSQL)\nMaster waits until\nat least one slave\nconfirms:\n“Yep, I received the log.”\nThis avoids data loss.\n🔄 How Updates Flow (Example With Steps)\nLet’s use a real example:\nA user updates their profile:\nUPDATE\nusers\nSET\nname\n=\n'\nNishikanta\n'\nWHERE\nid\n=\n5\n;\nEnter fullscreen mode\nExit fullscreen mode\nHere’s what happens:\nStep 1 — Master writes to its DB\nMaster updates row in its storage engine.\nStep 2 — Master logs the change\nMaster adds entry to binlog/oplog:\n{\nop\n:\n\"\nupdate\n\"\n,\nid\n:\n5\n,\nname\n:\n\"\nNishikanta\n\"\n}\nEnter fullscreen mode\nExit fullscreen mode\nStep 3 — Slaves fetch this log\nReplica 1 → “Give me log #520”\nReplica 2 → “Give me log #520”\nMaster streams them.\nStep 4 — Slaves apply changes\nReplica updates:\nid\n=\n5\n→\nname\n=\nNishikanta\nEnter fullscreen mode\nExit fullscreen mode\nStep 5 — Replicas catch up\nOnce all logs are applied → they’re in sync.\n📊 Diagram: How Replication Works (Clean + Blog-Ready)\n┌───────────────────────┐\n│\nMASTER\n│\n│\n(\nPrimary\n-\nAll\nWrites\n)\n│\n└───────┬───────────────┘\n│\nWrites\n→\nBinlog\n/\nOplog\ngenerated\n│\n┌───────────────┴───────────────┐\n│\n│\n┌────────────────────┐\n┌────────────────────┐\n│\nSLAVE\n#\n1\n│\n│\nSLAVE\n#\n2\n│\n│\n(\nReplica\n-\nReads\n)\n│\n│\n(\nReplica\n-\nReads\n)\n│\n└───────┬────────────┘\n└──────────┬─────────┘\n│\n│\n│\nFetch\nlog\ncontinuously\n│\n│\nApply\nupdates\n│\n│\nHandle\nreplication\nlag\n│\n▼\n▼\nUp\n-\nto\n-\ndate\ncopy\nof\nDB\nUp\n-\nto\n-\ndate\ncopy\nof\nDB\nEnter fullscreen mode\nExit fullscreen mode\n🟩 Conclusion\nMaster–slave (primary–replica) replication is one of the most essential techniques for building\nfast, reliable, and highly available\nmodern applications. By separating write operations to the master and distributing read operations across multiple replicas, systems can handle far more traffic, avoid downtime, and guarantee that data remains safe even if a server fails.\nAlthough replication may introduce small delays (replication lag), most real-world systems manage this easily through smart routing, read-after-write strategies, and monitoring tools. The result is a database architecture that provides\nscalability, resilience, and real-time data redundancy\n— all without changing how your application writes data.\nWhether you’re using MongoDB, MySQL, PostgreSQL, or Redis, mastering replication is a core skill that enables you to build applications that stay fast, stay online, and scale gracefully as your users grow.",
  "metadata": {
    "title": "Master–Slave (Primary–Replica) Replication - DEV Community",
    "description": "If you’re building a modern application that needs speed, availability, and fault tolerance, MongoDB... Tagged with distributedsystems, database, architecture, mongodb.",
    "keywords": "distributedsystems, database, architecture, mongodb, software, coding, development, engineering, inclusive, community",
    "author": null,
    "og:type": "article",
    "og:url": "https://dev.to/nishikantaray/master-slave-primary-replica-replication-5210",
    "og:title": "Master–Slave (Primary–Replica) Replication",
    "og:description": "If you’re building a modern application that needs speed, availability, and fault tolerance, MongoDB...",
    "og:site_name": "DEV Community",
    "og:image": "https://media2.dev.to/dynamic/image/width=1000,height=500,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5brbcqu0atnjbjjtl41r.png",
    "twitter:site": "@thepracticaldev",
    "twitter:creator": "@",
    "twitter:title": "Master–Slave (Primary–Replica) Replication",
    "twitter:description": "If you’re building a modern application that needs speed, availability, and fault tolerance, MongoDB...",
    "twitter:card": "summary_large_image",
    "twitter:widgets:new-embed-design": "on",
    "twitter:image:src": "https://media2.dev.to/dynamic/image/width=1000,height=500,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5brbcqu0atnjbjjtl41r.png"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "file": "attachments/87d8ce5e935f/code/body-000.txt",
      "chars": 331,
      "language": "text"
    },
    {
      "file": "attachments/87d8ce5e935f/code/body-001.txt",
      "chars": 46,
      "language": "text"
    },
    {
      "file": "attachments/87d8ce5e935f/code/body-002.txt",
      "chars": 66,
      "language": "text"
    },
    {
      "file": "attachments/87d8ce5e935f/code/body-003.txt",
      "chars": 36,
      "language": "text"
    },
    {
      "file": "attachments/87d8ce5e935f/code/body-004.txt",
      "chars": 47,
      "language": "text"
    },
    {
      "file": "attachments/87d8ce5e935f/code/body-005.txt",
      "chars": 44,
      "language": "text"
    },
    {
      "file": "attachments/87d8ce5e935f/code/body-006.txt",
      "chars": 23,
      "language": "text"
    },
    {
      "file": "attachments/87d8ce5e935f/code/body-007.txt",
      "chars": 833,
      "language": "text"
    }
  ],
  "images": [],
  "audio": [],
  "videos": [],
  "links": [],
  "repair_version": 2,
  "repaired_at": "2026-10-14T10:49:55Z",
  "source_url": "https://dev.to/nishikantaray/master-slave-primary-replica-replication-5210",
  "papers": [],
  "actual_video_files": [],
  "body_chars": 5784,
  "expected_body_images": 0,
  "discovery_status": "ok",
  "delivery_status": "ok",
  "missing_reason": "",
  "raw_html": "attachments/87d8ce5e935f/pages/source.html",
  "local_html": "attachments/87d8ce5e935f/pages/article.html",
  "body_base_path": "attachments/87d8ce5e935f/pages/",
  "body_markdown_path": "attachments/87d8ce5e935f/pages/article.md"
}