managing-database-replication

0
0
Source

Process use when you need to work with database scalability. This skill provides replication and sharding with comprehensive guidance and automation. Trigger with phrases like "set up replication", "implement sharding", or "scale database".

Install

mkdir -p .claude/skills/managing-database-replication && curl -L -o skill.zip "https://mcp.directory/api/skills/download/5446" && unzip -o skill.zip -d .claude/skills/managing-database-replication && rm skill.zip

Installs to .claude/skills/managing-database-replication

About this skill

Database Replication Manager

Overview

Configure and manage database replication topologies for PostgreSQL (streaming replication, logical replication), MySQL (source-replica, group replication), and MongoDB (replica sets). This skill covers primary-replica setup, read scaling through replica routing, failover automation, replication lag monitoring, and conflict resolution for multi-primary configurations.

Prerequisites

  • Superuser or replication-role credentials on primary and replica servers
  • Network connectivity between all replication nodes (verify with pg_isready or mysqladmin ping)
  • psql, mysql, or mongosh CLI tools installed on all nodes
  • Matching major database versions across all replication nodes
  • Sufficient disk space on replicas (equal to or greater than primary)
  • SSH access to replica servers for initial base backup transfer

Instructions

  1. Choose the replication topology based on requirements:

    • Single primary + read replicas: Best for read-heavy workloads. All writes go to primary; reads distributed across replicas.
    • Multi-primary (active-active): Best for geographic distribution. Requires conflict resolution. Use PostgreSQL logical replication or MySQL Group Replication.
    • Cascading replication: Replica A replicates from primary, Replica B replicates from Replica A. Reduces primary load for many replicas.
  2. For PostgreSQL streaming replication, configure the primary:

    • Set wal_level = replica, max_wal_senders = 10, max_replication_slots = 10
    • Create replication user: CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'secure_password'
    • Add replication entry to pg_hba.conf: host replication replicator replica_ip/32 scram-sha-256
    • Reload configuration: SELECT pg_reload_conf()
  3. Initialize the replica with a base backup: pg_basebackup -h primary_host -U replicator -D /var/lib/postgresql/data -Fp -Xs -P -R. The -R flag creates standby.signal and configures primary_conninfo automatically.

  4. For MySQL source-replica replication, configure the source:

    • Set server-id = 1, log_bin = mysql-bin, binlog_format = ROW
    • Create replication user: CREATE USER 'replicator'@'replica_ip' IDENTIFIED BY 'secure_password'; GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'replica_ip'
    • Record binary log position: SHOW MASTER STATUS
  5. Configure the MySQL replica: CHANGE REPLICATION SOURCE TO SOURCE_HOST='primary_host', SOURCE_USER='replicator', SOURCE_PASSWORD='...', SOURCE_LOG_FILE='mysql-bin.000001', SOURCE_LOG_POS=154; START REPLICA.

  6. For MongoDB replica sets: initialize with rs.initiate({_id: "rs0", members: [{_id: 0, host: "node1:27017"}, {_id: 1, host: "node2:27017"}, {_id: 2, host: "node3:27017"}]}). MongoDB handles leader election and failover automatically.

  7. Monitor replication lag continuously:

    • PostgreSQL: SELECT client_addr, state, sent_lsn, write_lsn, flush_lsn, replay_lsn, (sent_lsn - replay_lsn) AS lag_bytes FROM pg_stat_replication
    • MySQL: SHOW REPLICA STATUS\G (check Seconds_Behind_Source)
    • MongoDB: rs.printReplicationInfo() and rs.printSecondaryReplicationInfo()
  8. Configure application-level read routing: direct write queries to the primary connection and read queries to a load-balanced replica pool. Use connection poolers (PgBouncer, ProxySQL) or application middleware for automatic routing.

  9. Set up automated failover using Patroni (PostgreSQL), MySQL InnoDB Cluster + MySQL Router, or MongoDB's built-in election mechanism. Test failover by stopping the primary and verifying the replica promotes automatically within the target RTO.

  10. Configure alerting for replication lag exceeding 10 seconds, replication slot inactive for more than 1 hour, and replica connection drops. Stale replication slots in PostgreSQL cause WAL accumulation and can fill the disk.

Output

  • Replication configuration files for primary and replica nodes
  • Base backup and initialization scripts for setting up new replicas
  • Replication monitoring queries with lag measurement and health checks
  • Failover runbook with manual and automated promotion procedures
  • Read routing configuration for application or connection pooler

Error Handling

ErrorCauseSolution
Replication lag increasing steadilyReplica cannot keep up with primary write volumeCheck replica I/O and CPU; increase max_parallel_workers on replica; consider upgrading replica hardware; reduce write-heavy batch operations on primary
replication slot is inactive warningReplica disconnected or paused, WAL accumulating on primaryReconnect replica; if permanently removed, drop the slot with SELECT pg_drop_replication_slot('slot_name') to prevent disk fill
could not connect to primary on replicaNetwork partition, primary down, or authentication failureVerify network connectivity; check pg_hba.conf entries; confirm replication user credentials; check primary process status
Replica has diverged from primarySplit-brain after failed failover or manual writes to replicaRe-initialize replica from fresh base backup; for PostgreSQL, use pg_rewind if timeline divergence is small
Conflict in logical replicationSame row modified on both publisher and subscriberConfigure conflict resolution policy; use UPDATE conflict handler; design schema to avoid cross-node writes to same rows

Examples

Setting up PostgreSQL read replicas for a web application: A primary database handles 2,000 writes/second but read traffic is 10x higher. Two streaming replicas are added with PgBouncer routing read queries to replicas in round-robin. Result: primary CPU drops from 90% to 40%, read latency improves by 60%.

Automated failover with Patroni: A 3-node PostgreSQL cluster managed by Patroni with etcd for consensus. When the primary fails, Patroni promotes the most up-to-date replica within 10 seconds. Application reconnects automatically through the Patroni-managed VIP or DNS endpoint.

Cross-region logical replication for compliance: EU customer data must stay in EU region. Logical replication publishes only non-PII tables to the US region replica. EU application reads locally; US analytics queries use the replicated subset. Publication filter: CREATE PUBLICATION us_analytics FOR TABLE orders, products, categories.

Resources

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2412

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

django-view-generator

jeremylongshore

Generate django view generator operations. Auto-activating skill for Backend Development. Triggers on: django view generator, django view generator Part of the Backend Development skill category. Use when working with django view generator functionality. Trigger with phrases like "django view generator", "django generator", "django".

15

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.