Vous êtes sur la page 1sur 74

1

Database Mirroring (SQL Server)


2016-5-16 16 min to read Contributors


Note

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this
feature in new development work, and plan to modify applications that currently use
this feature. Use Always On availability groups instead.

Database mirroring is a solution for increasing the availability of a SQL Server database.
Mirroring is implemented on a per-database basis and works only with databases that
use the full recovery model.
Important

For information about support for database mirroring, restrictions, prerequisites,


recommendations for configuring partner servers, and recommendations for deploying
database mirroring, see Prerequisites, Restrictions, and Recommendations for Database
Mirroring.

Benefits of Database Mirroring


Database mirroring is a simple strategy that offers the following benefits:

 Increases availability of a database.

In the event of a disaster, in high-safety mode with automatic failover, failover


quickly brings the standby copy of the database online (without data loss). In the
other operating modes, the database administrator has the alternative of forcing
service (with possible data loss) to the standby copy of the database. For more
information, see Role Switching, later in this topic.

 Increases data protection.


2

Database mirroring provides complete or almost complete redundancy of the data,


depending on whether the operating mode is high-safety or high-performance.
For more information, see Operating Modes, later in this topic.

A database mirroring partner running on SQL Server 2008 Enterprise or later


versions automatically tries to resolve certain types of errors that prevent reading a
data page. The partner that is unable to read a page requests a fresh copy from
the other partner. If this request succeeds, the unreadable page is replaced by the
copy, which usually resolves the error. For more information, see Automatic Page
Repair (Availability Groups: Database Mirroring).

 Improves the availability of the production database during upgrades.

To minimize downtime for a mirrored database, you can sequentially upgrade the
instances of SQL Server that are hosting the failover partners. This will incur the
downtime of only a single failover. This form of upgrade is known as a rolling
upgrade. For more information, see Upgrading Mirrored Instances.

Database Mirroring Terms and Definitions


automatic failover
The process by which, when the principal server becomes unavailable, the mirror server
to take over the role of principal server and brings its copy of the database online as the
principal database.

failover partners
The two server instances (the principal server or the mirror server) that act as role-
switching partners for a mirrored database.

forced service
A failover initiated by the database owner upon the failure of the principal server that
transfers service to the mirror database while it is in an unknown state.

High-performance mode
The database mirroring session operates asynchronously and uses only the principal
server and mirror server. The only form of role switching is forced service (with possible
data loss).
3

High-safety mode
The database mirroring session operates synchronously and, optionally, uses a witness,
as well as the principal server and mirror server.

manual failover
A failover initiated by the database owner, while the principal server is still running, that
transfers service from the principal database to the mirror database while they are in a
synchronized state.

mirror database
The copy of the database that is typically fully synchronized with the principal database.

mirror server
In a database mirroring configuration, the server instance on which the mirror database
resides.

mirror server
In a database mirroring configuration, the server instance on which the mirror database
resides.

principal database
In database mirroring, a read-write database whose transaction log records are applied
to a read-only copy of the database (a mirror database).

principal server
In database mirroring, the partner whose database is currently the principal database.

redo queue
Received transaction log records that are waiting on the disk of a mirror server.

role
The principal server and mirror server perform complementary principal and mirror
roles. Optionally, the role of witness is performed by a third server instance.

role switching
The taking over of the principal role by the mirror.

send queue
Unsent transaction log records that have accumulated on the log disk of the principal
server.
4

session
The relationship that occurs during database mirroring among the principal server,
mirror server, and witness server (if present).

After a mirroring session starts or resumes, the process by which log records of the
principal database that have accumulated on the principal server are sent to the mirror
server, which writes these log records to disk as quickly as possible to catch up with the
principal server.

Transaction safety
A mirroring-specific database property that determines whether a database mirroring
session operates synchronously or asynchronously. There are two safety levels: FULL and
OFF.

Witness
For use only with high-safety mode, an optional instance of SQL Server that enables the
mirror server to recognize when to initiate an automatic failover. Unlike the two failover
partners, the witness does not serve the database. Supporting automatic failover is the
only role of the witness.

Overview of Database Mirroring


Database mirroring maintains two copies of a single database that must reside on
different server instances of SQL Server Database Engine. Typically, these server
instances reside on computers in different locations. Starting database mirroring on a
database, initiates a relationship, known as a database mirroring session, between these
server instances.

One server instance serves the database to clients (the principal server). The other
instance acts as a hot or warm standby server (the mirror server), depending on the
configuration and state of the mirroring session. When a database mirroring session is
synchronized, database mirroring provides a hot standby server that supports rapid
failover without a loss of data from committed transactions. When the session is not
synchronized, the mirror server is typically available as a warm standby server (with
possible data loss).

The principal and mirror servers communicate and cooperate as partners in a database
mirroring session. The two partners perform complementary roles in the session:
the principal role and the mirror role. At any given time, one partner performs the
principal role, and the other partner performs the mirror role. Each partner is described
5

as owning its current role. The partner that owns the principal role is known as
the principal server, and its copy of the database is the current principal database. The
partner that owns the mirror role is known as the mirror server, and its copy of the
database is the current mirror database. When database mirroring is deployed in a
production environment, the principal database is the production database.

Database mirroring involves redoing every insert, update, and delete operation that
occurs on the principal database onto the mirror database as quickly as possible.
Redoing is accomplished by sending a stream of active transaction log records to the
mirror server, which applies log records to the mirror database, in sequence, as quickly
as possible. Unlike replication, which works at the logical level, database mirroring works
at the level of the physical log record. Beginning in SQL Server 2008, the principal server
compresses the stream of transaction log records before sending it to the mirror server.
This log compression occurs in all mirroring sessions.
Note

A given server instance can participate in multiple concurrent database mirroring


sessions with the same or different partners. A server instance can be a partner in some
sessions and a witness in other sessions. The mirror server instance must be running the
same edition of SQL Server.

In This Section:

 Operating Modes
 Role Switching
 Concurrent Sessions
 Client Connections
 Impact of Pausing a Session on the Principal Transaction Log

Operating Modes

A database mirroring session runs with either synchronous or asynchronous operation.


Under asynchronous operation, the transactions commit without waiting for the mirror
server to write the log to disk, which maximizes performance. Under synchronous
operation, a transaction is committed on both partners, but at the cost of increased
transaction latency.

There are two mirroring operating modes. One of them, high-safety mode supports
synchronous operation. Under high-safety mode, when a session starts, the mirror
server synchronizes the mirror database together with the principal database as quickly
6

as possible. As soon as the databases are synchronized, a transaction is committed on


both partners, at the cost of increased transaction latency.

The second operating mode, high-performance mode, runs asynchronously. The mirror
server tries to keep up with the log records sent by the principal server. The mirror
database might lag somewhat behind the principal database. However, typically, the gap
between the databases is small. However, the gap can become significant if the principal
server is under a heavy work load or the system of the mirror server is overloaded.

In high-performance mode, as soon as the principal server sends a log record to the
mirror server, the principal server sends a confirmation to the client. It does not wait for
an acknowledgement from the mirror server. This means that transactions commit
without waiting for the mirror server to write the log to disk. Such asynchronous
operation enables the principal server to run with minimum transaction latency, at the
potential risk of some data loss.

All database mirroring sessions support only one principal server and one mirror server.
This configuration is shown in the following illustration.

High-safety mode with automatic failover requires a third server instance, known as
a witness. Unlike the two partners, the witness does not serve the database. The witness
supports automatic failover by verifying whether the principal server is up and
functioning. The mirror server initiates automatic failover only if the mirror and the
witness remain connected to each other after both have been disconnected from the
principal server.

The following illustration shows a configuration that includes a witness.


7

For more information, see Role Switching, later in this topic.


Note

Establishing a new mirroring session or adding a witness to an existing mirroring


configuration requires that all involved server instances run the same version of SQL
Server. However, when you are upgrading to SQL Server 2008 or a later version, the
versions of the involved instances can vary. For more information, see Upgrading
Mirrored Instances.

Transaction Safety and Operating Modes

Whether an operating mode is asynchronous or synchronous depends on the


transaction safety setting. If you exclusively use SQL Server Management Studio to
configure database mirroring, transaction safety settings are configured automatically
when you select the operation mode.

If you use Transact-SQL to configure database mirroring, you must understand how to
set transaction safety. Transaction safety is controlled by the SAFETY property of the
ALTER DATABASE statement. On a database that is being mirrored, SAFETY is either
FULL or OFF.

 If the SAFETY option is set to FULL, database mirroring operation is synchronous,


after the initial synchronizing phase. If a witness is set in high-safety mode, the
session supports automatic failover.
8

 If the SAFETY option is set to OFF, database mirroring operation is asynchronous.


The session runs in high-performance mode, and the WITNESS option should also
be OFF.

For more information, see Database Mirroring Operating Modes.

Role Switching

Within the context of a database mirroring session, the principal and mirror roles are
typically interchangeable in a process known as role switching. Role switching involves
transferring the principal role to the mirror server. In role switching, the mirror server
acts as the failover partner for the principal server. When a role switch occurs, the mirror
server takes over the principal role and brings its copy of the database online as the new
principal database. The former principal server, if available, assumes the mirror role, and
its database becomes the new mirror database. Potentially, the roles can switch back
and forth repeatedly.

The following three forms of role switching exist.

 Automatic failover

This requires high-safety mode and the presence of the mirror server and a
witness. The database must already be synchronized, and the witness must be
connected to the mirror server.

The role of the witness is to verify whether a given partner server is up and
functioning. If the mirror server loses its connection to the principal server but the
witness is still connected to the principal server, the mirror server does not initiate
a failover. For more information, see Database Mirroring Witness.

 Manual failover

This requires high-safety mode. The partners must be connected to each other,
and the database must already be synchronized.

 Forced service (with possible data loss)

Under high-performance mode and high-safety mode without automatic failover,


forcing service is possible if the principal server has failed and the mirror server is
available.
Important
9

High-performance mode is intended to run without a witness. But if a witness


exists, forcing service requires that the witness is connected to the mirror server.

In any role-switching scenario, as soon as the new principal database comes


online, the client applications can recover quickly by reconnecting to the database.

Concurrent Sessions

A given server instance can participate in multiple, concurrent database mirroring


sessions (once per mirrored database) with the same or different server instances. Often,
a server instance serves exclusively as a partner or a witness in all of its database
mirroring sessions. However, because each session is independent of the other sessions,
a server instance can act as a partner in some sessions and as a witness in other
sessions. For example, consider the following four sessions among three server instances
( SSInstance_1 , SSInstance_2 , and SSInstance_3 ). Each server instance serves as a
partner in some sessions and as a witness in others:
Server Session for Session for Session for Session for
instance database A database B database C database D

SSInstance_1 Witness Partner Partner Partner

SSInstance_2 Partner Witness Partner Partner

SSInstance_3 Partner Partner Witness Witness

The following figure illustrates two server instances that are participating as partners
together in two mirroring sessions. One session is for a database named Db_1, and the
other session is for a database named Db_2.
10

Each of the databases is independent of the others. For example, a server instance might
initially be the mirror server for two databases. If one of those databases fails over, the
server instance becomes the principal server for the failed-over database while
remaining the mirror server for the other database.

As another example, consider a server instance that is the principal server for two or
more databases running in high-safety mode with automatic failover, If the server
instance fails, all of the databases automatically failover to their respective mirror
databases.

When setting up a server instance to operate both as a partner and a witness, be sure
that the database mirroring endpoint supports both roles (for more information, see The
Database Mirroring Endpoint (SQL Server)). Also, ensure that the system has sufficient
resources to reduce resource contention.
Note

Because mirrored databases are independent of each other, databases cannot fail over
as a group.

Client Connections

Client-connection support for database mirroring sessions is provided by the Microsoft


.NET Data Provider for SQL Server. For more information, see Connect Clients to a
Database Mirroring Session (SQL Server).

Impact of Pausing a Session on the Principal Transaction Log


11

At any time, the database owner can pause a session. Pausing preserves the session
state while removing mirroring. When a session is paused, the principal server does not
send any new log records to the mirror server. All of these records remain active and
accumulate in the transaction log of the principal database. As long as a database
mirroring session remains paused, the transaction log cannot be truncated. Therefore, if
the database mirroring session is paused for too long, the log can fill up.

For more information, see Pausing and Resuming Database Mirroring (SQL Server).

Setting Up Database Mirroring Session


Before a mirroring session can begin, the database owner or system administrator must
create the mirror database, set up endpoints and logins, and, in some cases, create and
set up certificates. For more information, see Setting Up Database Mirroring (SQL
Server).
+++++++++++++

Prerequisites, Restrictions, and


Recommendations for Database Mirroring
2016-5-17 5 min to read Contributors

12


Note

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this
feature in new development work, and plan to modify applications that currently use
this feature. Use Always On availability groups instead.

This topic describes the prerequisites and recommendations for setting up database
mirroring. For an introduction to database mirroring, see Database Mirroring (SQL
Server).

Support For Database Mirroring


For information about support for database mirroring in SQL Server 2017, see Editions
and Supported Features for SQL Server 2016.

Note that database mirroring works with any supported database compatibility level. For
information about the supported compatibility levels, see ALTER DATABASE
Compatibility Level (Transact-SQL).
13

Prerequisites
 For a mirroring session to be established, the partners and the witness, if any, must
be running on the same version of SQL Server.
 The two partners, that is the principal server and mirror server, must be running
the same edition of SQL Server. The witness, if any, can run on any edition of SQL
Server that supports database mirroring.
Note

You can upgrade server instances that are partners in a mirroring session to a
more recent version of SQL Server. For more information, see Upgrading Mirrored
Instances.

 The database must use the full recovery model. The simple and bulk-logged
recovery models do not support database mirroring. Therefore, bulk operations are
always fully logged for a mirrored database. For information about recovery
models, see Recovery Models (SQL Server).
 Verify that the mirror server has sufficient disk space for the mirror database.
Note

For information about how to use database mirroring on a replicated database,


see Database Mirroring and Replication (SQL Server).

 When you are creating the mirror database on the mirror server, make sure that
you restore the backup of the principal database specifying the same database
name WITH NORECOVERY. Also, all log backups that were created after that
backup was taken must also be applied, again WITH NORECOVERY.
Important

If database mirroring has been stopped, before you can restart it, any subsequent
log backups taken on the principal database must be applied to the mirror
database.

Restrictions
 Only user databases can be mirrored. You cannot mirror
the master, msdb, tempdb, or modeldatabases.
 A mirrored database cannot be renamed during a database mirroring session.
14

 Database mirroring does not support FILESTREAM. A FILESTREAM filegroup cannot


be created on the principal server. Database mirroring cannot be configured for a
database that contains FILESTREAM filegroups.
 Database mirroring is not supported with either cross-database transactions or
distributed transactions. For more information, see Cross-Database Transactions
and Distributed Transactions for Always On Availability Groups and Database
Mirroring (SQL Server).

Recommendations for Configuring Partner Servers


 The partners should run on comparable systems that can handle identical
workloads.
Note

If you plan to use high-safety mode with automatic failover, the normal load on
each failover partner should be less than 50 percent of the CPU. If your work load
overloads the CPU, a failover partner might be unable to ping the other server
instances in the mirroring session. This causes a unnecessary failover. If you cannot
keep the CPU usage under 50 percent, we recommend that you use either high-
safety mode without automatic failover or high-performance mode.

 If possible, the path (including the drive letter) of the mirror database should be
identical to the path of the principal database. You must include the MOVE option
in the RESTORE statement if the file layouts must differ. For example, if the
principal database is on drive 'F:' but the mirror system lacks an F: drive.
Important

If you move the database files when you create the mirror database, you might be
unable to add files to the database later without mirroring being suspended.

 All of the server instances in a mirroring session should use the same master code
page and collation. Differences can cause a problem during mirroring setup.
 Optionally, estimate the time to fail over a database, to make sure that the system
configuration will provide the performance you require. For more information,
see Estimate the Interruption of Service During Role Switching (Database
Mirroring).
 For best performance, use a dedicated network adapter (network interface card)
for mirroring.
 We make no recommendations about whether a wide-area network (WAN) is
reliable enough for database mirroring in high-safety mode. If you decide to use
15

high-safety mode over a WAN, be cautious about how you add a witness to the
session, because unwanted automatic failovers can occur. For more information,
see Recommendations for Deploying Database Mirroring, later in this topic.

Recommendations for Deploying Database Mirroring


Optimal database mirroring performance is obtained by using asynchronous operation.
A mirroring session that uses synchronous operation might experience slowed
performance when its workload generates large amounts of transaction log data.

In test environments, it is appropriate to explore all the operating modes to evaluate


how database mirroring performs. However, before you deploy mirroring into a
production environment, make sure that you understand how the network functions in
the real world.

High-safety mode with automatic failover is designed for a high-service network that
has either a dedicated connection or a fairly simple network configuration that
minimizes the sources of possible network failures. Such a high-quality network
environment is necessary for high-safety mode with automatic failover and is
recommended for all database mirroring sessions. However, high-performance mode
and high-safety mode without automatic failover are much less affected by network
reliability.

Therefore, for production environments we recommend that you adhere to the


following deployment guidelines:

1. Start running in asynchronous, high-performance mode. This mode is the least


sensitive to the network environment and provides the best configuration for
exploring how mirroring works. We recommend that you run your system
asynchronously until you are confident that your bandwidth supports mirroring
and you have developed an understanding of mirroring setup and of the
performance of asynchronous mode in your environment. For more information,
see Database Mirroring Operating Modes.
Important

Throughout testing, we recommend that you monitor your sessions for network
errors that cause database mirroring to fail. For more information about potential
sources of failure, see Possible Failures During Database Mirroring. For information
about how to monitor database mirroring, see Monitoring Database Mirroring
(SQL Server).
16

2. When you are confident that asynchronous operation is meeting the business
needs, you might want to try synchronous operation to improve your data
protection. When you test how synchronous mirroring works in your environment,
we recommend that first you test high-safety mode without automatic failover. The
primary purpose of this testing is to see how synchronous operation affects the
database performance. For more information, see Database Mirroring Operating
Modes.
3. Wait to enable automatic failover until you are confident that high-safety mode
without automatic failover is meeting the business needs and that network errors
are not causing failures. For more information, see Role Switching During a
Database Mirroring Session (SQL Server).
+++++++++++++++++++++++++++++++++++++

Database Mirroring Operating Modes


2017-3-14 15 min to read Contributors


17

This topic describes the synchronous and asynchronous operating modes for database
mirroring sessions.
Note

For an introduction to database mirroring, see Database Mirroring (SQL Server).

Terms and Definitions


This section introduces a few terms that are central to this topic.

High-performance mode
The database mirroring session operates asynchronously and uses only the principal
server and mirror server. The only form of role switching is forced service (with possible
data loss).

High-safety mode
The database mirroring session operates synchronously and, optionally, uses a witness,
as well as the principal server and mirror server.

Transaction safety
A mirroring-specific database property that determines whether a database mirroring
session operates synchronously or asynchronously. There are two safety levels: FULL and
OFF.

Witness
For use only with high-safety mode, an optional instance of SQL Server that enables the
mirror server to recognize whether to initiate an automatic failover. Unlike the two
failover partners, the witness does not serve the database. Supporting automatic failover
is the only role of the witness.

Asynchronous Database Mirroring (High-Performance


Mode)
This section describes how asynchronous database mirroring works, when it is
appropriate to use high-performance mode, and how to respond if the principal server
fails.
Note
18

Most editions of SQL Server 2017 support only synchronous database mirroring ("Safety
Full Only"). For information about editions that fully support database mirroring, see
"High Availability (Always On)" in Editions and Supported Features for SQL Server 2016.

When transaction safety is set to OFF, the database mirroring session operates
asynchronously. Asynchronous operation supports only one operating mode—high-
performance mode. This mode enhances performance at the expense of high
availability. High-performance mode uses just the principal server and the mirror server.
Problems on the mirror server never impact the principal server. On the loss of the
principal server, the mirror database is marked DISCONNECTED but is available as a
warm standby.

High-performance mode, supports only one form of role switching: forced service (with
possible data loss), which uses the mirror server as a warm standby server. Forced
service is one of the possible responses to the failure of the principal server. Because
data loss is possible, you should consider other alternatives before forcing service to the
mirror. For more information, see Responding to Failure of the Principal, later in this
topic.

The following figure shows the configuration of a session using high-performance


mode.

In high-performance mode, as soon as the principal server sends the log for a
transaction to the mirror server, the principal server sends a confirmation to the client,
without waiting for an acknowledgement from the mirror server. Transactions commit
without waiting for the mirror server to write the log to disk. Asynchronous operation
permits the principal server to run with minimum transaction latency.

The mirror server attempts to keep up with the log records sent by the principal server.
But the mirror database might lag somewhat behind the principal database, though
typically the gap between the databases is small. However, the gap can become
substantial if the principal server is under a heavy work load or the system of the mirror
server is over loaded.

In This Section:

 When Is High-Performance Mode Appropriate?


19

 The Impact of a Witness on High-Performance Mode


 Responding to Failure of the Principal

When Is High-Performance Mode Appropriate?

High-performance mode can be useful in a disaster-recovery scenario in which the


principal and mirror servers are separated by a significant distance and where you do
not want small errors to impact the principal server.
Note

Log shipping can be a supplement to database mirroring and is a favorable alternative


to asynchronous database mirroring. For information about the advantages of log
shipping, see High Availability Solutions (SQL Server). For information on using log
shipping with database mirroring, see Database Mirroring and Log Shipping (SQL
Server).

The Impact of a Witness on High-Performance Mode

If you use Transact-SQL to configure high-performance mode, whenever the SAFETY


property is set to OFF, we strongly recommend that the WITNESS property also be set to
OFF. A witness can coexist with high-performance mode, but the witness provides no
benefit and introduces risk.

If the witness is disconnected from the session when either partner goes down, the
database becomes unavailable. This is because, even though high-performance mode
does not require a witness, if one is set, the session requires a quorum consisting of two
or more server instances. If the session losses quorum, it cannot serve the database.

When a witness is set in a high-performance mode session, the enforcement of quorum


means that:

 If the mirror server is lost, the principal server must be connected to the witness.
Otherwise, the principal server takes its database offline until either the witness or
mirror server rejoins the session.
 If the principal server is lost, forcing service to the mirror server requires that the
mirror server be connected to the witness.
Note

For information about the types of quorums, see Quorum: How a Witness Affects
Database Availability (Database Mirroring).
20

Responding to Failure of the Principal

When the principal fails, the database owner has several choices, as follows:

 Leave the database unavailable until the principal becomes available again.

If the principal database and its transaction log are intact, this choice preserves all
of the committed transactions at the expense of availability.

 Stop the database mirroring session, manually update the database, and then
begin a new database mirroring session.

If the principal database is lost but the principal server is still running, immediately
attempt to back up the tail of the log on the principal database. If the tail-log
backup succeeds, removing mirroring may be your best alternative. After removing
mirroring, you can restore the log onto the former mirror database, which
preserves all of the data.
Note

If the tail-log backup failed and you cannot wait for the principal server to recover,
consider forcing service, which has the advantage of maintaining the session state.

 Force service (with possible data loss) on the mirror server.

Forced service is strictly a disaster recovery method and should be used sparingly.
Forcing service is possible only if the principal server is down, the session is
asynchronous (transaction safety is set to OFF), and either the session does not
have any witness (the WITNESS property is set to OFF) or the witness is connected
to the mirror server (that is, they have quorum).

Forcing service causes the mirror server to assume the role of principal and serve
its copy of the database for clients. When service is forced, whatever transaction
logs the principal has not yet sent to the mirror server are lost. Therefore, you
should limit forced service to situations where possible data loss is acceptable and
immediate database availability is critical. For information on how forced service
works and on best practices for using it, see Role Switching During a Database
Mirroring Session (SQL Server).

Synchronous Database Mirroring (High-Safety Mode)


21

This section describes how synchronous database mirroring works, including the
alternative high-safety modes (with automatic failover and without automatic failover),
and contains information about the role of the witness in automatic failover.

When transaction safety is set to FULL, the database mirroring session runs in high-
safety mode and operates synchronously after an initial synchronizing phase. This
section describes the details of database mirroring sessions that are configured for
synchronous operation.

To achieve synchronous operation for a session, the mirror server must synchronize the
mirror database with the principal database. When the session begins, the principal
server begins sending its active log to the mirror server. The mirror server writes all of
the incoming log records to disk as quickly as possible. As soon as all of the received log
records have been written to disk, the databases are synchronized. As long as the
partners remain in communication, the databases remain synchronized.
Note

To monitor state changes in a database mirroring session, use the Database Mirroring
State Change event class. For more information, see Database Mirroring State Change
Event Class.

After synchronization finishes, every transaction committed on the principal database is


also committed on the mirror server, guaranteeing protection of the data. This is
achieved by waiting to commit a transaction on the principal database, until the
principal server receives a message from the mirror server stating that it has hardened
the transaction's log to disk. Note the wait for this message increases the latency of the
transaction.

The time required for synchronization depends essentially on how far the mirror
database was behind the principal database at the start of the session (measured by the
number of log records initially received from the principal server), the work load on the
principal database, and the speed of the mirror system. After a session is synchronized,
the hardened log that has yet to be redone on the mirror database remains in the redo
queue.

As soon as the mirror database becomes synchronized, the state of both the copies of
the database changes to SYNCHRONIZED.

Synchronous operation is maintained in the following manner:


22

1. On receiving a transaction from a client, the principal server writes the log for the
transaction to the transaction log.
2. The principal server writes the transaction to the database and, concurrently, sends
the log record to the mirror server. The principal server waits for an
acknowledgement from the mirror server before confirming either of the following
to the client: a transaction commit or a rollback.
3. The mirror server hardens the log to disk and returns an acknowledgement to the
principal server.
4. On receiving the acknowledgement from the mirror server, the principal server
sends a confirmation message to the client.

High-safety mode protects your data by requiring the data to be synchronized


between two places. All the committed transactions are guaranteed to be written
to disk on the mirror server.

In This Section:

 High-Safety Mode Without Automatic Failover


 High-Safety Mode with Automatic Failover

High-Safety Mode Without Automatic Failover

The following figure shows the configuration of high-safety mode without automatic
failover. The configuration consists of only the two partners.

When the partners are connected and the database is already synchronized, manual
failover is supported. If the mirror server instance goes down, the principal server
instance is unaffected and runs exposed (that is without mirroring the data). If the
principal server is lost, the mirror is suspended, but service can be forced to the mirror
server (with possible data loss). For more information, see Role Switching During a
Database Mirroring Session (SQL Server).

High-Safety Mode with Automatic Failover


23

Automatic failover provides high availability by ensuring that the database is still served
after the loss of one server. Automatic failover requires that the session possess a third
server instance, the witness, which ideally resides on a third computer. The following
figure shows the configuration of a high-safety mode session that supports automatic
failover.

Unlike the two partners, the witness does not serve the database. The witness simply
supports automatic failover by verifying whether the principal server is up and
functioning. The mirror server initiates automatic failover only if the mirror and the
witness remain connected to each other after both have been disconnected from the
principal server.

When a witness is set, the session requires quorum—a relationship between at least two
server instances that allows the database to be made available. For more information,
see Database Mirroring Witnessand Quorum: How a Witness Affects Database
Availability (Database Mirroring).

Automatic failover requires the following conditions:

 The database is already synchronized.


 The failure occurs while all three server instances are connected, and the witness
and mirror server remain connected.

The loss of a partner has the following effect:

 If the principal server becomes unavailable under the above conditions, automatic
failover occurs. The mirror server switches to the role of principal, and it offers its
database as the principal database.
 If the principal server becomes unavailable when those conditions are not met,
forcing service (with possible data loss) might be possible. For more information,
see Role Switching During a Database Mirroring Session (SQL Server).
 If the only mirror server becomes unavailable, the principal and witness continue.
24

If the session loses its witness, quorum requires both partners. If either partner
loses quorum, both partners lose quorum, and the database becomes unavailable
until quorum is re-established. This quorum requirement makes sure that in the
absence of a witness the database never runs exposed, that is without being
mirrored.
Note

If you expect the witness to remain disconnected for a significant amount of time, we
recommend that you remove the witness from the session until it becomes available.

Transact-SQL Settings and Database Mirroring Operating


Modes
This section describes a database mirroring session in terms of the ALTER DATABASE
settings and states of the mirrored database and witness, if any. The section is aimed at
users who manage database mirroring primarily or exclusively using Transact-SQL,
rather than using SQL Server Management Studio.
Tip

As an alternative to using Transact-SQL, you can control the operating mode of a


session in Object Explorer using the Mirroring page of the Database Properties dialog
box. For more information, see Establish a Database Mirroring Session Using Windows
Authentication (SQL Server Management Studio).

In This Section:

 How Transaction Safety and Witness State Affect the Operating Mode
 Viewing the Safety Setting and State of the Witness
 Factors Affecting Behavior on Loss of the Principal Server

How Transaction Safety and Witness State Affect the Operating Mode

The operating mode of a session is determined by the combination of its transaction


safety setting and the state of the witness. At any time, the database owner can change
the transaction safety level, and can add or remove the witness.

In This Section:

 Transaction Safety
 Witness State
25

Transaction Safety

Transaction safety is a mirroring-specific database property that determines whether a


database mirroring session operates synchronously or asynchronously. There are two
safety levels: FULL and OFF.

 SAFETY FULL

Full transaction safety causes the session to operate synchronously in high-safety


mode. If a witness is present, a session supports automatic failover.

When you establish a session using ALTER DATABASE statements, the session
begins with the SAFETY property set to FULL; that is, the session begins in high-
safety mode. After the session begins, you can add a witness.

For more information, see Synchronous Database Mirroring (High-Safety Mode),


earlier in this topic.

 SAFETY OFF

Turning off transaction safety causes the session to operate asynchronously, in


high-performance mode. If the SAFETY property is set to OFF, the WITNESS
property should also be set to OFF (the default). For information about the impact
of the witness in high-performance mode, see The State of the Witness, later in
this topic. For more information about running with transaction safety turned off,
see Asynchronous Database Mirroring (High-Performance Mode), earlier in this
topic.

The transaction safety setting of the database is recorded on each partner in


the sys.database_mirroring catalog view in
the mirroring_safety_level and mirroring_safety_level_desc columns. For more
information, see sys.database_mirroring (Transact-SQL).

The database owner can change the transaction safety level at any time.

The State of the Witness

If a witness has been set, quorum is required, so the state of the witness is always
significant.

If it exists, the witness has one of two states:


26

 When the witness is connected to a partner, the witness is in the CONNECTED


state relative to that partner and has quorum with that partner. In this case, the
database can be made available, even if one of the partners is unavailable.
 When the witness exists but is not connected to a partner, the witness is in the
UNKOWN or DISCONNECTED state relative to that partner. In this case, the witness
lacks quorum with that partner, and if the partners are not connected to each
other, the database becomes unavailable.

For information about quorum, see Quorum: How a Witness Affects Database
Availability (Database Mirroring).

The state of each witness on a server instance is recorded in


the sys.database_mirroringcatalog view in
the mirroring_witness_state and mirroring_witness_state_desc columns. For
more information, see sys.database_mirroring (Transact-SQL).

The following table summarizes how the operating mode of a session depends
upon its transaction safety setting and on state of the witness.
Operating mode Transaction safety Witness state

High-performance mode OFF NULL (no witness)**

High-safety mode without automatic failover FULL NULL (no witness)

High-safety mode with automatic failover* FULL CONNECTED

*If the witness becomes disconnected, we recommend that you set WITNESS OFF until
the witness server instance becomes available.

**If a witness is present in high-performance mode, the witness does not participate in
the session. However, to make the database available, at least two of the server
instances must remain connected. Therefore, we recommend keeping the WITNESS
property set to OFF in high-performance mode sessions. For more information,
see Quorum: How a Witness Affects Database Availability (Database Mirroring).

Viewing the Safety Setting and State of the Witness

To view the safety setting and the state of the witness for a database, use
the sys.database_mirroringcatalog view. The relevant columns are as follows:
27

Factor Columns Description

Transaction mirroring_safety_level or mirroring_safety_level_desc Transaction safety


safety setting for updates o
the mirror database,
one of:

UNKNOWN

OFF

FULL

NULL= database is
online.

Does a mirroring_witness_name Server name of the


witness database mirroring
exist? witness or NULL,
indicating that no
witness exists.

Witness mirroring_witness_state or mirroring_witness_state_desc State of the witness


state the database on a gi
partner:

UNKNOWN

CONNECTED

DISCONNECTED

NULL = no witness
exists or the databas
not online.

For example, on either the principal or mirror server, enter:


Copy

SELECT mirroring_safety_level_desc, mirroring_witness_name,


mirroring_witness_state_desc FROM sys.database_mirroring
28

For more information about this catalog view, see sys.database_mirroring (Transact-
SQL).

Factors Affecting Behavior on Loss of the Principal Server

The following table summarizes the combined effect of the transaction safety setting,
the state of the database, and the state of the witness on the behavior of a mirroring
session on the loss of the principal server.
Transaction Mirroring state of mirror
safety database Witness state Behavior when principal is lost

FULL SYNCHRONIZED CONNECTED Automatic failover occurs.

FULL SYNCHRONIZED DISCONNECTED Mirror server stops; failover is not


possible, and the database cannot be
made available.

OFF SUSPENDED or NULL (no Service can be forced to the mirror


DISCONNECTED witness) server (with possible data loss).

FULL SYNCHRONIZING or NULL (no Service can be forced to the mirror


SUSPENDED witness) server (with possible data loss).
+++++++++++++++

Database Mirroring Witness


2017-3-14 4 min to read Contributors

29

To support automatic failover, a database mirroring session must be configured in high-


safety mode and also possess a third server instance, known as the witness. The witness
is an optional instance of SQL Server that enables the mirror server in a high-safety
mode session to recognize whether to initiate an automatic failover. Unlike the two
partners, the witness does not serve the database. Supporting automatic failover is the
only role of the witness.
Note

In high-performance mode, the witness can adversely affect availability. If a witness is


configured for a database mirroring session, the principal server must be connected at
least to one of the other server instances, the mirror server or the witness, or both of
them. Otherwise, the database becomes unavailable and forcing service (with possible
data loss) is impossible. Therefore, for high-performance mode, we strongly recommend
that you always keep the witness set to OFF. For information about the impact of a
witness on high-performance mode, see Database Mirroring Operating Modes.

The following illustration shows a high-safety mode session with a witness.


30

In This Topic:

 Using a Witness in Multiple Sessions


 Software and Hardware Recommendations
 Role of the Witness in Automatic Failover
 To Add or Remove a Witness

Using a Witness in Multiple Sessions


A specific server instance can act as a witness in concurrent database mirroring sessions,
each for a different database. Different sessions can be with different partners. The
following illustration shows a server instance that is a witness in two database mirroring
sessions with different partners.
31

A single-server instance can also function at the same time as a witness in some
sessions and a partner in other sessions. However, in practice, a server instance typically
functions as either a witness or a partner. This is because the partners require
sophisticated computers that have enough hardware to support a production database,
whereas the witness can run on any available Windows system that supports SQL Server
2017.

Software and Hardware Recommendations


We strongly recommend that the witness reside on a separate computer from the
partners. Database mirroring partners are supported only by SQL Server Standard
edition and by SQL Server Enterprise edition. Witnesses, in contrast, are also supported
by SQL Server Workgroup and by SQL Server Express. Except during an upgrade from an
earlier version of SQL Server, the server instances in a mirroring session must all be
running the same version of SQL Server. For example, a SQL Server 2008 witness is
supported when you are upgrading from a SQL Server 2008 mirroring configuration but
cannot be added to an existing or new SQL Server 2008 R2 or later mirroring
configuration.

A witness can run on any reliable computer system that supports any of these editions
of SQL Server. However, we recommend that every server instance that is used as a
witness correspond to the minimum configuration that is required for the SQL Server
Standard version that you are running. For more information about these requirements,
see Hardware and Software Requirements for Installing SQL Server 2016.

Role of the Witness in Automatic Failover


32

Throughout a database mirroring session, all the server instances monitor their
connection status. If the partners become disconnected from each other, they rely on
the witness to make sure that only one of them is currently serving the database. If a
synchronized mirror server loses its connection to the principal server but remains
connected to the witness, the mirror server contacts the witness to determine whether
the witness has lost its connection to the principal server:

 If the principal server is still connected to the witness, automatic failover does not
occur. Instead, the principal server continues to server the database while
accumulating log records to send the mirror server when the partners reconnect.
 If the witness is also disconnected from the principal server, the mirror server
knows that principal database has become unavailable. In this case, the mirror
server immediately initiates an automatic failover.
 If the mirror server is disconnected from the witness and also from the principal
server, automatic failover is not possible, regardless of the state of the principal
server.

The requirement that at least two of the server instances be connected is known
as quorum. Quorum makes sure that the database can only be served by one
partner at a time. For information about how quorum works and its impact on a
session, see Quorum: How a Witness Affects Database Availability (Database
Mirroring).
+++++++++++++++++++++++++++++++

Role Switching During a Database Mirroring


Session (SQL Server)
2017-3-14 18 min to read Contributors

33

Within the context of a database mirroring session, the principal and mirror roles are
typically interchangeable in a process known as role switching. In role switching, the
mirror server acts as the failover partner for the principal server, taking over the principal
role, recovering its copy of the database and bringing it online as the new principal
database. The former principal server, when available, assumes the mirror role, and its
database becomes the new mirror database. Potentially, the roles can switch back and
forth either in response to multiple failures or for administrative purposes.
Note

This topic assumes that you are familiar with the database mirroring operating modes.
For more information, see Database Mirroring Operating Modes.

The following illustration shows mirroring partners, Partner_A and Partner_B,


switching the principal and mirror roles over a series of automatic or manual failovers.
34

Important

After a role switch, jobs that ran on the former principal database must be recreated on
the new principal server to run there. For more information, see Management of Logins
and Jobs After Role Switching (SQL Server).

Three types of role switching exist: automatic failover, manual failover, and forced
service (with possible data loss). Support for each form depends on the operating mode
of the session.
Note

If you are unfamiliar with these operating modes, see Database Mirroring Operating
Modes.

 Manual failover

High-safety mode supports manual failover. Whenever the database is


synchronized, the database owner can initiate a manual failover.

Manual failover is provided for administrative purposes. For more information,


see Manual Failover, later in this topic.

 Automatic failover
35

In the presence of a witness, high-safety mode supports automatic failover.


Automatic failover occurs only on the loss of the principal server when the witness
and mirror server are still connected to each other and the database is already
synchronized. For more information, see Automatic Failover, later in this topic.

 Forced service (with possible data loss)

Forcing service is supported in high-safety mode when no witness is set and in


high-performance mode. On the loss of the principal server, the database owner
can make the database available by forcing service to the mirror server (with
possible data loss).
Note

We recommend that the WITNESS property be set to OFF in high-performance


mode. Otherwise, to bring the database online, the mirror server must connected
to the witness.

For more information, see Forced Service (with Possible Data Loss), later in this
topic.

The following table summarizes which forms of failover are supported under each
of the operating modes.
High High-safety mode without a High-safety mode with a
performance witness witness

Automatic No No Yes
failover

Manual failover No Yes Yes

Forced service Yes Yes No

After a role switch, certain metadata must exist on both partners to ensure that all of the
database users can access the new principal database. In addition, backup jobs must be
created on the new principal server, to ensure that the database continues to be backed
up on its regular schedule. For more information, see Management of Logins and Jobs
After Role Switching (SQL Server).

During a role switch, the amount of time that database mirroring will be out of service
depends on the type of role switching and on the cause. For more information,
see Estimate the Interruption of Service During Role Switching (Database Mirroring).
36

Manual Failover
Manual failover disconnects the clients from the database and reverses the roles of the
partners. Only high-safety mode supports manual failover.

In This Section:

 Maintaining Availability During Upgrades


 Conditions Required for a Manual Failover
 How Manual Failover Works

Maintaining Availability During Upgrades

The database administrator can use manual failover for upgrading hardware or software
without sacrificing availability. To use database mirroring for software upgrades, the
mirror server and/or system must have already received the upgrades.
Note

Database mirroring should be able to do a rolling upgrade, but this is not guaranteed,
because future changes are unknown. For more information, see Upgrading Mirrored
Instances.

The following figure illustrates an instance of using manual failover to maintain


database availability while you upgrade a database server instance. When the upgrade is
completed, an administrator may optionally fail over back to the original server instance.
This is useful when the administrator wants to stop the mirroring session and use the
mirror server elsewhere. In this way, a single server instance can be used repeatedly
when updating a series of database server instances.
37

Conditions Required for a Manual Failover

Manual failover requires transaction safety to be set to FULL (that is, high-safety mode).
When the partners are connected and the database is already synchronized, manual
failover is supported.

How Manual Failover Works

Manual failover initiates the following sequence of actions:

1. The principal server disconnects clients from the principal database, sends the tail
of the log to the mirror server, and, in preparation for switching to the mirror role,
sets the mirroring state to SYNCHRONIZING.
38

2. The mirror server records the log sequence number (LSN) of the last log record
received from the principal as the failover LSN.
Note

To view this LSN, select the mirroring_failover_lsn column


from sys.database_mirroring (Transact-SQL).

3. If any log is waiting in the redo queue, the mirror server finishes rolling forward the
mirror database. The amount of time required depends on the speed of the
system, the recent workload, and the amount of log in the redo queue. For a
synchronous operating mode, the failover time can be regulated by limiting the
size of the redo queue. However, this can cause the principal server to slow down
to allow the mirror server to keep up.
Note

To learn the current size of the redo queue, use the Redo Queue performance
counter in the database mirroring performance object (for more information,
see Monitoring Database Mirroring (SQL Server)).

4. The mirror server becomes the new principal server, and the former principal
server becomes the new mirror server.
5. The new principal server rolls back any uncommitted transactions and brings its
copy of the database online as the principal database.
6. The former principal takes on the mirror role, and the former principal database
becomes the mirror database. The new mirror server quickly resynchronizes the
new mirror database with the new principal database.
Note

As soon as the new mirror server has resynchronized the databases, failover is
again possible, but in the reverse direction.

After failover, clients must reconnect to the current principal database. For more
information, see Connect Clients to a Database Mirroring Session (SQL Server).

To initiate manual failover

 Manually Fail Over a Database Mirroring Session (SQL Server Management Studio)
 Manually Fail Over a Database Mirroring Session (Transact-SQL).

Automatic Failover
39

Automatic failover is supported only in database mirroring sessions running with a


witness in high-safety mode (high-safety mode with automatic failover). In high-safety
mode with automatic failover, once the database is synchronized, if the principal
database becomes unavailable, an automatic failover occurs. An automatic failover
causes the mirror server to take over the role of principal server and bring its copy of
the database online as the principal database. Requiring that the database be
synchronized prevents data loss during failover, because every transaction committed
on the principal database is also committed on the mirror database.
Important

For automatic failover to improve reliability, the mirror and principal databases must
reside on different computers.

In This Section:

 Conditions Required for an Automatic Failover


 How Automatic Failover Works
 To Disable Automatic Failover (SQL Server Management Studio)
 To Disable Automatic Failover (Using Transact-SQL)

Conditions Required for an Automatic Failover

Automatic failover requires the following conditions:

 The database mirroring session must be running in high-safety mode and must
possess a witness. For more information, see Database Mirroring Operating
Modes.
 The mirror database must already be synchronized. This guarantees that all of the
log sent to the mirror server has been written to disk.
 The principal server has lost communication with the rest of the database
mirroring configuration, while the mirror and witness retain quorum. If all server
instances lose communication, however, and the witness and the mirror server
later regain communication, automatic failover does not occur.
Note

For more information, see Quorum: How a Witness Affects Database Availability
(Database Mirroring).

 The mirror server has detected the loss of the principal server.
40

How the mirror server detects a failure of the principal server depends on whether
it is a hard or soft failure. For more information, see Possible Failures During
Database Mirroring.

How Automatic Failover Works

Under the preceding conditions, automatic failover initiates the following sequence of
actions:

1. If the principal server is still running, it changes the state of the principal database
to DISCONNECTED and disconnects all clients from the principal database.
2. The witness and mirror servers register that the principal server is unavailable.
3. If any log is waiting in the redo queue, the mirror server finishes rolling forward the
mirror database.
Note

The amount of time required to apply the log depends on the speed of the system,
the recent work load, and the amount of log in the redo queue.

4. The former mirror database moves online as the new principal database, and
recovery cleans up all uncommitted transactions by rolling them back as quickly as
possible. Locks isolate those transactions.
5. When the former principal server rejoins the session, it recognizes that its failover
partner now owns the principal role. The former principal server takes on the role
of mirror, making its database the mirror database. The new mirror server
synchronizes the new mirror database with the principal database as quickly as
possible. As soon as the new mirror server has resynchronized the databases,
failover is again possible, but in the reverse direction.

The following illustration shows a single instance of automatic failover.


41

Initially, all three servers are connected (the session has full quorum). Partner_A is
the principal server and Partner_B is the mirror server. Partner_A (or the principal
database on Partner_A) becomes unavailable. The witness and Partner_B both
recognize that the principal is no longer available the session retains
quorum. Partner_B becomes the principal server and makes its copy of the
database available as the new principal database.
Eventually, Partner_A reconnects to the session and discovers
that Partner_B now owns the principal role. Partner_A then takes on the mirror
role.
42

After failover, clients must reconnect to the current principal database. For more
information, see Connect Clients to a Database Mirroring Session (SQL Server).
Note

Transactions that have been prepared using the Microsoft Distributed Transaction
Coordinator but are still not committed when a failover occurs, are considered aborted
after the database has failed over.

To Disable Automatic Failover (SQL Server Management Studio)

Open the Database PropertiesMirroring page, and change the operating mode by
selecting one of the following options:

 High safety without automatic failover (synchronous)

In this mode, the database continues to be synchronized, and manual failover


remains possible.

 High performance (asynchronous)

In this mode, the mirror database might lag somewhat behind the principal
database, and manual failover is no longer possible.

To Disable Automatic Failover (Using Transact-SQL)

At any point in a database mirroring session, the database owner can disable automatic
failover by turning off the witness.

To turn off the witness

 Remove the Witness from a Database Mirroring Session (SQL Server)


Note

Turning off the witness while retaining full transaction safety puts the session into
high-safety mode without automatic failover.

Forced Service (with Possible Data Loss)


Database mirroring provides forcing service (with possible data loss) as a disaster
recovery method to allow you to use a mirror server as a warm standby server. Forcing
service is possible only if the principal server is disconnected from the mirror server in a
43

mirroring session. Because forcing service risks possible data loss, it should be used
cautiously and sparingly.

Support for forced service depends on the operating mode and the state of the session,
as follows:

 Typically, high-performance mode supports forcing service whenever the principal


server is disconnected. However, though unnecessary, a witness can exist for a
high-performance mode session. In this case, forcing service requires that the
mirror server and witness are connected to each other.
 High-safety mode without automatic failover supports forcing service whenever
the principal server is disconnected.
 High-safety mode with automatic failover supports forcing service whenever the
mirror server and witness are connected to each other and neither is connected to
the principal server (as long as the mirror server was not in the process of rolling
back the mirror database when it was last connected to the principal).

We recommend forcing service only if you must restore service to the database
immediately and are willing to risk losing data. The effect of forcing service is
similar to removing mirroring, except that forcing service facilitates
resynchronizing the databases when mirroring is resumed, at the risk of possible
data loss. Forcing service initiates a smooth transition of the principal role to the
mirror database. The mirror server assumes the role of principal server and
immediately serves its copy of the database to clients. The new principal database
runs without a mirror (that is, it runs exposed).
Important

If the principal server was merely disconnected from the database mirroring session and
is still running, some clients might continue to access the original principal database.
Before you force service, it is important to prevent clients from accessing the original
principal server. Otherwise, after service is forced, the original principal database and the
current principal database could be updated independently of the other.

In This Section:

 Typical Case of Forced Service


 Risks of Forcing Service
 Managing the Potential Data Loss
 Related Tasks For Managing a Forced Failover

Typical Case of Forced Service


44

The following figure illustrates a typical case of forced service (with possible data loss).

In the figure, the original principal server, Partner_A, becomes unavailable to the mirror
server, Partner_B, causing the mirror database to be disconnected. After ensuring
that Partner_A is not available to clients, the database administrator forces service, with
possible data loss, on Partner_B. Partner_B becomes the principal server and runs with
the database exposed (that is, unmirrored). At this point, clients can reconnect
to Partner_B.

When Partner_A becomes available, it reconnects to the new principal server, rejoining
the session and assuming the mirror role. The mirroring session is suspended
immediately, without having synchronized the new mirror database. Suspending the
session allows the database administrator to decide whether to resume the session or, in
45

extreme cases, remove mirroring and attempt to salvage data from the former principal
database. In this case, the database administrator chooses to resume mirroring. At that
point, Partner_A takes over the role of mirror server and rolls back the former principal
database to the point in time of the last successfully synchronized transaction; if any
committed transactions were not written to disk on the mirror server before service was
forced, they are lost. Partner_A then rolls forward the new mirror database by applying
any changes made on the new principal database since the former mirror server became
the new principal server.
Note

Although high-performance mode does not require a witness, if one is configured,


forcing service is possible only if the witness is currently connected to the mirror server.

Risks of Forcing Service

It is essential to understand that forcing service can cause data loss. Data loss is possible
because the mirror server cannot communicate with the principal server and, therefore,
cannot guarantee that the two databases are synchronized. Forcing service starts a new
recovery fork. Because the original principal database and mirror database are on
different recovery forks, each database now contains data that the other database does
not: the original principal database contains whatever changes were not yet sent from
its send queue to the former mirror database (the unsent log); the former mirror
database contains whatever changes occur after service was forced.

If service is forced because the principal server has failed, potential data loss is depends
on whether any transaction logs were not sent to the mirror server before the failure.
Under high-safety mode, this is possible only until the mirror database becomes
synchronized. Under the high-performance mode, accumulated unsent log is always a
possibility.

The implications of forcing service depend partly on whether the session has a witness:

 In the absence of a witness, service can be forced if the partners become


disconnected, for example, because their network connection is broken. If the
original principal server is still running, both partners own the principal role. Clients
connecting to the new principal server will access the current version of the
database, while clients connecting to the original principal server will access the
original principal database. This situation increases the potential for data loss. If
the partners are allowed to reconnect, the original principal server assumes the
mirror role and changes the status of its database to "recovering," before mirroring
is suspended. If the session is resumed, transactions on the original principal
46

database whose log was in the send queue as of the most recent disconnection are
lost. In addition, any the transactions that occurred after service was forced are
also lost.
 In the presence of a witness, if the mirror server is disconnected from both the
principal server and the witness, as long as the latter two remain connected to
each other, the principal runs exposed. If the principal server then becomes
disconnected from the witness, it stops serving the database. Thereafter, if the
mirror server reconnects to the witness, forcing service becomes possible. If service
is forced, all the changes made while the original principal server was running
exposed will be lost if the original principal server reconnects.

For more information, see Managing the Potential Data Loss, later in this topic.

Managing the Potential Data Loss

After service is forced, once the former principal server is available, assuming that its
database is undamaged, you can attempt to manage the potential data loss. The
available approach for managing potential data loss depends on whether the original
principal server has reconnected to its partner and rejoined the mirroring session.
Assuming that the original principal server can access the new principal instance,
reconnecting occurs automatically and transparently.

The Original Principal Server Has Reconnected

Typically, after a failure, when the original principal server restarts it quickly reconnects
to its partner. On reconnecting, the original principal server becomes the mirror server.
Its database becomes the mirror database and enters the recovering state before the
session is suspended. The mirror database will not be not rolled back unless you resume
mirroring.

However, the recovering database is inaccessible; therefore, you cannot inspect it to


evaluate what data would be lost if you were to resume mirroring. Therefore, the
decision on whether to resume or remove mirroring depends on whether you are willing
to accept any data loss at all.

 If losing any data would be unacceptable, you should remove mirroring to salvage
them.

Removing mirroring would allow the database administrator to recover the original
principal database and attempt to recover the data that would have been lost.
47

However, when the former mirror database comes online, the former partners will
be serving divergent databases with the same name. The database administrator
needs to make one of the databases inaccessible to clients to avoid further
divergence of the database and to prevent client-failover issues.

 If losing any data would be acceptable, you can resume mirroring.

Resuming mirroring causes the new mirror database to be rolled back as the first
step in synchronizing the database. If any log records were waiting in the send
queue at the time of failure, the corresponding transactions are lost, even if they
were committed.

The Original Principal Server Has Not Reconnected

If you can temporarily prevent the original principal server from reconnecting over the
network to the new principal server, you can inspect the original principal database to
evaluate what data would be lost if mirroring were resumed.

 If the potential data loss is acceptable

Allow the original principal server to reconnect to its partner. Reconnecting causes
mirroring to be suspended. To proceed with mirroring, simply resume the session.
The former principal server assumes the mirror role. The new mirror server drops
the original recovery fork, losing any transactions that were never sent to or
received by the former mirror server.

 If the data loss is unacceptable

If the original principal database contains critical data that would be lost if you
resumed the session, you can preserve the data on the original principal server by
removing mirroring. We recommend that you attempt to back up the tail of the
principal's log at this point. Then, you can update the current principal (the former
mirror database) by exporting the data you want to salvage from the original
principal database and importing it into the current principal database. We
recommend taking a full database backup of the updated database as quickly as
possible.

To re-establish mirroring with the updated database as the initial principal


database, use this backup (and least one subsequent log backup) to create a new
mirror database. Every log backup taken after mirroring was removed must be
48

applied. Therefore, we recommend delaying additional log backups of the principal


database until the new mirroring session starts.
+++++++++++++++++++++++++++++++++++++++++++++++++++++

Possible Failures During Database Mirroring


2017-3-14 5 min to read Contributors

Physical, operating system, or SQL Server problems can cause a failure in a database
mirroring session. Database mirroring does not regularly check the components on
which Sqlservr.exe relies to verify whether they are functioning correctly or have failed.
However, for some types of failures, the affected component reports an error to
Sqlservr.exe. An error reported by another component is called a hard error. To detect
other failures that would otherwise go unnoticed, database mirroring implements its
own time-out mechanism. When a mirroring time-out occurs, database mirroring
assumes that a failure has occurred and declares a soft error. However, some failures
49

that happen at the SQL Server instance level do not cause mirroring to time-out and can
go undetected.
Important

Failures in databases other than the mirrored database are not detectable in a database
mirroring session. Moreover, a data disk failure is unlikely to be detected, unless the
database is restarted because of a data disk failure.

The speed of error detection and, therefore, the reaction time of the mirroring session
to a failure, depends on whether the error is hard or soft. Some hard errors, such as
network failures are reported immediately. However, in some cases, component-specific
time-out periods can delay the reporting of some hard errors. For soft errors, the length
of the mirroring time-out period determines the speed of error detection. By default,
this period is 10 seconds. This is the minimum recommended value.

Failures Due to Hard Errors


Possible causes of hard errors include (but are not limited to) the following conditions:

 A broken connection or wire


 A bad network card
 A router change
 Changes in the firewall
 Endpoint reconfiguration
 Loss of the drive where the transaction log resides
 Operating system or process failure

For example, when the log drive on the principal database becomes unresponsive
and fails, the operating system informs Sqlservr.exe that a serious error has
occurred.

Some components, such as network components and some IO subsystems, have


their own time-outs to determine failures. Such time-outs are independent of
database mirroring, which has no knowledge of them and is completely unaware
of their behavior. In these cases, the time-out delay increases the time between a
failure and when database mirroring receive the resulting hard error.
Note

The only active error checking performed for database mirroring occurs for soft error
cases. For more information, see "Failures Due to Soft Errors," later in this topic.
50

To help you interpret the error conditions that occur on the network, ask a network
engineer what error messages are sent to a port when the following events occur on a
TCP connection:

 DNS is not working.


 Cables are unplugged.
 Microsoft Windows has a firewall that blocks a specific port.
 The application that is monitoring a port fails.
 A Windows-based server is renamed.
 A Windows-based server is rebooted.
Note

Mirroring does not protect against problems specific to client accessing the servers. For
example, consider a case in which a public network adapter handles client connections
to the principal server instance, while a private network interface card handles all
mirroring traffic among server instances. In this case, failure of the public network
adapter would prevent clients from accessing the database, though the database would
continue to be mirrored.

Failures Due to Soft Errors


Conditions that might cause mirroring time-outs include (but are not limited to) the
following:

 Network errors such as TCP link time-outs, dropped or corrupted packets, or


packets that are in an incorrect order.
 A hanging operating system, server, or database state.
 A Windows server timing out.
 Insufficient computing resources, such as a CPU or disk overload, the transaction
log filling up, or the system is running out of memory or threads. In these cases,
you must increase the time-out period, reduce the workload, or change the
hardware to handle the workload.

The Mirroring Time-Out Mechanism

Because soft errors are not detectable directly by a server instance, a soft error could
potentially cause a server instance to wait indefinitely. To prevent this, database
mirroring implements its own time-out mechanism, based on each server instance in a
mirroring session sending out a ping on each open connection at a fixed interval.
51

To keep a connection open, a server instance must receive a ping on that connection in
the time-out period defined, plus the time that is required to send one more ping.
Receiving a ping during the time-out period indicates that the connection is still open
and that the server instances are communicating over it. On receiving a ping, a server
instance resets its time-out counter on that connection.

If no ping is received on a connection during the time-out period, a server instance


considers the connection to have timed out. The server instance closes the timed-out
connection and handles the time-out event according to the state and operating mode
of the session.

Even if the other server is actually proceeding correctly, a time-out is considered a


failure. If the time-out value for a session is too short for the regular responsiveness of
either partner, false failures can occur. A false failure occurs when one server instance
successfully contacts another whose response time is so slow that its pings are not
received before the time-out period expires.

In high-performance mode sessions, the time-out period is always 10 seconds. This is


generally enough to avoid false failures. In high-safety mode sessions, the default time-
out period is 10 seconds, but you can change the duration. To avoid false failures, we
recommend that the mirroring time-out period always be 10 seconds or more.

To change the time-out value (high-safety mode only)

 Use the ALTER DATABASE <database> SET PARTNER TIMEOUT


<integer> statement.

To view the current time-out value

 Query mirroring_connection_timeout in sys.database_mirroring.

Responding to an Error
Regardless of the type of error, a server instance that detects an error responds
appropriately based on the role of the instance, the operating mode of the session, and
the state of any other connection in the session. For information about what occurs on
the loss of a partner, see Database Mirroring Operating Modes.
++++++++++++++++++++++++++++++

The Database Mirroring Endpoint (SQL Server)


52

2017-3-14 4 min to read Contributors


To participate in Always On availability groups or database mirroring a server instance


requires its own, dedicated database mirroring endpoint. This endpoint is a special-
purpose endpoint that is used exclusively to receive connections from other server
instances. On a given server instance, every Always On availability groups or database
mirroring connection to any other server instance uses a single database mirroring
endpoint.

Database mirroring endpoints use Transmission Control Protocol (TCP) to send and
receive messages between the server instances participating database mirroring
sessions or hosting availability replicas. The database mirroring endpoint listens on a
unique TCP port number.
Note

Client connections to a principal server or primary replica do not use the database
mirroring endpoint.
53

Note

The database mirroring feature will be removed in a future version of Microsoft SQL
Server. Avoid using this feature in new development work, and plan to modify
applications that currently use database mirroring to use Always On availability groups
instead.

Server Network Address


The network address of a server instance (its server network address or Endpoint URL)
contains the port number of its endpoint, as well as the system and domain name of its
host computer. The port number uniquely identifies a specific server instance.

The following figure illustrates how two server instances on the same server are uniquely
identified. The server network addresses of both server instances contain the same
system name, MYSYSTEM , and domain name, Adventure-Works.MyDomain.com . To enable
the system to route connections to a server instance, a server network address includes
the port number associated with the mirroring endpoint of a particular server instance.
54

By default, an instance of SQL Server does not contain a database mirroring endpoint.
These must be created manually as part of setting up a database mirroring session. The
system administrator must create a separate endpoint in each server instance that is to
participate in database mirroring. Note that if more than one server instance on a given
computer requires a database mirroring endpoint, specify a different port number for
each endpoint.
Important

If the computer running SQL Server has a firewall, the firewall configuration must allow
both incoming and outgoing connections for the port specified in the endpoint.

For database mirroring and Always On availability groups, authentication and encryption
are configured on the endpoint. For more information, see Transport Security for
Database Mirroring and Always On Availability Groups (SQL Server).
Important

Do not reconfigure an in-use database mirroring endpoint. The server instances use
each other's endpoints to learn the state of the other systems. If the endpoint is
reconfigured, it might restart, which can appear to be an error to the other server
instances. This is particularly important for automatic failover mode, in which
reconfiguring the endpoint on a partner could cause a failover to occur.

Determining the Authentication Type for a Database


Mirroring Endpoint
It is important to understand that the SQL Server service accounts of your server
instances determine what type of authentication you can use for your database
mirroring endpoints, as follows:

 If every server instance is running under a domain service account, you can use
Windows Authentication for your database mirroring endpoints. If all the server
instances run as the same domain user account, the correct user logins exist
automatically in both master databases. This simplifies the security configuration
for the availability databases and is recommended.

If any server instances that are hosting the availability replicas for an availability
group run as different accounts, the login each account must be created
in master on the other server instance. Then, that login must be granted
CONNECT permissions to connect to the database mirroring endpoint of that
55

server instance. For more information, Set Up Login Accounts for Database
Mirroring or Always On Availability Groups (SQL Server).

If your server instances use Windows Authentication, you can create database
mirroring endpoints by using Transact-SQL, PowerShell, or the New Availability
Group Wizard.
Note

If a server instance that is to host an availability replica lacks a database mirroring


endpoint, the New Availability Group Wizard can automatically create a database
mirroring endpoint that uses Windows Authentication. For more information,
see Use the Availability Group Wizard (SQL Server Management Studio).

 If any server instance is running under a built-in account, such as Local System,
Local Service, or Network Service, or a nondomain account, you must use
certificates for endpoint authentication. If you are using certificates for your
database mirroring endpoints, your system administrator must configure each
server instance to use certificates on both outbound and inbound connections.

There is no automated method for configuring database mirroring security using


certificates. You will need to use either CREATE ENDPOINT Transact-SQL statement
or the New-SqlHadrEndpoint PowerShell cmdlet. For more information,
see CREATE ENDPOINT (Transact-SQL). For information about enabling certificate
authentication on a server instance, see Use Certificates for a Database Mirroring
Endpoint (Transact-SQL).
+++++++++++++++++++++++

Setting Up Database Mirroring (SQL Server)


2016-5-17 5 min to read Contributors

56

This section describes the prerequisites, recommendations, and steps for setting up
database mirroring. For an introduction to database mirroring, see Database Mirroring
(SQL Server).
Important

We recommend that you configure database mirroring during off-peak hours because
configuration can impact performance.

Preparing a Server Instance to Host a Mirror Server


For each database mirroring session:

1. The principal server, mirror server, and witness, if any, must be hosted by separate
server instances, which should be on separate host systems. Each of the server
instances requires a database mirroring endpoint. If you need to create a database
mirroring endpoint, ensure that it is accessible to the other server instances.
57

The form of authentication used for database mirroring by a server instance is a


property of its database mirroring endpoint. Two types of transport security are
available for database mirroring: Windows Authentication or certificate-based
authentication. For more information, see Transport Security for Database
Mirroring and Always On Availability Groups (SQL Server).

The requirements for network access are specific to the form of authentication, as
follows:

 If using Windows Authentication

If server instances are running under different domain user accounts, each
requires a login in the master database of the others. If the login does not
exist, you must create it. For more information, see Allow Network Access to
a Database Mirroring Endpoint Using Windows Authentication (SQL Server).

 If using certificates

To enable certificate authentication for database mirroring on a given server


instance, the system administrator must configure each server instance to use
certificates on both outbound and inbound connections. Outbound
connections must be configured first. For more information, see Use
Certificates for a Database Mirroring Endpoint (Transact-SQL).

2. Make sure that logins exist on the mirror server for all the database users. For
more information, see Set Up Login Accounts for Database Mirroring or Always On
Availability Groups (SQL Server).
3. On the server instance that will host the mirror database, set up the rest of the
environment that is required for the mirrored database. For more information,
see Manage Metadata When Making a Database Available on Another Server
Instance (SQL Server).

Overview: Establishing a Database Mirroring Session


The basic steps for establishing a mirroring session are as follows:

1. Create the mirror database by restoring the following backups, using RESTORE
WITH NORECOVERY on every restore operation:
a. Restore a recent full database backup of the principal database, after making
sure that the principal database was already using the full recovery model when
58

the backup was taken. The mirror database must have the same name as the
principal database.
b. If you have taken any differential backups of the database since the restored full
backup, restore your most recent differential backup.
c. Restore all the log backups done since the full or differential database backup.

For more information, see Prepare a Mirror Database for Mirroring (SQL Server).
2. Important

3. Complete the remaining setup steps as soon as you can after taking the backup of
the principal database. Before you can start mirroring on the partners, you should
create a current log backup on the original database and restore it to the future
mirror database.

4. You can set up mirroring by using either Transact-SQL or the Database Mirroring
Wizard. For more information, see one of the following:
 Establish a Database Mirroring Session Using Windows Authentication
(Transact-SQL)
 Establish a Database Mirroring Session Using Windows Authentication (SQL
Server Management Studio)
5. By default a session is set to full transaction safety (SAFETY is set to FULL), which
starts the session in synchronous, high-safety mode without automatic failover.
You can reconfigure the session to run in high-safety mode with automatic failover
or in asynchronous, high-performance mode, as follows:
 High-safety mode with automatic failover

If you want a high-safety mode session to support automatic failover, add a


witness server instance.

To add a witness

o Add a Database Mirroring Witness Using Windows Authentication


(Transact-SQL)
o Establish a Database Mirroring Session Using Windows Authentication
(SQL Server Management Studio)
Note

The database owner can turn off the witness for a database at any time.
Turning off the witness is equivalent to having no witness, and automatic
failover cannot occur.

 High-performance mode
59

Alternatively, if you do not want automatic failover and you prefer to


emphasize performance over availability, turn off transaction safety. For more
information, see Change Transaction Safety in a Database Mirroring Session
(Transact-SQL).
Note

In high-performance mode, WITNESS needs to be set to OFF. For more


information, see Quorum: How a Witness Affects Database Availability
(Database Mirroring).
Note

For an example of using Transact-SQL to set up database mirroring using Microsoft


Windows Authentication, see Example: Setting Up Database Mirroring Using Windows
Authentication (Transact-SQL).

For an example of using Transact-SQL to set up database mirroring using certificate-


based security, see Example: Setting Up Database Mirroring Using Certificates (Transact-
SQL).
++++++++++++++++++

Connect Clients to a Database Mirroring


Session (SQL Server)
2017-3-14 17 min to read Contributors

60

To connect to a database mirroring session, a client can use either SQL Server Native
Client or .NET Framework Data Provider for SQL Server. When configured for a SQL
Server 2017 database, these data access providers both fully support database
mirroring. For information about programming considerations for using a mirrored
database, see Using Database Mirroring. In addition, the current principal server
instance must be available and the login of the client must have been created on the
server instance. For more information, see Troubleshoot Orphaned Users (SQL Server).
Client connections to a database mirroring session do not involve the witness server
instance, if one exists.

Making the Initial Connection to a Database Mirroring


Session
For the initial connection to a mirrored database, a client must supply a connection
string that minimally supplies the name of a server instance. This required server name
61

should identify the current principal server instance and is known as the initial partner
name.

Optionally, the connection string can also supply the name of another server instance,
which should identify the current mirror server instance, for use if the initial partner is
unavailable during the first connection attempt. The second name is known as
the failover partner name.

The connection string must also supply a database name. This is necessary to enable
failover attempts by the data access provider.

On receiving a connection string, the data access provider stores the initial partner name
and the failover partner name, if supplied, in a cache in the client's volatile memory (for
managed code, the cache is scoped to the application domain). Once cached, the initial
partner name is never updated by the data access provider. When the client supplies the
failover partner name, the data access provider also stores this failover partner name
temporarily in case the provider cannot connect using the initial partner name.

A database mirroring session does not protect against server-access problems that are
specific to clients, such as when a client computer is having a problems communicating
with the network. A connection attempt to a mirrored database can also fail for a variety
of reasons that are unrelated to the data-access provider; for example, a connection
attempt can fail because the principal server instance is inactive, as occurs when the
database is failing over, or because of a network error.

When attempting to connect, the data access provider begins by using the initial partner
name. If the specified server instance is available and is the current principal server
instance, the connection attempt typically succeeds.
Note

If the mirroring session is paused, the client typically connects to the principal server
and the downloads the partner name. However, the database is unavailable to the client
until mirroring resumes.

If that attempt does not work, the data access provider tries the failover partner name, if
available. If either partner name correctly identifies the current principal server, the data
access provider normally succeeds in opening the initial connection. On completing this
connection, the data access provider downloads the server instance name of the current
mirror server. This name is stored in the cache as the failover partner name, overwriting
the client-supplied failover partner name, if any. Thereafter, the .NET Framework Data
Provider for SQL Server does not update the failover partner name. In contrast, SQL
62

Server Native Client updates the cache whenever a subsequent connection or


connection reset returns a different partner name.

The following figure illustrates a client connection to the initial partner, Partner_A, for a
mirrored database named Db_1. This figure shows a case in which the initial partner
name supplied by the client correctly identifies the current principal server, Partner_A.
The initial connection attempt succeeds, and the data access provider stores the name
of the mirror server (currently Partner_B) as the failover partner name in the local
cache. Finally, the client connects to the principal copy of the Db_1 database.

The initial connection attempt may fail, for example, because of a network error or an
inactive server instance. Because the initial partner is unavailable, for the data access
provider to attempt to connect to the failover partner, the client must have supplied the
failover partner name in the connection string.

In that case, if the failover partner name is unavailable, the original connection attempt
continues until the network connection timeout or an error is returned (just as for a
non-mirrored database).

When the failover partner name is supplied in the connection string, the behavior of the
data access provider depends on the network protocol and operating system of the
client, as follows:

 For TCP/IP, the connection attempts are regulated by a connection retry algorithm
that is specific to database mirroring. The connection retry algorithm determines
the maximum time (the retry time) allotted for opening a connection in a given
connection attempt.
63

 For other network protocols

If an error occurs or if the initial partner is unavailable, the initial connection


attempt waits until the network connection timeout period expires or the login
timeout period expires on the data access provider. Typically, this wait is on the
order of 20 to 30 seconds. Thereafter, if the data access provider has not timed
out, it attempts to connect to the failover partner. If the connection timeout period
expires before the connection succeeds or the failover partner is unavailable, the
connection attempt fails. If failover partner is available within the login timeout
period and is now the principal server, the connection attempt normally succeeds.

Connection Strings for a Mirrored Database

The connection string supplied by the client contains information that the data access
provider uses to connect to the database. This section discusses the keywords that are
specifically relevant for connecting to a mirrored database using a SQL Server Native
Client ODBC Driver Connection.

Network Attribute

The connection string should contain the Network attribute to specify the network
protocol. This ensures that the specified network protocol persists between connections
to different partners. The best protocol for connecting to a mirrored database is TCP/IP.
To ensure that the client requests TCP/IP for every connection to the partners, a
connection string supplies the following attribute:
Copy

Network=dbmssocn;

Important

We recommend keeping TCP/IP at the top of a client's protocol list. However, if the
connection string specifies the Network attribute, this overrides the list order.

Alternatively, to ensure that the client requests named pipes for every connection to the
partners, a connection string supplies the following attribute:
Copy

Network=dbnmpntw;

Important
64

Because named pipes does not use the TCP/IP retry algorithm, in many cases, a named
pipes connection attempt may time out before connecting to a mirrored database.

Server Attribute

The connection string must contain a Server attribute that supplies the initial partner
name, which should identify the current principal server instance.

The simplest way to identify the server instance is by specifying its name , [\]. For
example:

Server=Partner_A;

or

Server=Partner_A\Instance_2;

However, when the system name is used, the client must perform a DNS lookup to
obtain the IP address of the server and a SQL Server Browser query to obtain the port
number of the server on which the partner resides. Those lookups and queries can be
bypassed by specifying the IP address and port number of the partner in
the Server attribute, rather than specifying the server name. This is recommended to
minimize the possibility of external delays while connecting to that partner.
Note

A SQL Server Browser query is necessary if the connection string specifies the named
instance name and not the port.

To specify the IP address and port, the Server attribute takes the following
form, Server=, <port>, for example:
Copy

Server=123.34.45.56,4724;

Note

The IP address can be IP Version 4 (IPv4) or IP Version 6 (IPv6).

Database Attribute
65

In addition, the connection string must specify the Database attribute to supply the
name of the mirrored database. If the database is unavailable when the client attempts
to connect, an exception is raised.

For example, to expressly connect to the AdventureWorks database on the principal


server Partner_A, a client uses the following connection string:

" Server=Partner_A; Database=AdventureWorks "


Note

This string omits authentication information.


Important

Bundling the protocol prefix with the Server attribute ( Server=tcp: <servername>) is
incompatible with the Network attribute, and specifying the protocol in both places will
likely result in an error. Therefore, we recommend that a connection string specify the
protocol using the Network attribute and specify only the server name in
the Server attribute ( "Network=dbmssocn; Server= <servername> " ).

Failover Partner Attribute

In addition to the initial partner name, the client can also specify failover partner name,
which should identify the current mirror server instance. The failover partner is specified
by one of the keywords for the failover partner attribute. The keyword for this attribute
depends on the API that you are using. The following table lists these keywords:
API Keyword for failover partner attribute

OLE DB Provider FailoverPartner

ODBC Driver Failover_Partner

ActiveX Data Objects (ADO) Failover Partner

The simplest way to identify the server instance is by its system name, [\].

Alternatively, the IP address and port number can be supplied in the Failover
Partner attribute. If the initial connection attempt fails during the first connection to the
database, the attempt to connect to the failover partner will be freed from relying on
DNS and SQL Server Browser. Once a connection is established, the failover partner
66

name will be overwritten with the failover partner name, so if a failover occurs, the
redirected connections will require DNS and SQL Server Browser.
Note

When only the initial partner name is provided, application developers do not need to
take any action or write any code except about how to reconnect.
Note

Managed code application developers supply the failover partner name in


the ConnectionString of the SqlConnection object. For information on using this
connection string, see "Database Mirroring Support in the .NET Framework Data
Provider for SQL Server" in the ADO.NET documentation, which is part of the Microsoft
.NET Framework SDK.

Example Connection String

For example, to explicitly connect using TCP/IP to the AdventureWorks database on


either Partner_A or Partner_B, a client application that uses the ODBC Driver could
supply the following connection string:
Copy

"Server=Partner_A; Failover_Partner=Partner_B; Database=AdventureWorks;


Network=dbmssocn"

Alternatively, the client could use the IP address and port number to identify the initial
partner, Partner_A; for example, if the IP address is 250.65.43.21 and the port number is
4734, the connection string would be:
Copy

"Server=250.65.43.21,4734; Failover_Partner=Partner_B; Database=AdventureWorks;


Network=dbmssocn"

Connection Retry Algorithm (for TCP/IP Connections)


For a TCP/IP connection, when both partner names are in the cache, the data access
provider adheres to a connection retry algorithm. This is true both for making the initial
connection to the session and for reconnecting after losing an established connection.
67

Once a connection has been opened, completing the pre-login and login steps takes
additional time.
Note

The time spent in opening a connection can exceed the retry time because of external
factors, such as slow DNS lookups, slow domain controller/Kerberos Key Distribution
Center (KDC), time spent contacting SQL Server Browser, network congestion, and so
forth. Such external factors can prevent a client from connecting to a mirrored database.
Also, external factors can cause a connection to take longer to open than the allotted
retry time. For information on bypassing DNS and SQL Server Browser for connection
attempt to the initial partner, see Making the Initial Connection to a Database Mirroring
Session, earlier in this topic.

If a connection attempt fails or the retry time expires before it succeeds, the data access
provider tries the other partner. If a connection is not opened by this point, the provider
alternately tries the initial and failover partner names, until a connection is opened or
the login period times out. The default login time-out period is 15 seconds. We
recommend that the login time-out period be at least 5 seconds. Specifying a smaller
time-out period might prevent any of the connection attempts from succeeding.

The retry time is a percentage of the login period. The retry time for a connection
attempt is larger in each successive round. In the first round, the retry time for each of
the two attempts is 8 percent of the total login period. In each successive round, the
retry algorithm increases the maximum retry time by the same amount. Thus, the retry
times for the first eight connection attempts is as follows:

8%, 8%, 16%, 16%, 24%, 24%, 32%, 32%

The retry time is calculated using the following formula:

RetryTime = PreviousRetryTime +( 0.08 \LoginTimeout)*

Where PreviousRetryTime is initially 0.

For example, if using the default login time-out period of 15 seconds, LoginTimeout =
15. In this case, the retry times allotted in the first three rounds are as follows:
Round RetryTime calculation Retry time per attempt

1 0 +(0.08 \* 15) 1.2 seconds


68

Round RetryTime calculation Retry time per attempt

2 1.2 +(0.08 \* 15) 2.4 seconds

3 2.4 +(0.08 \* 15) 3.6 seconds

4 3.6 +(0.08 \* 15) 4.8 seconds

The following figure illustrates these retry times for successive connection attempts,
each of which times out.

For the default login time-out period, the maximum time allotted to the first three
rounds of connection attempts is 14.4 seconds. If every attempt were to use all of its
allotted time, only 0.6 seconds of time would remain before the login period times out.
In that case, the fourth round would be curtailed, allowing only a final quick attempt to
connect using the initial partner name. However, a connection attempt may fail in less
than its allotted retry time, particularly in later rounds. For example, receiving a network
error can cause an attempt to end before the retry time expires. If earlier attempts fail
due to a network error, additional time would be available for the fourth round and,
perhaps, additional rounds.

Another cause of a failed attempt is an inactive server instance, as occurs when a server
instance is engaged in failing over its database. In this case, a retry delay is imposed to
prevent clients from overloading the partners with a rapid succession of connection
attempts.
Note
69

When both partner names are available, if the login time-out period is infinite, the client
attempts to reconnect to the servers indefinitely, alternating between the initial partner
name and the failover partner name.

Retry Delays During Failover

If a client attempts to connect to a partner that is failing over, the partner immediately
responds that it is inactive. In this case, each round of connection attempts are much
briefer than the allotted retry time. This means that many rounds of connection
attempts could happen before the login period times out. To avoid overloading the
partners with a rapid series of connection attempts during a failover, the data access
provider adds a brief retry delay after each retry cycle. The length of a given retry delay
is determined by the retry-delay algorithm. After the first round, the delay is 100
milliseconds. After each of the next three rounds, the retry delay doubles—to 200, 400,
and 800. For all later rounds, the retry delay is 1 second until the connection attempt
succeeds or times out.
Note

If the server instance is stopped, then the connection request fails immediately.

The following figure illustrates how the retry delay affects connection attempts during a
manual failover, in which the partners switch their roles. The login time-out period is 15
seconds.

Reconnecting to a Database Mirroring Session


70

If an established connection to a database mirroring session fails for any reason, for
example, due to a database mirroring failover, and the application attempts to
reconnect to the initial server, the data access provider can attempt to reconnect using
the failover partner name stored in the client's cache. Reconnecting is not automatic,
however. The application must become aware of the error. Then, the application needs
to close the failed connection and open a new connection using the same connection
string attributes. At this point, the data access provider redirects the connection to the
failover partner. If the server instance identified by this name is currently the principal
server, the connection attempt usually succeeds. If it is unclear whether a transaction
was committed or rolled back, the application must check on the state of the
transaction, in the same way as when reconnecting to a stand-alone server instance.

Reconnecting resembles an initial connection for which the connection string supplied a
failover partner name. If the first connection attempt fails, connection attempts alternate
back and forth between the initial partner name and failover partner name until either
the client connects to the principal server or the data access provider times out.
Note

SQL Server Native Client verifies that it connects to a principal server instance but not
whether this instance is the partner of server instance specified in the initial partner
name of the connection string.

If the connections use TCP/IP, the connection retry algorithm determines the amount of
time allotted to the connection attempts in each round.
Important

If the client gets disconnected from the database, the data access provider does not
attempt to reconnect. The client must issue a new connection request. Also, if an
application shuts down on losing the connection, it will lose the cached partner names.
If the connection was lost because the principal server became unavailable, the only way
that the application can reconnect to the mirror server is by supplying the failover
partner name in its connection string.

Impact of Redirection on a Client Application

After a failover, the data access provider redirects the connection to the current principal
server instance. However, the redirection is transparent to clients. To a client, a
redirected connection appears to be a connection to the server instance identified by
the initial partner name. When the initial partner is currently the mirror server, the client
can appear to be connected to the mirror server and updating the mirror database.
71

Actually, however, the client has been redirected to the failover partner, which is the
current principal database, and the client is updating the new principal database.

After being redirected to the failover partner, a client can experience unexpected results
when using a Transact-SQL USE statement to use a different database. This can happen
if the current principal server instance (the failover partner) has a different set of
databases than the original principal server (the initial partner).

The Impact of a Stale Failover Partner Name


The database administrator can change the failover partner at any time. Therefore, a
client-supplied failover partner name might be out of date, or stale. For example,
consider a failover partner named Partner_B that is replaced by another server instance,
Partner_C. Now, if a client supplies Partner_B as the failover partner name, that name is
stale. When the client-supplied failover partner name is stale, the behavior of the data
access provider equates to the case in which a failover partner name is not supplied by
the client.

Principal Mirror Behavior when attempting to connect


Configuration server server specifying Partner_A and Partner_B

Original mirroring Partner_A Partner_B Partner_A is cached as the initial partner


configuration. name. The client succeeds in connecting to
Partner_A. The client downloads the name of
mirror server, Partner_B, and caches it,
ignoring the client-supplied failover partner
name.

Partner_A experiences a Partner_B none The Partner_A is still cached as the initial
hardware failure, and failover partner name, but the client-supplied failover
occurs (disconnecting clients). partner name, Partner_B, permits the client to
connect to the current principal server.

The database administrator Partner_B Partner_C The client attempts to connect to Partner_A
stops mirroring and fails; then the client tries Partner_B (the
(disconnecting clients), current principal server) and succeeds. The
replaces Partner_A with data access provider downloads the name of
Partner_C, and restarts the current mirror server, Partner_C, and
mirroring. caches it as the current failover partner name.
72

Service is manually failed Partner_C Partner_B Client attempts to connect to Partner_A


over to Partner_C initially, and then to Partner_B. Both names
(disconnecting clients). fail, and eventually the connection request
times out and fails.

For example, consider situation in which a client uses one connection string for a series
of four connection attempts. In the connection string, the initial partner name is
Partner_A, and the failover partner name is Partner_B:
Copy

"Server=Partner_A; Failover Partner=Partner_B; Database=AdventureWorks"

The following table shows four partner configurations and indicates for each whether
this connection string works for connecting the client for the first time.
Note

An application can track configuration changes and change its connection string
accordingly. This requires extra code but reduces the administrative burden.

See Also
++++++++++++++++++++

Pausing and Resuming Database Mirroring


(SQL Server)
2017-3-4 2 min to read Contributors

The database owner can pause and later resume a database mirroring session at any
time. Pausing preserves the session state while suspending mirroring. During
bottlenecks, pausing might be useful to improve performance on the principal server.
73

When a session is paused, the principal database remains available. Pausing sets the
state of the mirroring session to SUSPENDED, and the mirror database no longer keeps
up with the principal database, causing the principal database to run exposed.

We recommend that you resume a paused session quickly, because as long as a


database mirroring session remains paused, the transaction log cannot be truncated.
Therefore, if a database mirroring session is paused for too long, the transaction log fills
up, making the database unavailable. For an explanation of why this happens, see "How
Pausing and Resuming Affect Log Truncation," later in this topic.
Important

Following a forced service, when the original principal server reconnects mirroring is
suspended. Resuming mirroring in this situation could possibly cause data loss on the
original principal server. For information about managing the potential data loss,
see Database Mirroring Operating Modes.

In this Topic:

 How Pausing and Resuming Affect Log Truncation


 Avoid a Full Transaction Log
 Related Tasks

How Pausing and Resuming Affect Log Truncation


Normally, when an automatic checkpoint is performed on a database, its transaction log
is truncated to that checkpoint after the next log backup. While a database mirroring
session remains paused, all of the current log records remain active because the
principal server is waiting to send them to the mirror server. The unsent log records
accumulate in the transaction log of the principal database until the session resumes
and the principal server has sent the log records to the mirror server.

When the session is resumed, the principal server immediately begins sending the
accumulated log records to the mirror server. After the mirror server confirms that it has
queued the log record corresponding to the oldest automatic checkpoint, the principal
server truncates the log of the principal database to that checkpoint. The mirror server
truncates the redo queue at the same log record. As this process is repeated for each
successive checkpoint, the log is truncated in stages, checkpoint by checkpoint.
Note

For more information about the checkpoints and log truncation, see Database
Checkpoints (SQL Server).
74

Avoid a Full Transaction Log


If the log fills up (either because it reaches its maximum size or the server instance runs
out of space), the database cannot perform any more updates. To avoid this problem,
you have two alternatives:

 Resume the database mirroring session before the log fills up, or add more log
space. Resuming database mirroring lets the principal server send its accumulated
active log to the mirror server and puts the mirror database in the
SYNCHRONIZING state. The mirror server can then harden the log to disk and start
to redo it.
 Stop the database mirroring session by removing mirroring.

Unlike pausing a session, removing mirroring drops all information about the
mirroring session. Each partner server instance retains its own copy of the
database. If the former mirror copy is recovered, it will have diverged from the
former principal copy and be behind by the amount of time that has elapsed since
the session was paused. For more information, see Removing Database Mirroring
(SQL Server).
+++++++++++++++++++++++++++

Vous aimerez peut-être aussi