Loading...

We've detected that your browser language is Chinese. Would you like to visit our Chinese website? [ Dismiss ]
By: Dylan

Microsoft SQL Server Always On Availability Groups (AG) provide high availability and disaster recovery for mission-critical databases. At the same time, SQL Server Replication supports data distribution, reporting offloading, incremental synchronization, and cross-server data consolidation.

In most enterprise environments, these two technologies are used together to build resilient data pipelines that continue operating even after a replica failover—without disrupting downstream subscribers.

However, database administrators often encounter challenges due to native limitations between Availability Groups and replication. By default, databases hosted in AGs cannot be directly configured as replication publishers. Without proper configuration, replication can break entirely after an automatic or manual failover.

This guide walks through configuring replication with Always On Availability Groups. It includes required prerequisites, detailed steps and common runtime issues,

Supported Scenarios and Limitations of Always On AG

Before we get started, please know the Always On AG and SQL Server replication supported scenario and limitation:

Supported Replication Types:

  • Transactional Replication (fully supported, primary production use case)
  • Snapshot Replication (fully supported)

Unsupported & Incompatible Replication Scenarios:

Microsoft explicitly restricts the following replication topologies with AG-hosted databases:

  • Peer-to-Peer replication
  • Immediate updating subscribers and queued updating subscribers
  • Oracle publishing from AG databases
  • Merge replication (limited functionality, not recommended for production)

Key Architectural Rules:

  1. Secondary replicas cannot act as active publishers. Only the current AG primary replica can publish data to replication subscribers. Secondary replicas remain passive failover targets for the publisher role.
  2. Replication agents query the AG listener endpoint, not individual replica hostnames.
  3. The sp_redirect_publisher system stored procedure maps the original publisher instance to the static AG listener. This is the core mechanism that preserves replication after failover.
  4. All AG replicas must be registered on the remote distributor to accommodate failover promotion.

If the Aways On AG can meet your requirements, we will also introduce an alternative for easier and more powerful replication solution in this article.

Prerequisites for Configuring Replication with Always On AG

Before you begin setting up, please ensure you satisfy all infrastructure, edition, and configuration prerequisites.

1. You require SQL Server Enterprise Edition across all Availability Group replica nodes. Basic AG and replication integration is fully supported starting with SQL Server 2016. Distribution database high availability via Availability Groups is supported in SQL Server 2016 SP2 CU3, SQL Server 2017 CU6, and all later releases.

2. Your AG needs to be fully already configured with healthy primary and secondary replicas, synchronized user databases, and no unresolved AG health warnings.

3. The SQL Server Replication feature needs to be installed on every node in the Availability Group cluster, not only the primary replica. Replication agents and metadata require consistent binaries across all potential failover publishers.

4. A standalone remote SQL Server Distributor is highly recommended for production. Local distributors are supported but eliminate HA separation and increase complexity. The distributor manages all replication metadata, agent jobs, and transaction log delivery.

5. A DNS-named Availability Group Listener is a must for this integration. The listener provides a static network endpoint that remains unchanged during AG failover, which powers transparent replication publisher redirection.

6. Security & Network Permissions need to be configured correctly.

  •  Sysadmin server role permissions on all AG replicas, distributor, and subscriber servers
  • Consistent Windows logins, service accounts, and permissions across all replica nodes
  • Unrestricted network file share access for replication snapshot working directories
  • Functional Kerberos authentication to eliminate connection authentication failures

7. AG user databases need to be in the FULL recovery model, with transaction log backups configured to support transactional replication log reading.

How to Configure Replication with Always On Availability Groups

Follow these steps below in your SQL Server environment.

Step 1: Configure the Distributor and Distribution Database

The Distributor is the heart of replication. It stores the distribution database that holds metadata and transaction commands. This is how to set up replication distributor and distribution database

► Option A: Standalone Distributor (All Supported Versions)

1. Connect to the Distributor instance in SQL Server Management Studio (SSMS).

2. Right-click Replication and select Configure Distribution.

configure distribution SQL Server Management Studio

3. Follow the wizard to set the instance as its own Distributor, specify a snapshot folder, and create the distribution database.

4. Alternatively, use T-SQL:

USE master;
GO
EXEC sp_adddistributor @distributor = @@SERVERNAME, @password = N'StrongPassword!';
GO
EXEC sp_adddistributiondb @database = N'distribution';
GO

► Option B: Distribution Database in an Availability Group (SQL Server 2016 SP2-CU3+ / 2017 CU6+)

If you require HA for the Distributor, you can place the distribution database in its own AG. This configuration requires careful setup, but the key requirement is that the Publisher and Distributor need to be on separate SQL Server instances. The distribution database AG need to have its own listener.

Step 2: Configure the Publisher on the Primary Replica

With the Distributor ready, configure the database for publication on the current primary replica.

1. Connect to the primary replicainstance.

2. Enable the database for transactional replication:

USE [YourDatabaseName];
GO
EXEC sp_replicationdboption
    @dbname = N'YourDatabaseName',
    @optname = N'publish',
    @value = N'true';
GO

3. Create the publication. Important: At this stage, you still use the physical server name of the primary replica, not the AG Listener. The redirection to the listener happens in a later step.

USE [YourDatabaseName];
GO
EXEC sp_addpublication
    @publication = N'YourPublicationName',
    @description = N'Transactional publication of database.',
    @sync_method = N'concurrent',
    @retention = 336,
    @allow_push = N'true',
    @allow_pull = N'true',
    @allow_anonymous = N'false',
    @enabled_for_internet = N'false',
    @snapshot_in_defaultfolder = N'true',
    @compress_snapshot = N'false',
    @ftp_port = 21,
    @allow_subscription_copy = N'false',
    @add_to_active_directory = N'false',
    @repl_freq = N'continuous',
    @status = N'active',
    @independent_agent = N'true',
    @immediate_sync = N'true',
    @allow_sync_tran = N'false',
    @autogen_sync_procs = N'false',
    @allow_queued_tran = N'false',
    @allow_dts = N'false',
    @replicate_ddl = 1,
    @allow_initialize_from_backup = N'true',
    @enabled_for_p2p = N'false',
    @enabled_for_het_sub = N'false';
GO

4. Add articles (tables, views, etc.) to the publication:

USE [YourDatabaseName];
GO
EXEC sp_addarticle
    @publication = N'YourPublicationName',
    @article = N'YourTableName',
    @source_owner = N'dbo',
    @source_object = N'YourTableName',
    @type = N'logbased',
    @description = NULL,
    @creation_script = NULL,
    @pre_creation_cmd = N'drop',
    @schema_option = 0x000000000803509F,
    @identityrangemanagementoption = N'none',
    @destination_table = N'YourTableName',
    @destination_owner = N'dbo',
   @status = 24;
GO

— Repeat for each table you wish to replicate

Step 3: Ensure All Secondary Replica Hosts Are Configured for Replication

Every secondary replica that could become the primary after a failover must be properly configured to host the publication.

On each secondary replica host, perform the following:

1. Add the Distributor(if not already present):

USE master;
GO
EXEC sp_adddistributor
    @distributor = N'YourDistributorServerName',
    @password = N'StrongPassword!';
GO

2. Register each secondary replica with the Distributor. Run this on the Distributorinstance:

USE distribution;
GO
EXEC sp_adddistpublisher
    @publisher = N'SecondaryReplicaHostName',  -- Physical server name of the secondary replica
    @distribution_db = N'distribution',
    @working_directory = N'\\NetworkShare\ReplData',
    @security_mode = 1,                        -- 1 = Windows Authentication
    @trusted = N'false',
    @thirdparty_flag = 0,
    @publisher_type = N'MSSQLSERVER';
GO

— Repeat for each secondary replica that will be a potential publisher

3. Add the subscriber as a linked serveron each secondary replica (required for push subscriptions):

— Run on each secondary replica

EXEC sp_addlinkedserver
    @server = N'SubscriberServerName',
    @srvproduct = N'SQL Server';
GO

Step 4: Configure Secondary Replica Hosts as Replication Publishers

This step completes the configuration on the secondary replicas so that they are fully ready to act as publishers.

On each secondary replica host, execute:

-- This step registers the publication on the secondary
USE [YourDatabaseName];
GO
EXEC sp_replicationdboption
    @dbname = N'YourDatabaseName',
    @optname = N'publish',
    @value = N'true';
GO

Note: Do not attempt to re-create the publication on the secondary. The publication already exists in the database and will be recognized when the database becomes primary.

Step 5: Redirect the Original Publisher to the AG Listener Name

This is the critical step that enables seamless failover. It tells the Distributor that when it cannot reach the original publisher, it should connect to the AG Listener instead.

Run this on the Distributor instance, in the distribution database:

USE distribution;
GO
EXEC sys.sp_redirect_publisher
    @original_publisher = N'PhysicalPrimaryServerName',  -- The original primary's hostname
    @publisher_db = N'YourDatabaseName',
    @redirected_publisher = N'YourAGListenerName';       -- Can include port if non-default, e.g., 'Listener,2233'
GO
Verify the redirection:
USE distribution;
GO
SELECT * FROM MSredirected_publishers;
GO

Step 6: Validate the Configuration

Before creating subscriptions, Microsoft recommends validating that all replicas are properly configured to serve as publishers.

Run this validation on the Distributor:

USE distribution;
GO
DECLARE @redirected_publisher sysname;
EXEC sys.sp_validate_replica_hosts_as_publishers
    @original_publisher = N'PhysicalPrimaryServerName',
    @publisher_db = N'YourDatabaseName',
    @redirected_publisher = @redirected_publisher OUTPUT;
GO

If the validation returns errors, review the previous steps to ensure all secondary replicas have been correctly registered with the Distributor and have the publication database marked for publishing.

Step 7: Create the Subscription

Now create the subscription. And you will need to use T-SQL scripts; the SSMS wizard does not properly handle AG listener scenarios.

►Option A: Push Subscription (Recommended for AG Subscribers)

Create the push subscription at the Publisher using the AG Listener name of the subscriber (if the subscriber database is in an AG) or the physical server name (if not).

-- Run on the publisher (primary replica)
GO

-- Add the subscription
EXEC sp_addsubscription
    @publication = N'YourPublicationName',
    @subscriber = N'SubscriberAGListenerName',   -- Use listener if subscriber is in AG
    @destination_db = N'SubscriberDatabaseName',
    @subscription_type = N'Push',
    @sync_type = N'automatic',
    @article = N'all',
    @update_mode = N'read only',
    @subscriber_type = 0;
GO

-- Add the Distribution Agent job
EXEC sp_addpushsubscription_agent
    @publication = N'YourPublicationName',
    @subscriber = N'SubscriberAGListenerName',
    @subscriber_db = N'SubscriberDatabaseName',
    @job_login = N'DOMAIN\ReplAgentAccount',
    @publication = N'YourPublicationName',
    @job_password = N'StrongPassword!',
    @subscriber_security_mode = 1,               -- 1 = Windows Authentication
    @frequency_type = 64,                        -- 64 = Continuously
    @frequency_interval = 0,
    @frequency_relative_interval = 0,
    @frequency_recurrence_factor = 0,
    @frequency_subday = 0,
    @frequency_subday_interval = 0,
    @active_start_time_of_day = 0,
    @active_end_time_of_day = 235959,
    @active_start_date = 20240101,
    @active_end_date = 99991231,
    @dts_package_location = N'Distributor';
GO

►Option B: Pull Subscription

Pull subscriptions are created at the Subscriber. Use the AG Listener name for the publisher.

-- Run on the subscriber
USE [SubscriberDatabaseName];
GO

-- Add the pull subscription
EXEC sp_addpullsubscription
    @publisher = N'YourAGListenerName',          -- Publisher AG Listener
    @publication = N'YourPublicationName',
    @publisher_db = N'YourDatabaseName',
    @independent_agent = N'True';
GO

-- Add the Distribution Agent job on the subscriber
EXEC sp_addpullsubscription_agent
    @publisher = N'YourAGListenerName',
    @publisher_db = N'YourDatabaseName',
    @publication = N'YourPublicationName',
    @distributor = N'YourDistributorServerName',
    @distributor_security_mode = 1,
    @distributor_login = N'',
    @distributor_password = N'',
    @enabled_for_syncmgr = N'False',
    @frequency_type = 64,
    @frequency_interval = 0,
    @frequency_relative_interval = 0,
    @frequency_recurrence_factor = 0,
    @frequency_subday = 0,
    @frequency_subday_interval = 0,
    @active_start_time_of_day = 0,
    @active_end_time_of_day = 235959,
    @active_start_date = 20240101,
    @active_end_date = 99991231,
    @alt_snapshot_folder = N'',
    @working_directory = N'';
GO

When you create a pull subscription and the subscriber database is in an AG, the distribution agent job is created only on the current primary replica of the subscriber AG. After a failover of the subscriber AG, replication will continue automatically if the original subscriber server remains operational (the job still runs there).

However, for long-term stability, you should eventually disable the job on the old primary and enable/create it on the new primary. See the “Post-Failover Management” section for details.

Step 8: Start the Snapshot Agent and Initialize the Subscriber

Generate the initial snapshot to synchronize the subscriber.

-- Run on the publisher (primary replica)
USE [YourDatabaseName];
GO
EXEC sp_startpublication_snapshot @publication = N'YourPublicationName';
GO

Monitor the snapshot generation and delivery in Replication Monitor or by querying MSsnapshot_history in the distribution database.

Step 9: Add the Original Publisher to Replication Monitor (Optional but Recommended)

For easier monitoring, add the original publisher to Replication Monitor:

1. In SSMS, connect to the Distributor instance.

2. Expand Replication, right-click Replication Monitor, and select Add Publisher.

3. Add the original physical server name of the publisher. Replication Monitor will automatically detect the redirected publisher and display the correct information.

Note: After a failover, Replication Monitor may continue to show the original primary name, but replication functionality is unaffected.

Easier and Professional Replication Solution for Database Failover

While Always On Availability Groups offer high availability, integrating availability groups with replication technologies is a complex operation. If your actual requirements involve achieving read-write separation, visual reporting, or heterogeneous data integration through data distribution, consider a professional database replication solution.

i2Stream provides an enterprise-grade and professional alternative solution that addresses the limitations organizations face when trying to extend Always On AGs beyond pure HA scenarios. No Enterprise edition is required, and it does not rely on Windows Cluster.

Main features and advantages of i2Stream:

  • Non-intrusive CDC:  It uses log‑based change data capture with multi‑threaded parallel processing, offering better replication performance while maintaining sub‑second latency. Because i2Stream is decoupled from the source database’s commit process, it never blocks or slows down your production workload—regardless of how many targets you replicate to.
  • Agentless and simplified architecture: You don’t need to install an agent or software on the production database server, eliminating performance impact and security concerns. And provides a unified dashboard that tracks throughput, latency, and errors in real time, with proactive alerting that prevents issues from escalating
  • Full DDL replication without manual intervention: i2Stream provides integrated DDL and DML synchronization—schema changes (ALTER TABLE, CREATE INDEX, etc.) are automatically captured and replicated to all targets without manual scripting or downtime.
  • Complete data validation: 2Stream includes automated data validation with MD5 checksum comparisons, visual drift analysis, and one‑click repair capabilities.
  • Heterogeneous Support: i2Stream supports homogeneous and heterogeneous replication across 40+ database environments, including Oracle, SQL Server, DB2, MySQL, PostgreSQL, MongoDB, Kafka, Hive, HBase, and major cloud‑native platforms. You can replicate databases between different platforms.

You can click the free trial button below. And we will contact you soon and help you to deploy it on your environemnt and guide you how to use it.

FREE Trial for 60-Day

Common Issues and Troubleshooting

    Issue 1: Replication Agents Fail to Connect After Failover

    Symptoms: Log Reader Agent or Distribution Agent fails with connection errors after an AG failover.

    Common causes:

    • sp_redirect_publisher was not executed or was executed with the wrong parameters
    • The AG Listener name is not resolving correctly in DNS
    • Login permissions are missing on the new primary replica

    Resolution:

    1. Verify redirection: EXEC sys.sp_validate_redirected_publisher
    2. Check that the AG Listener is online and accessible
    3. Ensure SQL Server Agent service account has permissions on all replicas

    Issue 2: “The current transaction cannot be committed…”

    Symptoms: Transactions fail to replicate, with errors about uncommitted transactions.

    Common causes: The distribution database is not properly synchronized, or there are conflicts during AG synchronization.

    Resolution:

    • Check the synchronization state of all AG databases
    • Review the SQL Server error log for AG-related errors
    • If the distribution database is in an AG, ensure the monitoring job is functioning correctly

    Issue 3: Snapshot Agent Fails on Availability Database

    Symptoms: Snapshot Agent reports “Could not retrieve agent status” or similar errors when the database is in an AG.

    Common causes: The database was added to the AG before replication was fully configured, or Contained AG is being used (SQL Server 2022).

    Resolution:

    • Configure replication before adding the database to the AG
    • For SQL Server 2022, verify you’re not using Contained Availability Groups for replication scenarios
    • Ensure the replication feature is installed on all replicas

    Issue 4: Log Reader Agent Still Trying Old Primary After Failover

    Symptoms: After failover, the Log Reader Agent continues attempting to connect to the former primary.

    Common causes: sp_redirect_publisher was executed on the wrong database or with incorrect parameters.

    Resolution:

    1. On the Distributor, in the distribution database, verify the redirection:

    SELECT * FROM MSredirected_publishers;

    2. If incorrect, drop and recreate the redirection:

    EXEC sys.sp_redirect_publisher
        @original_publisher = N'PhysicalServerName',
        @publisher_db = N'YourDatabase',
    @redirected_publisher = N'AGListenerName';

    3. Restart the Log Reader Agent job

    Issue 5: Replication Monitor Shows Wrong Publisher Name

    Symptoms: After failover, Replication Monitor continues to display replication information under the name of the original primary instance.

    Explanation: This is a known behavior. Replication Monitor is unable to adjust the name of the publishing instance after failover and continues to display the original primary name.

    Resolution: This is cosmetic only; replication functionality is not affected. Tracer tokens entered on the new publisher using T-SQL will be visible in Replication Monitor.

    Conclusion

    Configuring replication with Always On Availability Groups transforms your SQL Server infrastructure from a simple HA solution into a comprehensive data distribution platform with built-in resiliency.

    But if you want an easier and enterprise-grade database replication solution, i2Stream is a better choice. It provides non-intrusive CDC and agentless architecture to continuously replicate data between different database platforms.

    Dylan
    Dylan is a data protection specialist and a senior content writer at Information2 with more than 6 years of experience. His passion for writing and sharing data protection solutions such as data backup, replication, high availability and other technology information.

    More Related Articles

    Table of Contents:
    Stay Updated on Latest Tips
    Subscribe to our newsletter for the latest insights, news, exclusive content. You can unsubscribe at any time.
    Subscribe
    Ready to Enhance Business Data Security?
    Start a 60-day free trial or view demo to see how Info2soft protects enterprise data.
    {{ country.name }}
    Please fill out the form and submit it, our customer service representative will contact you soon.
    By submitting this form, I confirm that I have read and agree to the Privacy Notice.
    {{ isSubmitting ? 'Submitting...' : 'Submit' }}