Always On Availability Groups Across AZs on EC2

Before you run any command, double-check it

Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.

Sometimes RDS Multi-AZ isn’t enough, because you need a readable secondary, a third replica in another Region or full control of the cluster. Then you build a SQL Server Always On AWS setup yourself, with two or more EC2 instances, a Windows failover cluster, an availability group and a listener spread across Availability Zones.

You’ll deploy a two-node, multi-subnet availability group with AWS Launch Wizard on SQL Server 2022 Developer edition, check its health and fail it over by hand. After that you’ll meet the two problems EC2 availability groups run into in real life: slow listener connections, and logins that don’t follow the database.

TimeYou needBy the end you can
3 to 4 hours (Launch Wizard needs a few hours to build; you can step away)Lessons 45 and 54 done (you know Managed AD and Multi-AZ), signed in to the console as saat-admin. Cost: about USD 4 if you delete it the same day: Developer edition has no SQL license charge, so you pay for Windows instances, the directory and the Remote Desktop gateway. Launch Wizard builds its own VPC, so saat-vpc isn’t touched.Explain WSFC, availability groups, listeners and multi-subnet failover, deploy an AG with Launch Wizard, check replica health, fail over by hand, and keep logins and connection strings working on every replica.

What it is, in one line

SQL Server Always On on AWS means running a Windows failover cluster and an availability group on EC2 instances in different Availability Zones, with a listener for clients to connect to.

In Simple Words

Two kitchens, one phone number

Picture a restaurant that opens a second kitchen in another building, where every order written in the main kitchen is copied to the second one at the same moment. Customers ring one phone number and get put through to whichever kitchen is in charge that day, so if the main kitchen floods, the manager says “the second kitchen is in charge now”, the number points there, and customers notice a short pause instead of a closed restaurant. The staff list at the door, though, is kept by each kitchen on its own, and a new waiter added only at the main kitchen won’t be let into the second one, which is the login problem you’ll fix later.

Engineer's View

How an availability group works on EC2

A Windows Server Failover Cluster (WSFC) joins the nodes, with a witness (file share or cloud) for quorum. The availability group replicates user databases from the primary replica to the secondaries. Synchronous commit between AZs gives you no data loss with automatic failover, and asynchronous suits other Regions. Enterprise and Developer editions allow readable secondaries and several databases per group, while Standard only has Basic AGs (one database, no reads).

On EC2 every node sits in its own subnet, so the cluster and the listener need one secondary private IP per subnet, and only the IP in the primary’s subnet is online. DNS returns both IPs, which is why clients should use MultiSubnetFailover=True to try them in parallel. The domain is usually AWS Managed Microsoft AD.

The AG copies only what’s inside user databases. Logins, Agent jobs, linked servers and credentials live in master and msdb, so you have to create them on every replica, and SQL logins need the same SID. AWS Launch Wizard builds the whole stack from a form, using CloudFormation and Systems Manager behind the scenes.

How it works, step by step

This is what goes on when the primary fails or you fail over yourself.

1The cluster notices

Either WSFC health checks fail on the primary node, or you start a manual failover from the secondary.

Multi-subnet SQL Server availability group on EC2 with a two-IP listener

2The secondary becomes primary

Since commits were synchronous, the secondary already has every committed transaction, so it takes over and starts accepting writes.

3The listener moves subnets

The listener IP in the old subnet goes offline and the one in the new subnet comes online, and clients reconnect using the listener name.

4Choose between EC2 and RDS

It’s the same feature with a different owner:

Always On on EC2 compared with RDS Multi-AZ, building blocks and gaps

If RDS Multi-AZ covers what you need, use it. Build AGs on EC2 only when you need something only EC2 offers, and accept that Windows, the cluster and AD are now yours to run as well.

✅ Checkpoint: You can explain WSFC, the AG, synchronous vs asynchronous commit and why a multi-subnet listener has two IPs.

Hands-on lab: deploy and fail over a two-node AG

1Deploy the availability group with Launch Wizard

In the console, open AWS Launch Wizard in ap-south-1, pick Microsoft SQL Server and then Create deployment. Use these settings and leave everything else at the defaults:

  • Deployment type: Always On availability groups, on Windows.
  • Application name: saat-ag; you can turn on SNS notifications to saat-alerts if you want them.
  • Infrastructure: create a new VPC across two Availability Zones, and a new AWS Managed Microsoft AD with domain corp.saatvedha.lab and NetBIOS name SAAT.
  • SQL Server: SQL Server 2022 Developer on Windows Server 2022, two nodes, availability group name saat-ag, listener saat-agl, and a database named AgShop if the form offers one.
  • Instance size: the smallest the form allows (for example m6i.large) with gp3 volumes.

Check the cost estimate, deploy, and come back in a couple of hours. Once it shows Completed, connect to the first SQL node as the domain admin with Fleet Manager Remote Desktop (or the Remote Desktop Gateway it built) and open PowerShell as administrator.

AWS Launch Wizard deployment saat-ag completed with two SQL Server nodes and an availability group listener
The finished Launch Wizard deployment, with two SQL Server nodes in two zones, the domain, the AG and its listener.

2Check the cluster, the AG and the listener

On SQLNODE1, paste this whole block (use your node names if Launch Wizard named them differently):

$n1 = 'SQLNODE1'; $n2 = 'SQLNODE2'
Get-ClusterNode | Select-Object Name, State
Get-ClusterResource | Where-Object ResourceType -eq 'IP Address' | Select-Object Name, State
sqlcmd -S $n1 -E -W -Q "SELECT ar.replica_server_name, rs.role_desc, rs.synchronization_health_desc, ar.availability_mode_desc FROM sys.dm_hadr_availability_replica_states rs JOIN sys.availability_replicas ar ON ar.replica_id = rs.replica_id"

You should see something like this:

Name     State
----     -----
SQLNODE1    Up
SQLNODE2    Up

Name                 State
----                 -----
Cluster IP 10.0.1.100   Online
Cluster IP 10.0.3.100  Offline
saat-ag_10.0.1.200      Online
saat-ag_10.0.3.200     Offline

replica_server_name role_desc synchronization_health_desc availability_mode_desc
------------------- --------- --------------------------- ----------------------
SQLNODE1            PRIMARY   HEALTHY                     SYNCHRONOUS_COMMIT
SQLNODE2            SECONDARY HEALTHY                     SYNCHRONOUS_COMMIT

You’ve got two nodes in two subnets and synchronous commit, and each cluster name and the listener have one IP online (in the primary’s subnet) and one offline. That offline IP is normal, and it’s what Break 1 is about.

3Add a database and data

If AgShop isn’t in the group yet, this block creates it and adds it with automatic seeding, and if it’s already there, it only adds rows:

sqlcmd -S $n1 -E -Q "IF DB_ID('AgShop') IS NULL BEGIN CREATE DATABASE AgShop; ALTER DATABASE AgShop SET RECOVERY FULL; BACKUP DATABASE AgShop TO DISK = 'NUL'; END"
sqlcmd -S $n1 -E -Q "IF NOT EXISTS (SELECT 1 FROM sys.availability_databases_cluster WHERE database_name = 'AgShop') BEGIN ALTER AVAILABILITY GROUP [saat-ag] MODIFY REPLICA ON N'$n2' WITH (SEEDING_MODE = AUTOMATIC); ALTER AVAILABILITY GROUP [saat-ag] ADD DATABASE AgShop; END"
sqlcmd -S $n2 -E -Q "ALTER AVAILABILITY GROUP [saat-ag] GRANT CREATE ANY DATABASE"
Start-Sleep 30
sqlcmd -S saat-agl -E -d AgShop -Q "IF OBJECT_ID('dbo.Orders') IS NULL CREATE TABLE dbo.Orders (OrderId int IDENTITY PRIMARY KEY, Customer nvarchar(100), Amount decimal(10,2)); INSERT dbo.Orders (Customer, Amount) VALUES (N'Asha', 2499.00), (N'Ravi', 1850.00), (N'Meena', 3200.00);" -M
sqlcmd -S $n2 -E -W -Q "SELECT DB_NAME(database_id) AS db, synchronization_state_desc FROM sys.dm_hadr_database_replica_states WHERE is_local = 1"

You should see something like this:

db     synchronization_state_desc
------ --------------------------
AgShop SYNCHRONIZED

AgShop was seeded to SQLNODE2 automatically, without copying any backup files, and it’s SYNCHRONIZED. The -M switch makes sqlcmd use MultiSubnetFailover when it connects to the listener.

SQL Server Always On AWS lab output: replica roles and listener IP resources
Cluster nodes, listener IPs and replica health, roughly like this.

4Fail over by hand

Run the failover on the secondary and then check the roles:

sqlcmd -S $n2 -E -Q "ALTER AVAILABILITY GROUP [saat-ag] FAILOVER;"
Start-Sleep 20
sqlcmd -S $n2 -E -W -Q "SELECT ar.replica_server_name, rs.role_desc FROM sys.dm_hadr_availability_replica_states rs JOIN sys.availability_replicas ar ON ar.replica_id = rs.replica_id"
sqlcmd -S saat-agl -E -M -d AgShop -W -Q "SELECT @@SERVERNAME AS now_serving, COUNT(*) AS orders FROM dbo.Orders"

You should see something like this:

replica_server_name role_desc
------------------- ---------
SQLNODE1            SECONDARY
SQLNODE2            PRIMARY
now_serving orders
----------- ------
SQLNODE2         3

SQLNODE2 is now primary, the listener followed it to the other subnet and all the data is there. You patch Windows and SQL Server on AG nodes with planned failovers like this one, one node at a time, and the interruption is only seconds.

SSMS availability group dashboard showing SQLNODE2 as primary and both replicas synchronized
The AG dashboard in SSMS after the planned failover shows SQLNODE2 as primary with both replicas synchronized.

✅ Checkpoint: Both cluster nodes are Up, the AG is HEALTHY and synchronous, AgShop is SYNCHRONIZED on SQLNODE2, and after a manual failover SQLNODE2 serves the listener with 3 orders.

Break It, Then Fix It

These two show up once real apps start connecting.

1Break it: clients without MultiSubnetFailover

After the failover the listener’s online IP is in the second subnet. Connect a few times with the setting and a few times without it:

function Test-Listener([bool]$Msf) {
  $cs = "Server=saat-agl;Database=AgShop;Integrated Security=SSPI;Connect Timeout=30;TrustServerCertificate=True;MultiSubnetFailover=$Msf"
  $sw = [Diagnostics.Stopwatch]::StartNew()
  $cn = New-Object System.Data.SqlClient.SqlConnection $cs
  try { $cn.Open(); 'connected in {0:N1} s (MultiSubnetFailover={1})' -f $sw.Elapsed.TotalSeconds, $Msf } catch { 'failed after {0:N1} s: {1}' -f $sw.Elapsed.TotalSeconds, $_.Exception.InnerException.Message } finally { $cn.Close() }
}
1..3 | ForEach-Object { Test-Listener $false }
1..3 | ForEach-Object { Test-Listener $true }

You’ll get something like this:

connected in 21.3 s (MultiSubnetFailover=False)
connected in 0.1 s (MultiSubnetFailover=False)
connected in 21.2 s (MultiSubnetFailover=False)
connected in 0.1 s (MultiSubnetFailover=True)
connected in 0.1 s (MultiSubnetFailover=True)
connected in 0.1 s (MultiSubnetFailover=True)

DNS hands back both listener IPs, and without the setting the client tries them one after the other, so whenever the offline IP comes first it sits there for about 21 seconds until TCP gives up. With shorter timeouts the app just fails now and then, which is miserable to debug. Fix: put MultiSubnetFailover=True in every connection string (sqlcmd -M, JDBC multiSubnetFailover=true), and for old clients that can’t do that, set the listener’s RegisterAllProvidersIP to 0 and lower its DNS TTL.

2Break it: a login that only exists on one replica

Create a domain user, give it a login on the current primary only, and test it before and after failing back:

Add-Type -AssemblyName System.Web
$pw = [System.Web.Security.Membership]::GeneratePassword(20, 3)
net user saatapp $pw /add /domain | Out-Null
$cred = New-Object System.Management.Automation.PSCredential('SAAT\saatapp', (ConvertTo-SecureString $pw -AsPlainText -Force))
sqlcmd -S $n2 -E -Q "CREATE LOGIN [SAAT\saatapp] FROM WINDOWS; USE AgShop; CREATE USER [SAAT\saatapp] FOR LOGIN [SAAT\saatapp]; ALTER ROLE db_datareader ADD MEMBER [SAAT\saatapp];"
function Test-AppLogin {
  $job = Start-Job -Credential $cred -ScriptBlock {
    $cn = New-Object System.Data.SqlClient.SqlConnection 'Server=saat-agl;Database=AgShop;Integrated Security=SSPI;TrustServerCertificate=True;MultiSubnetFailover=True'
    try { $cn.Open(); $cm = $cn.CreateCommand(); $cm.CommandText = "SELECT SUSER_NAME() + ' reads ' + CAST(COUNT(*) AS varchar(10)) + ' rows on ' + @@SERVERNAME FROM dbo.Orders"; $cm.ExecuteScalar() }
    catch { $_.Exception.Message } finally { $cn.Close() }
  }
  $job | Wait-Job -Timeout 60 | Receive-Job
}
Test-AppLogin
sqlcmd -S $n1 -E -Q "ALTER AVAILABILITY GROUP [saat-ag] FAILOVER;"
Start-Sleep 20
Test-AppLogin

You’ll get something like this:

SAAT\saatapp reads 3 rows on SQLNODE2
Login failed for user 'SAAT\saatapp'.
Always On problems: slow listener connects and missing login after failover
Here are both problems and their fixes, something like this.

The database user came over with AgShop, but the login lives in master on SQLNODE2 only, so after failing back to SQLNODE1 the app can’t log in at all. Teams run into this more than anything else after their first real failover. Fix: create the login on the other replica as well:

sqlcmd -S $n1 -E -Q "CREATE LOGIN [SAAT\saatapp] FROM WINDOWS;"
Test-AppLogin

You should see something like this:

SAAT\saatapp reads 3 rows on SQLNODE1

Windows logins map by their AD SID, so the user matches straight away. SQL logins have to be created with the same SID on every replica (sp_help_revlogin, or dbatools’ Copy-DbaLogin), and jobs, linked servers and credentials need the same care.

Now for the clean-up. In Launch Wizard > Deployments, select saat-ag and choose Delete, and once it’s done, check nothing was left behind:

aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE DELETE_FAILED --query "StackSummaries[?contains(StackName, 'saat-ag')].[StackName,StackStatus]" --output text
aws ds describe-directories --query "DirectoryDescriptions[?Name=='corp.saatvedha.lab'].[DirectoryId,Stage]" --output text
aws ec2 describe-addresses --query "Addresses[?AssociationId==null].PublicIp" --output text

None of the three commands should print anything.

✅ Checkpoint: You fixed slow listener connections with MultiSubnetFailover and a failed login by creating it on every replica. The Launch Wizard deployment, its stacks, the directory and any spare Elastic IPs have all gone.

This happened at work

The 21-second login nobody could reproduce

A logistics company had moved its tracking database to an availability group across two AZs on EC2. About a week after a routine failover, the drivers’ handheld app started timing out “randomly”, roughly half the time, and yet the developers could never make it happen from their laptops. It took a while to spot that the handhelds used an old driver without MultiSubnetFailover and a 15-second connection timeout. DNS was returning both listener IPs in rotating order, so whenever the offline one came first the connection timed out, while the developers’ tools had the setting on by default and never hit it. A one-line change to the connection string sorted it out. For one legacy app that couldn’t be changed they set RegisterAllProvidersIP to 0, and they added “connect through the listener after a failover” to their failover test script.

Common mistakes and troubleshooting

MistakeWhat happensWhat to do
No MultiSubnetFailover in connection stringsRandom 21-second connects or timeoutsMultiSubnetFailover=True everywhere
Logins created on one replicaLogin failed after failoverCreate on all replicas; same SID for SQL logins
Jobs and linked servers on one nodeThey stop after failoverScript to every replica, make jobs AG-aware
Asynchronous commit between AZsData loss possible on failoverSynchronous inside a Region
No witnessCluster loses quorumFile share or cloud witness
Building AGs when RDS would doExtra work running Windows, AD and the clusterUse RDS Multi-AZ unless you need EC2-only features

Interview questions

Click a question to open it. Each one is phrased the way an interviewer would ask it, and underneath you’ll find why they ask it and one way you could answer in your own words.

Fresher level

1. Can you explain in simple words what an Always On availability group is?

Why they ask this: They’re checking that you understand the basic building block of SQL Server HA and what it sits on.

How you might answer: It’s a SQL Server feature that copies a set of user databases from a primary replica to one or more secondaries, so if the primary fails a secondary can take over. Underneath it there’s a Windows failover cluster doing the health checks and making the failover decision.

2. How would you explain an availability group listener to a new team member?

Why they ask this: They want to see you understand how clients reach an AG without needing to know which node is primary.

How you might answer: I’d say it’s like a front door name that never changes. It’s a virtual network name with its own IPs that always points at the current primary, so the app connects to the listener and after a failover it reaches the new primary without anyone touching the config.

3. What’s the difference between synchronous and asynchronous commit, and when would you use each?

Why they ask this: They want to know you understand the trade-off between data safety and speed and can match it to distance.

How you might answer: With synchronous commit the primary waits until the secondary has hardened the log, so you lose no data but each write is a bit slower, and I’d use it between AZs in the same Region. Asynchronous commit doesn’t wait, which makes it faster but means you can lose some data on failover, so that’s what I’d use for a replica in another Region.

2–5 years experience

4. Apps on AWS randomly take about 20 seconds to connect to the AG listener. What’s causing it?

Why they ask this: They’re checking whether you know how multi-subnet listeners behave on AWS, since this is one of the most common AG problems in the cloud.

How you might answer: On AWS the nodes sit in different subnets, so the listener has two IPs and one of them is always offline. Clients without MultiSubnetFailover=True sometimes try that offline IP first and wait for it to time out. The proper fix is adding MultiSubnetFailover=True to the connection strings, and for an old app that can’t, I’d set RegisterAllProvidersIP=0 with a low TTL.

5. Right after a failover, a user calls and says they can’t log in anymore. What happened?

Why they ask this: They want to see you know logins live outside the AG databases and how you’d keep them in step on every replica.

How you might answer: Most likely the login only exists on the old primary. Logins live in master and master isn’t part of the availability group, so I’d create the login on every replica, using the same SID for SQL logins so the database users stay linked to them.

6. Walk me through how you’d patch the nodes of an availability group with very little downtime.

Why they ask this: They’re looking for a safe rolling patch process where you check health before each step.

How you might answer: I’d patch the secondary first and fail over to it, so users see only a short blip, then patch the old primary and fail back if we need to. Between each step I check synchronization health is good before I move on.

Senior level

7. Design SQL Server HA and DR on EC2 with no data loss inside the Region and only minutes of loss across Regions.

Why they ask this: They want to see how you mix sync and async replicas, and whether you also think about the cluster, identity, clients and testing.

How you might answer: An AG with synchronous replicas in two AZs for zero data loss, plus an asynchronous replica in another Region for DR. The cluster gets a cloud or file share witness, identity comes from Managed AD with trusts, clients go through a multi-subnet listener, and the server objects are scripted. Then I’d monitor AG health and redo queues and test failover and DR on a regular schedule.

8. When would you choose Basic availability groups on Standard edition instead of Enterprise?

Why they ask this: They want to see you can weigh licensing cost against features and explain what the team gives up.

How you might answer: Basic AGs work when one database per AG is enough, nobody needs a readable secondary and Enterprise licensing is too expensive. If we need more than that, I’d look at Enterprise, or at RDS Multi-AZ if its limits suit us.

Quick quiz

Q1. What does a multi-subnet listener on AWS have?

  1. One IP
  2. One IP per subnet
  3. No IP
  4. A public IP
Show answer

B — Only the primary subnet’s IP is online.

Q2. Which setting stops slow listener connections?

  1. Pooling=False
  2. MultiSubnetFailover=True
  3. Encrypt=False
  4. ApplicationIntent=ReadOnly
Show answer

B — It tries all IPs in parallel.

Q3. Why did SAAT\saatapp fail after failback?

  1. Wrong password
  2. Login missing on that replica
  3. Database offline
  4. DNS
Show answer

B — Logins live in master on each node.

Q4. Which commit mode gives no data loss between AZs?

  1. Asynchronous
  2. Synchronous
  3. Delayed
  4. Bulk
Show answer

B — It waits for the secondary.

Q5. What did Launch Wizard save you from doing by hand?

  1. Nothing
  2. Building AD, cluster, AG and listener
  3. Writing SQL
  4. Paying for EC2
Show answer

B — It builds the whole stack.

Quick recap

  • Always On on EC2 = WSFC + availability group + listener across AZs.
  • Multi-subnet listeners have one IP per subnet; use MultiSubnetFailover=True.
  • Logins, jobs and linked servers don’t move with the AG, so create them on every replica.
  • Planned failovers let you patch the nodes one at a time.
  • Prefer RDS Multi-AZ unless you need what only EC2 gives.

Next lesson

Lesson 56: The AWS troubleshooting workflow → That’s where Phase 4 starts, with one repeatable way to find what changed, where it changed and who changed it.

Further reading: SQL Server Always On AWS

If you want to go further with SQL Server Always On AWS, read AWS Launch Wizard for SQL Server and Connect to an Always On availability group listener. The full plan for this course is on the AWS Cloud Administration course page.

Scroll to Top

This website uses cookies

We use a few cookies to keep this site working. If you allow it, we also use Google Analytics to count visits so we can improve our lessons. You can accept all, deny the optional ones, or choose what to allow.