Vous êtes sur la page 1sur 61

Microsoft SQL Server Community (http://sqlcommunity.

com)

SQLFEST
Author: Saleem Hakani | http://sqlcommunity.com

COPYRIGHT AND TRADEMARK NOTICES:


All contents of the this article are: Copyright 2007 by www.sqlcommunity.com and/or its suppliers. All rights reserved.

Page | 1

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Table of contents:
Topic 1) Overview of Database Mirroring 2) Comparing log shipping with database mirroring 3) Comparing fail-over clustering with database mirroring 4) Database mirroring roles and participants 5) Forming a quorum 6) Transaction safety and operating modes 7) Client redirection 8) Endpoints: Communication mechanism for database mirroring 9) Understanding different types of failovers and role switching 10) Pre-requisites for setting up database mirroring 11) Database mirroring setup flow 12) Setting up database mirroring using T-SQL 13) Viewing the database mirroring state 14) Monitoring database mirroring 15) Setting up database mirroring thresholds 16) Querying the status of performance metrics 17) Database mirroring maintenance and operations Changing modes and transaction safety using T-SQL Steps to take when rebooting, applying hot fixes or service packs Changing the default auto-failover timeout value Performing manual failover Performing forced failover Setting up database mirroring on low-bandwidth networks / modems Setting up database mirroring on local area network Geo-redundancy with database mirroring Preparing the mirror server for failover Mirroring multiple databases 18) What happens when you lose a server? 19) Viewing database mirroring information using T-SQL 20) Monitoring database mirroring performance 21) Suspending and resuming a mirror session 22) Making replication mirror-aware 23) Implementing database mirroring in production environment 24) Querying mirrored database using database snapshots 25) Documenting database mirroring environment Page Numbers 2 3 3 5 6 7 9 10 11 13 14 15 19 20 22 24 25 25 27 28 28 29 29 30 30 31 32 33 34 37 38 40 41 42 43

Page | 2

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Overview of Database Mirroring

SQLFEST

With the introduction of SP1 in SQL Server 2005, Microsoft introduced a new high availability technology called Database Mirroring. It works by transferring transaction log records for a database from the primary server to the secondary server, thereby maintaining a hot standby server. As with normal SQL Server operation, with Database Mirroring data changes are recorded in the transaction log before any changes to actual data pages are made. The log records are first placed in the principal databases log buffer in memory and then hardened to disk. Those transaction log records are copied to and replayed on the mirror servers database. Because the mirror database replays the principal's transaction log records, it duplicates the principals database changes on the mirrors database. Note: Database Mirroring was also available prior to SP1 for SQL Server 2005 but was disabled by default; you could enable it by using the trace flag T1400 during SQL Server start-up. Database Mirroring gives SQL Server 2005 a nearly instant standby capability by providing database-level failover. When Database Mirroring is enabled and the primary/principal database fails, the mirrored database on the standby SQL Server system becomes available within a few seconds. Database Mirroring works with all the standard hardware that supports SQL Server 2005 and it enables zero data loss in the event of a database failure. The mirror database will always be updated with the current transaction thats being processed on the primary database server.

High Level Database Mirroring

Page | 3

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

You might ask this question as to why was there a need of introducing a new high availability technology when we already have log shipping, fail-over clustering, etc? Well, every technology has its advantages and disadvantages. In many cases database mirroring offers the same level of data redundancy as log shipping with the advantage of higher availability and automatic failover. Both the technologies provide protection on a per database basis and utilize SQL Server recovery capabilities. Some of the major differences are compared in the next topic.

SQLFEST

Comparing Log Shipping with Database Mirroring


Log shipping provides you a warm standby of your data that can be brought online in the event your primary system fails for any reason. Log shipping works by restoring a full database backup to a secondary server, and then transaction logs from the primary database are continuously applied to the secondary database. Note: Log shipping is available only for user databases and not for system databases (same as Database Mirroring). The following table lists some of the differences between Log Shipping and Database Mirroring: Consideration Data Transfer Log Shipping T-Logs are backed up and transferred to secondary server Can be applied to multiple stand-by servers Manual Can take more than 30 mins Database Mirroring Individual T-Log records are transferred using TCP endpoints Can be applied to only one mirror server Automatic Failover is fast, sometimes takes seconds Role change is fully automatic Fully automatic with the use of .NET 2.0

Server Limitation

Failover Failover duration

Role Change Client Redirection

Role change is manual Manual changes required

Page | 4

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Comparing Failover Clustering with Database Mirroring


Failover clustering is another technology for maintaining your database servers highly available, it provides instance-wide high availability which can help you with hardware failure or can help you with scheduled maintenance. In case of failure, the operating system and SQL Server work together to provide automatic system for failover. You can configure one node to failover during scheduled maintenance. With SQL Server 2005, Failover clustering now supports up to eight nodes when running on Microsoft Windows Server 2003 Datacenter edition. SQL Server 2005 also extends clustering functionality to enable you to use clustering in conjunction with Analysis Services and Full-Text Search. Database Mirroring offers several advantages over failover clustering, such as faster failover, protection against storage failures, standard hardware, low maintenance, etc. The following table lists some of the differences between failover clustering and database mirroring:

SQLFEST

Consideration Standby Type Protection from Disks H/A Level Failover Duration

Failover clustering Hot Standby If the shared disk crashes your entire cluster is down Instance Level > = 30 seconds + Database Recovery < = 100 miles; more with geographically-dispersed clusters Specific hardware required Setup is more complex at the system level

Database Mirroring Instant Standby Provides redundancy in the event of a server and or storage failure Database Level Failover is fast, sometime takes seconds.

Distance Limitation

Virtually no distance limit

Hardware

Standard SQL Server 2005 hardware Setup is easy and completely within SQL Server

Setup

Page | 5

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Scope Failure Detection Transparent to client Whole instance; all system & user databases Yes Yes, Reconnect to same IP Only user databases can be mirrored Yes Yes, Auto-Redirect Minimal impact (Since the log records must be copied; response time may impact due to latency on commit) Yes

Impact on throughput

No Impact

Zero work loss

Yes

So now you know that database mirroring can be the best H/A solution for many scenarios, lets look at how it can be implemented. Database mirroring comprises of the following components and learning these components will help you setup, configure, and maintain database mirroring: Roles Quorum Transaction Safety, Operating mode Endpoints

Lets look at each of them in detail.

Database Mirroring Roles and Participants


There are three roles a database can take on when participating in database mirroring: 1. The principal Server role 2. The mirror Server role 3. The witness server role (optional)

1. Principal database role:


The role of the principal server is to serve the production database to clients. Only the principal database is accessible to client connections. When the principal database receives changes requested by clients, the principal server sends those active changes to the mirror server.

Page | 6

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

2. Mirror database role:

SQLFEST

Mirror server holds an exact point-in-time copy of the principal database and is always ready to take over the principal server role in the event of a failure on the principal server. It acts as a hot standby server. When the mirror receives the changes sent by the principal, it places those changes in mirror databases log buffer and then commits them to disk as quickly as possible. Internally, the mirror server redoes the log on the mirror database with the oldest log record, record by record and as quickly as possible. Redoing the log involves applying the pending or queued changes to the mirror database in sequence, starting with the oldest record. Each change is done only once and it is then rolled forward. When the principal server truncates or shrinks the log for the principal database, the mirror server also shrinks the log at the same point. This is because the mirror server replays the activities of principal databases changes. Note: Your mirror server hardware, disk configuration and database file placement should be exactly the same way principal server is configured so that in the event of the failover the mirror functions exactly the same way as your principal server.

3. Witness server role:


In the database mirroring topology you may have an optional third server called the witness. Witness server is required for enabling automatic failover from principal to mirror server or vice-versa. Unlike principal and mirror servers, the witness server does not serve the database. The role of the witness is to verify whether a given partner server is up and functioning. Supporting automatic failover is the only function for witness server. It uses quorum to identify which server holds the principal copy and which server holds the mirror copy of the database. (more information about quorum is explained in the next topic) Note: Witness server can be any computer that can support SQL Server 2005; it doesnt have to be a high-end computer as long as it meets the recommended requirements for SQL Server 2005.

Forming a quorum:
Quorum basically is a relationship among two or more SQL Servers participating in a database mirroring session. Quorum is required only when a witness is setup for high availability in a database mirroring session. If a witness is present, a loss of either principal or mirror database leaves two servers to form a quorum. If the principal server cant see the mirror server, but if it can see the witness and form a quorum with the witness, it can keep its database in service. Similarly, if the mirror and witness server cannot see the principal, but if it can see the witness and can form a quorum with the witness, the mirror can take on the role of the new principal server.

Page | 7

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
There can be three types of quorum in database mirroring:
1. Full quorum 2. Partner to witness 3. Partner to partner More on these quorums can be found in the below table.

Quorum Type A Full Quorum

Description This includes all the 3 servers participating in database mirroring (Principal, Mirror & Witness). The good thing about Full Quorum is that if the Principal is not available, Database Mirroring will continue to function as both Witness and Mirror can talk to each other and if the Mirror is not available, database mirroring will still continue to function as both Principal and witness can talk to each other. This includes a witness and either partner (Principal / Mirror)

Full Quorum

Witness to Partner Quorum

If the network connection between the partners is lost because one of the partners has been lost, two cases are possible: 1) The mirror server is lost, and the principal server and witness retain quorum. In this case, the principal sets its database to DISCONNECTED state and runs with mirroring in a SUSPENDED state (this is called running exposed because the database is currently not being
M

Witness to Principal

Page | 8

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
mirrored). When the mirror server rejoins the session, it regains quorum as mirror and begins resynchronizing its copy of the database. 2) The principal server is lost, and the witness and the mirror server retain quorum.
P W M

Witness to mirror Partner to Partner Quorum This happens when the witness server is not available.
P

If the witness is lost, automatic failover is no longer possible. When the witness comes back up, the session resumes normal operation. As long as both Principal and Mirror retains quorum, the database continues in a SYNCHRONIZED state, and manual failover remains possible. When a session has only a partnerto-partner quorum and if either partner loses quorum, the database goes offline and remains unavailable until the principal server regains quorum with either the mirror server or witness.

If you expect the witness to remain disconnected for a significant amount of time, it is recommended that you temporarily remove the witness from the session.

Note: The witness server is not considered as a single point of failure in database mirroring session, because if the witness server fails, the principal and mirror can continue to form a quorum. (Automatic failover will not be possible when the witness is lost but you can manually perform a failover) The witness should be setup only if you intend to use High-Safety (High-availability) mode with automatic failover (both will be covered in the next topic) and if you are using highperformance mode than it is recommended that you dont setup the witness server or set the witness property to OFF.

Page | 9

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Now as we know what the different database mirroring roles and type of quorums are, lets look into the different safety level and operating modes for database mirroring.

SQLFEST

Transaction Safety & operating modes


There are three types of operating modes and two types of transaction safety which helps determine the type of topology in database mirroring and the exact mode is based on the setting of transaction safety and whether a witness is a part of the mirroring session or not: 1) Synchronous with automatic failover 2) Synchronous without automatic failover 3) Asynchronous mode (Safety=FULL) (Safety=FULL) (Safety=OFF)

Synchronous with automatic failover (Safety=FULL)


(Also known as High Availability operating mode) supports maximum database availability with automatic failover to the mirror database. This operating mode is best used where you have fast and very reliable communication between the servers and you require automatic failover for a single database. Please note: With High availability mode the principal server must wait briefly for responses from the mirror server, and therefore the performance of the principal server may be affected by the capability of the mirror server. In this mode Database Mirroring is self monitoring. If the principal database suddenly becomes unavailable, or the principals server is down, then the witness and the mirror will form a quorum of two and the mirror server will perform an automatic failover. Following is the behavior of synchronous with automatic failover mode: Step 1 Principal receives a transaction from client and writes the transaction to the T-log of the principal database Step 2 While the principal server writes the transaction to the t-log on the principal server and once it has hardened the log it sends the log record to the mirror server. At this moment the principal server waits for an acknowledgement from the mirror server. Step 3 During this time the mirror server hardens/commits the log to the disk and returns an acknowledgement to the principal server Step 4 Once the principal server receives the acknowledgement from the mirror server it confirms this acknowledgement for this transaction and is ready to receive new transactions High availability (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. Note: For automatic redirection of your client application please look into Client Redirection in the topics ahead.

Page | 10

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Synchronous without automatic failover (Safety=FULL)


(also known as High Protection operating mode) does not have witness server as part of the mirroring session. The principal database does not need to form a quorum, but because there is no witness, it must be with the mirror server only. Only manual failover is possible in this role as theres no witness.

SQLFEST

Asynchronous mode (SAFETY=OFF)


(Also known as High Performance operating mode) has the transaction safety set to OFF, and the transfer of log records is asynchronous. The principal server does not wait for an acknowledgement from the mirror. The mirror does its best to keep up with the principal, but it is not guaranteed at any point in time that all the most recent transactions from the principal will be hardened in the mirrors transaction log. In this operating mode a witness server plays no role, and a quorum is not required. Therefore automatic and manual failover is not enabled. It only allows FORCED SERVICE failover, which is also a manual operation. However, FORCED SERVICE will be rarely used. Normally you would switch to full safety. The forced service failover causes an immediate recovery of the mirror database. It may involve potential data loss on the mirror when it is recovered if some of the transaction log blocks from the principal have not yet been received by the mirror. Following table lists some of the quick differences between operating modes. Option Synchronous with automatic failover FULL SYNCHRONOUS Yes Yes Automatic or Manual Synchronous without automatic failover FULL SYNCHRONOUS Yes No Manual only Asynchronous

Transaction Safety Transfer Mechanism Quorum Required Witness Server Failover Type

OFF ASYNCHRONOUS No N/A Forced only

If transaction safety is set to FULL, the principal and mirror servers operate in synchronous mode. As the principal server first hardens its principal database log records to disk, and then sends them to the mirror. The principal then waits for a response from the mirror server. The mirror responds when it has hardened those same log records to the mirrors log disk. If the transaction safety is set to OFF, the communication between the principal and the mirror is asynchronous. The principal server will not wait for an acknowledgement from the mirror that the mirror has hardened a block of transaction records. The mirror will attempt to

Page | 11

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

keep up with the principal, by recording transactions as quickly as possible, but some transactions may be lost if the principal suddenly fails and you force the mirror into service.

SQLFEST

Key points of Synchronous with automatic failover operating mode:


The transaction safety is always set to FULL The records are transferred synchronously. The client does not get a transaction committed response until the mirror server has acknowledged the principal server. Both the partners and the witness server are required to be present. The failover is automatic and manual failover is also possible. No committed transactions are lost during failover.

Key points of synchronous without automatic failover operating mode:


The transaction safety is always set to FULL The records are transferred synchronously. The client does not get a transaction committed response until the mirror server has acknowledged the principal server. The quorum between witness and partners is not required Automatic failover is not possible as theres no witness server No committed transactions are lost during failover

Key points of asynchronous operating mode:


The transaction safety is always set to OFF The records are transferred asynchronously. The client gets transaction committed response as soon as the principal server has written the transaction to the log. The principal server does not wait for acknowledgement from the mirror server. Quorum is not set and the witness server is not present. During manual failover with safety OFF or FORCE_SERVICE, some transactions are lost during failover. (Generally this is never done as normally you would want to switch to full safety)

Client Redirection:
Client redirection is one of the most difficult process with other H/A technology, applications connecting to the Principal database must also be able to handle the connections during the failover of the Principal server to the Mirror server. This has always been a problem with Log shipping and Replication but Database Mirroring can handle this very nicely. The new data access provider (MDAC) contains a connection object called Transparent Client Redirect. This object allows the caching of both the Principal and the Mirror server name. This process of caching is transparent and developers do not need to implement any code to implement this functionality. If an active connection to the principal database fails for any reason, for example, due to a database mirroring failover, and the application attempts to reconnect to the same principal

Page | 12

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

server, the data access provider (MDAC) 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.

SQLFEST

Note:
SQL 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.

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.

ENDPOINTS: Communication Mechanism for Database Mirroring


Just to make it simple consider mirroring endpoints as a telephone which is used by 2 or more parties for communicating with each other. You use a specific telephone number to connect to the remote party and same can be considered in the mirroring session where in order to communicate with each other all the servers involved in database mirroring use TCP endpoints to communicate with each other on a specific TCP port. Before establishing a database mirroring session, you must configure to establish the communication mechanism between all the servers participating in database mirroring. This communication can be accomplished by creating endpoints on all the servers which controls the transmission control protocol (TCP) port to listen on. Database Mirroring endpoints use TCP protocol to send and receive messages between the server instances in database mirroring sessions. Each database mirroring endpoint listens on a unique TCP port number. The database mirroring endpoint of a server instance controls the port on which that instance listens for database mirroring messages from other server instances. Note: All mirroring connections on a server instance use a single database mirroring endpoint.

Page | 13

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Below picture shows how database mirroring communicates with servers using TCP Port.
r_3 rve s) Se itnes (W

SQLFEST
Mirroring Endpoint TCP Port: 5001

r_1 rve al) Se i n ci p (Pr

r_ 2 rve ) Se irror (M

int po nd 1 g E : 500 rin ort rro Mi C P P T

Mi TCrrorin PP gE ort nd : 5 po 00 int 1

Note:
1) If your server has multiple instances of SQL Server participating in mirroring sessions, each instance requires its own endpoint, configured with unique TCP port. 2) Client connections to the principal server do not use database mirroring endpoint. Instead they use any of the available protocols using SQL network library which could either be TCPIP, Named Pipes, Shared Memory, VIA.

Understanding different types of failovers/Role Switching


Failover (aka. Role switching) involves transferring the role of a principal database to a mirror database role and vice-versa. In role switching, the mirror server acts as the failover partner for the principal server. When a failover 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. As can be seen from the below picture Server_1 acts as a Principal server before the role switch is done and after the role switch it becomes the mirror server and the former mirror server becomes the principal server and the logs are transferred the other way round. Before failover Before switching the mirror role Server_1 is the principal server and server_2 is the Mirror server. After failover After switching the role Server_2 becomes the principal server and Server_1 becomes the mirror server.

Page | 14

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
P M

Server_1

Server_2

Server_1

Server_2

There are three forms of role switching that exist with Database Mirroring: 1) Automatic Failover 2) Manual Failover 3) Forced Failover (Rarely done)

Automatic failover
Automatic failover can occur whenever either of the partner becomes unavailable. This requires mirroring to be in high-availability mode (safety=full) meaning you must have a Principal, mirror and a witness server configured. Also, for a successful automatic failover 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 as the connection from witness to principal server is fine.

Key points to remember for automatic failover:


Automatic failover requires witness server and transaction safety must be set to full Automatic failover will be initiated only when the failure happens and when the partners are fully synchronized and both the partners and the witness are connected. Automatic failover could occur if the acting principal SQL Server shuts down or is rebooted or if the network connectivity is lost Automatic failover could occur for any unplanned events caused by Hardware/software errors.

Behind the scenes of Automatic failover:


Several things happen behind the scenes whenever a failover occurs as listed below:

What happens during automatic failover:


Step1: All the client connections are terminated and the principal database state changes to DISCONNECTED Step2: As theres a quorum between both the participants and the witness, both mirror and the witness will detect the failure of principal database. Step3: As the mirror database is in NORECOVERY mode, all the logs from the queue of the

Page | 15

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
principal server is applied on the mirror database to completely recover it. Step4: Once the log is fully recovered, it checks with the witness and decides that the database should now failover to the mirror. This usually takes seconds (based on your network and system performance) and if the principal database comes back before the mirror is fully recovered then failover is automatically cancelled. Step5: After all the above steps are performed, the mirror database is brought online and it assumes the role of the principal. The database is now available and clients can connect to the new principal and continue operation. Once the former Principal comes back up, it finds out that its partner is now performing the principal role, it will take on the role of the mirror server and will synchronize the database quickly as possible and once it is ready to serve as mirror, failover is again possible, but in the reverse direction.

Manual failover
You can manually perform failover from principal to mirror and vice-versa during planned maintenance like applying service packs or hotfix, rebooting the box, etc. Manual failover requires SAFETY=FULL and can only be done if the operating mode is set to either High Availability or High Protection mode and the partners must be connected to each other, and the database must already be synchronized.

Forced failover (with possible data loss)


Forced failover is strictly a disaster recovery method. Forcing failover may involve some data loss. Therefore, you should use this type of failover only if you are willing to risk losing some data in order to bring up the mirror database immediately. Forced Failover (with possible data loss) allows you to use mirror server as a warm standby server. This is only possible if the principal server is disconnected from the mirror server in a mirroring session. 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

Page | 16

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

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). You must perform this type of failover with extra care and must use this type of failover only if you must restore service to the database immediately and are willing to risk losing data. The effect of forcing failover is similar to removing mirroring, except that forcing failover facilitates re-synchronizing 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). Note: 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, once the new principal database comes online, the client applications can recover quickly by reconnecting to the database.

SQLFEST

Pre-requisites for setting up Database Mirroring:


Setting up database mirroring is easy and simple if you plan ahead and collect all the required information before you start setting up database mirroring in your environment, just for your ease we are providing you with the following checklist:

1) 2) 3) 4) 5) 6) 7) 8) 9)

Name of the Principal Server Name of the Mirror Server Name of the Witness Server Mirroring endpoint name for Principal server Mirroring endpoint name for Mirror server Mirroring endpoint name for Witness server Endpoint Port number for Principal server Endpoint Port number for Mirror server Endpoint Port number for Witness server Operating mode Safety Mode Principal server domain name Mirror server domain name Witness server domain name Name of the database to be mirrored Have you created exact partitions on the mirror server? Location where backups are stored?

Page | 17

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Was latest SQL Server Service pack applied? Location of the scripts for database mirroring? Did you copy all jobs, logins, SSIS packages, server configuration from Principal server to the mirror server? Fully qualified server name for Principal Fully qualified server name for Mirror Fully qualified server name for Witness Have you performed full and log database backups of the principal server?

Once you have the above checklist fully covered you are almost ready for setting up database mirroring: Keep the following points in mind before you start setting up database mirroring: 1. Make sure that both principal and mirror are running on the same edition of Microsoft SQL Server 2005, they can either be standard edition or enterprise edition. 2. Make sure Microsoft SQL Server 2005 (any edition) is installed on the witness server. The witness server can run on any reliable computer system that can support SQL Server 2005.

3. Make sure that the mirror server has the exact same jobs, logins, SSIS packages, disk partitions, disk space, server configuration, etc (This is very important) 4. Make sure that all the databases participating in Database Mirroring are set to FULL recovery model. 5. If possible, the path (including the drive letter) of the mirror database should be identical to the path of the principal database. If the file layouts must differ, for example if the principal database is on drive F: but the mirror system lacks an F: drive, you must include the move option in the RESTORE statement. 6. All of the server instances in a mirroring session should use the same master code page and collation. Having different collation/code-page can cause problems during database mirroring setup. 7. For best performance, use a dedicated network interface card (NIC) for database mirroring.

Page | 18

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

8. Configure the mirror server with the server settings exactly as the principal server was configured. You may do this by running and comparing the output of Exec SP_Configure system stored procedure on both principal and mirror servers. Just to get an idea of what we are going to do, let me help you understand the mirror setup process and steps; You can use these steps at any time to setup database mirroring on any server). With the steps below you will find how easy it is to setup database mirroring in your environment. If you keep in mind that database mirroring is very tough then yes it is very tough and you cant do it but take my word it is the most simplest H/A technology that can be configured very easily and is very simple to understand.

SQLFEST

Database mirroring setup flow:


Setting up database mirroring is a very easy process if you know exactly what steps you need to perform and just to make your life easy, I have provided the below setup process steps for you to follow in order to setup database mirroring in your environment. Step1: Create mirroring endpoints on principal, mirror and witness server instances. Step2: Perform a full and log backup of the principal database and restore it on the mirror server instance using NORECOVERY option Step3: Start the mirroring session on principal, mirror and witness server instances. Once you follow the above setup process you will be able to setup database mirroring in your environment in not much time.

Page | 19

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Database Mirroring Setup Flow
Create Endpoint on Principal Server Create Endpoint on Mirror Server Create Endpoint on Witness Server

n Pri

ci p

al

Mi

rro

P
Perform FULL database backup of Principal database and restore it on Mirror server

Enable Mirroring Sessions on all the servers

W
Principal Server Witness Server Mirror Server

Easy to understand Database Mirroring Setup Flow

Setting up Database Mirroring using T-SQL


Once you have met the all the pre-requisites as mentioned in the earlier topic and have understood the setup flow you are now ready to proceed with setting up database mirroring in your environment. Make sure that you have confirmed and checked all the items from the checklist provided in the earlier topic before you configure database mirroring, example: Server names, Port Numbers, security accounts, location where databases would reside (especially mirror). Once you have all the information ready you are not very far from configuring Database Mirroring.

Page | 20

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Now lets take a look at how easy it is to setup database mirroring and just for the sake of simplicity we will take an example of 3 easy to remember server names: Role Principal Mirror Witness Server Name ServerA ServerB ServerC Database Name DBM_Demo DBM_Demo Not applicable

I recommend that you configure Database Mirroring during off-peak hours because configuration can sometimes impact performance as it has to copy the pending transaction log from principal server to mirror server depending upon the volume of log. Step 1 Action Alter the principal database to use FULL recovery model if it is not already set to use FULL recovery model. Database Mirroring will not work on any other recovery model as it has to copy the transaction log from principal to mirror database server. T-SQL Statement for configuring the database to use FULL recovery model: -- Please run the below command on the ServerA (principal server) Use Master; Alter Database DBM_Demo Set Recovery FULL; 2 Create an endpoint on ServerA, ServerB, & ServerC servers. (For more information about endpoint read the topic Communication Mechanism for Database Mirroring (ENDPOINTS) mentioned in previous topic. T-SQL statement for creating an endpoint on ServerA (principal server): Use Master; Create Endpoint Mirroring_Endpoint State= Started as TCP (Listener_Port=5001) For Database_Mirroring (Role=Partner);

T-SQL statement for creating an endpoint on ServerB (mirror server): Use Master;

Page | 21

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Create Endpoint Mirroring_Endpoint State=Started as TCP (Listener_Port=5001) For Database_Mirroring (Role=Partner); T-SQL statement for creating an endpoint on ServerC (witness server): Use Master; Create Endpoint Mirroring_Endpoint State=Started as TCP (Listener_Port=5001) For Database_Mirroring (Role=Witness); 3 This is the time when you will perform a full database backup followed by a log backup of DBM_Demo database (principal database) from ServerA server. Please note: When restoring both Full backup and the Log backup of DBM_Demo database you will need to restore them using NORECOVERY option as mentioned in the pre-requisite section earlier.

T-SQL statement to perform a FULL database backup of DBM_Demo database from ServerA: Use Master; Backup Database DBM_Demo to DISK=E:\MSSQL\Bak\DBM_Demo_FULL.bak; If there are any changes to the database since you performed the FULL database backup, you may have to perform Log backup of the database, else it may not be required. T-SQL statement to perform LOG backup of DBM_Demo database from ServerA: Use Master; Backup Log DBM_Demo to Disk=E:\MSSQL\Bak\DBM_Demo_Log.bak; Once you have all the backups performed move the backup files to ServerB (mirror server) or to a shared location so that you can restore these backups on ServerB

Page | 22

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
server. 4 Restore the backups that you had taken in the previous step on ServerB server. You must follow the recommendations for restoring the databases on ServerB server: (Using NORECOVERY option assures that the mirror database will be in the Restoring state so that the transaction logs can be applied) T-SQL statement to restore the full backup on ServerB server using NORECOVERY option: Use Master; Restore Database DBM_Demo from Disk=E:\MSSQL\Bak\DBM_Demo_FULL.bak with NORECOVERY; Once you have restored the full backup on ServerB server you should now restore any T-Log backups that you had taken since the last FULL database backup from ServerA server: T-SQL statement to restore the Log backup on the mirror server using NORECOVERY option: Use Master; Restore Log DBM_Demo from Disk=E:\MSSQL\Bak\DBM_Demo_Log.bak with NORECOVERY; Go 5 Once you have restored all the backups you are now ready to perform the final step and that is to enable your database mirroring session on all the servers participating in database mirroring. Setting up a database mirroring session requires a server network address for each of the server instances. The server network address of a server instance must identify the instance by providing a system address and the port number on which the instance is listening.

The syntax for a server network address is as follows: TCP://<System-address>:<port> <System-address>: is a fully qualified domain name or an IP address: you can get

Page | 23

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
this information by executing IPCONFIG on the local machine from DOS prompt. <Port> : is the one that you created in step two when creating endpoints. You can use the following T-SQL statement to identify the port number from the configured TCP endpoints: Use Master; Select Type_Desc, Port from Sys.Tcp_EndPoints; You may also use the IP address for partner instead of the system address. You can use both IPv4 and IPv6. T-SQL for starting database mirroring session on the ServerB server: Use Master; Alter Database DBM_Demo Set Partner= TCP://ServerA.com:5001; Now run the following T-SQL for starting the database mirroring session on the ServerA server: Use Master; Alter Database DBM_Demo Set Partner=TCP://ServerB.com:5001; Once you have started the mirroring session on both ServerA and ServerB servers you now have to enable mirroring session on ServerC (witness) server: T-SQL for starting database mirroring session on ServerC (witness) server: Alter Database DBM_Demo Set Partner=TCP://ServerC.com:5001; Go Database Mirroring is now ready in your environment. Any database objects that have been added or modified on DBM_Demo database will be transferred to the ServerB copy. If ServerA database becomes unavailable, a failover can occur, changing the mirrored databases role to the principal role.

Page | 24

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

The above example is assuming that all the three servers are connected to the same domain and are using the same domain account. In case if the domain account for any of the server is different for example the domain account for ServerB (mirror) server is different than the domain account of the ServerA (principal) or ServerC (witness) server then you can use the following statement to grant permissions on the endpoint to that domain account: (You will need to run the below statement on all the three servers participating in mirroring session) Use Master; Create Login [Domain\Domain_user_account] From Windows; Grant Connect on EndPoint ::Mirroring_Endpoint to [Domain\Domain_user_account]; Once you have setup database mirroring successfully in your environment you can view the state of partners by querying the system catalog called sys.database_mirroring which is explained in next topic. For setting up database mirroring using SQL Server management studio, please visit MSPress website for a live demo.

SQLFEST

Viewing the database mirroring state:


Once Database mirroring is setup, you can view the state of database mirroring by querying Database_Mirroring system table in master database Use Master; Go Select * from sys.Database_Mirroring; Go Now look at the state column in the result state, this should show you the current state of your database. Following table states what each database mirroring state means: States <blank> Explanation No database mirroring session exists and there is no activity to report on the Mirroring page. The principal database is running but is not sending any logs to the mirror server. The mirror copy of the database is not available.

Paused

Page | 25

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
No connection The principal server instance cannot connect to its partner or to the witness server instance (if any) The contents of the mirror database are lagging behind the contents of the principal database. The principal server instance is sending log records to the mirror server instance, which is applying the changes to the mirror database to roll it forward. At the start of a database mirroring session, the mirror and principal databases are in the synchronizing state. Failover On the principal server instance, a manual failover (role swap) has begun but has not yet accepted by the mirror. The mirror database contains the same data as the principal database. Manual and automatic failover are possible only in the synchronized state. Synchronizing

Synchronized

Monitoring database mirroring


With the release of SQL Server 2005 SP1, Microsoft introduced Database Mirroring monitor to help monitor how well the data is flowing in the database mirroring session and it also can be very useful for troubleshooting the cause of reduced data flow from principal to mirror. Database Mirroring Monitor is available only with SQL Server 2005 Standard and SQL Server 2005 Enterprise editions. You can register any of your mirrored databases for monitoring each of the failover partners individually. When you register a database in Database Mirroring monitor, it caches the following information about the database that is being mirrored: Database Name Names of both Principal and Mirror servers The last known roles of each partner (Principal or Mirror) Also, with SP1 a new database role is introduced in MSDB database called dbm_monitor which can be used to grant access to users/operators/DBAs to access Database Mirroring Monitor for the local server and not the other partners. You must be a member of dbm_monitor database role in MSDB of all the servers if you want to monitor both Principal and Mirror databases. Note: sysadmin server role has full permissions to everything in SQL Server.

Page | 26

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Important: The dbm_monitor fixed database role is created in the MSDB database only when the first database is registered in database mirroring monitor. The new dbm_monitor role will not have any users unless you (sysadmin) assigns users to this role. Database Mirroring Monitor refreshes automatically @ every 30 seconds, alternatively you can click on the refresh button to refresh the screen.

How to launch database mirroring monitor:


1) After connecting to the principal server instance, in Object Explorer, click the server name to expand the server tree. 2) Expand Databases, and select the database to be monitored. 3) Right-click the database, select Tasks, and then click Launch Database Mirroring Monitor. 4) In the Database Mirroring Monitor dialog box, click Register Mirrored Database to register one or more mirrored database. Database Mirroring Monitor will now be launched and you can click on Register Mirrored database option from the right pane to register the database to monitor. Once the database is registered you should see a screen similar to the below: Note: You just have to register either Principal or the Mirror server and database mirroring monitor will automatically register the associated partner.

Page | 27

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST

Some of the features you might like about database mirroring monitor are: You can monitor the current status of each server You can monitor the latency You can view the warnings and the history of each transaction You can configure performance thresholds, etc. Also, the main database mirroring monitor page shows the below information: Feature Mirror Commit Overhead Description Number of milliseconds of average delay per transaction tolerated before a warning is generated on the principal server. This delay is the amount of overhead incurred while the principal server instance waits for the mirror server instance to write the transaction's log record into the redo queue. This value is relevant only in high-safety mode. The amount of log waiting in the send queue (in kilobytes).

Unsent Log from Principal Server

Page | 28

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Un-restored log from Mirror Server Current send rate and restore rate of the log Current rate of new transactions The amount of log waiting in the redo queue (in KB). Rate at which transactions are being sent from Principal and restored to the mirror server instance in kilobytes (KB) per second. Rate at which incoming transactions are being entered into the principal's log in KB per second. To determine whether mirroring is falling behind, staying up, or catching up, compare this value to the Estimated time to send log value. Will contain the current state of Database Mirroring session (ex: Unknown, synchronizing, Synchronized, Suspended, Disconnected) Will contain the current operating mode of the Database Mirroring session (Ex: High Availability (Synchronous), High Protection (Synchronous), High Performance (Asynchronous) History of each transactions occurred since the last 2 days (this can be very helpful when troubleshooting) You can view any warnings that have been generated for Database Mirroring session

State of the database

Operating Mode

Transaction History

Warnings

Setting up database mirroring thresholds


It is recommended that you setup threshold in the production environment for key performance metrics. Also, when setting up a threshold you must set it up both on the principal and on the mirror server to make sure that the warnings and thresholds persists if the database fails over. There are 3 ways you can setup warning thresholds for database mirroring: 1) Using Database Mirroring Monitor 2) Using System Stored Procedure & 3) Using SQL Server Performance Monitor

Page | 29

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Setup thresholds using Database Mirroring Monitor:
1) From the Database mirroring monitor select warnings tab from the right pane after you register the server 2) Click on Set Thresholds button on the Warnings page. (You will see the threshold page similar to the one below) 3) You can now check the boxes for which you want to setup warning threshold (Please do not forget to check the same thresholds for the mirror server as well so that you continue to receive performance related alerts even if the principal fails and mirror takes over.

Note: When a threshold exceeds its limit, an event is logged in the NT application log.

Setup thresholds using system stored procedures:


You can setup thresholds for monitoring database mirroring using the following system stored procedure. This can come handy when you are writing a process which can consume heavy resources and you want to execute that process based on the performance of database mirroring: The following set of system stored procedures enable an administrator to set up and manage warning thresholds on mirrored databases of one partner at a time.

Page | 30

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
System Stored Procedure Description sp_dbmmonitorchangealert (Transact-SQL) Adds or changes warning threshold for a specific mirroring performance metric. sp_dbmmonitorhelpalert (Transact-SQL) Returns information about warning thresholds on one or several key database mirroring monitor performance metrics. sp_dbmmonitordropalert (Transact-SQL) Drops the warning for a specified performance metric.

Example for sp_dbmmonitorchangealert:


Syntax: Exec sp_dbmmonitorchangealert <database_name>, ,alert_id ,alert_threshold ,enabled The following example sets thresholds for each of the performance metrics and the retention period for DBM_Demo database. Following table shows values used in the below examples:

Alert_id Performance metric 1 Oldest unsent transaction 2 3 4 5 Unsent log Unrestored log Mirror commit overhead Retention period

Warning threshold 30 minutes 10,000 KB 10,000 KB 1,000 milliseconds 8 hours

Is the warning enabled? Yes Yes Yes No Yes

Use Master; EXEC sp_dbmmonitorchangealert DBM_Demo, 1, 30, 1 ; --Oldest unsent transaction EXEC sp_dbmmonitorchangealert DBM_Demo, 2, 10000, 1 ; --Unsent log EXEC sp_dbmmonitorchangealert DBM_Demo, 3, 10000, 1 ; --Unrestored log EXEC sp_dbmmonitorchangealert DBM_Demo, 4, 1000, 0 ; --Mirror commit overhead EXEC sp_dbmmonitorchangealert DBM_Demo, 5, 8, 1 ; --Retention Period Note: When a threshold exceeds an event is logged in the application event log.

Page | 31

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Querying the status of performance metrics:
You may use sp_dbmmonitorresults to get a status for monitored database from the status table in which mirroring monitoring history is stored and allows you to choose whether the procedure obtains the latest status beforehand. This procedure accepts three parameters: 1) 2) 3) Database Name (Specify the database to query the mirroring status for) Rows to return (Specify the quantity of rows to return) Update Status (Specify to update the values before returning the result set. Rows to return can be: Rows to return code 0 1 2 3 4 5 6 7 8 9 Update status value can be: Update Status Value 0 Description Does not update the status for the database. The results are computed using just the last two rows, the age of which depends on when the status table was refreshed. Updates the status for the database by calling sp_dbbmonitorupdate before computing the results. However, if the status table has been updated within the previous 15 seconds, or the user is not a member of the sysadmin fixed server role, sp_dbmmonitorresults runs without updating the status. Returns Last Row Rows from last two hours Rows from last four hours Rows from last eight hours Rows from Last day Rows from last two days Last 100 rows Last 500 rows Last 1000 rows Last 1,000,000 rows

Page | 32

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Example: This example shows the rows recorded since the last 2 days for DBM_Demo database and it also updates the status of the database before the result set is displayed: Use MSDB; Exec sp_dbmmonitorresults DBM_Demo, 5, 1; There are also other procedures that can help you query other pieces of information for database mirroring monitor: System Stored Procedure sp_dbmmonitorhelpalert Sp_dbmmonitordropalert Purpose Returns information about warning thresholds Drops the warning for a specific performance metric

SQLFEST

Database Mirroring Maintenance and Operations


In this topic we will see the different mirroring operations/maintenance tasks you may have to perform with the database mirroring sessions.

Changing Modes and Transaction Safety using T-SQL


By default, the previous setup example we have seen operates in synchronous mode (i.e. SAFETY is set to FULL and is operating in High-Availability mode). You can change the operating mode of a mirror session by using the ALTER DATABASE statement with the SET PARTNER SAFETY clause on either partner server. Lets see what happens when the safety mode or the operating mode is changed. The behavior of high-safety mode depends partly on the witness as follows: When safety is set to FULL and a witness is configured: (High Availability) The session runs in synchronous mode with automatic failover. When the principal server is lost, the session automatically fails over to the mirror server if the database is synchronized and the mirror server instance and witness are still connected to each other (that is, they have quorum). When safety is set to FULL and the witness is set to OFF: (High Protection) The session runs in synchronous mode without automatic failover. If the mirror server instance goes down, the principal server instance is unaffected but if the principal server instance goes down, you can do a manual failover to the mirror server instance. When Safety is set to OFF: (High Performance) The session runs in asynchronous mode, and automatic failover and manual failover is not supported. However, problems on the mirror do not affect the principal, and if the principal

Page | 33

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

server instance goes down, you can, if necessary, force service (with possible data loss) to the mirror server instance. Turning off transaction safety shifts the session in to asynchronous operating mode, which maximizes performance but minimizes availability. If for any reason the principal database becomes unavailable, the mirror stops but is available as a warm standby (Failover requires forcing service with possible data loss). Important: Asynchronous (high-performance) operating mode is not intended to use a witness server. However, whenever you set SAFETY to OFF, we strongly recommend that you ensure that WITNESS is set to OFF. Also, if you plan to use high-safety mode with automatic failover, the normal load on each of the failover partners should use less than 50 percent of the CPU. If your work load overloads the CPU, a failover partner might not be able to ping the other server instances in the mirroring session, resulting in a unnecessary failover. If you are unable to keep the CPU usage below 50 percent, we recommend using either high-safety mode without automatic failover or high performance mode. Now, lets look at how we can make changes to the operating mode using T-SQL: Assume you would like to set the database mirroring to be asynchronous instead of synchronous. (i.e. to use SAFETY=OFF) To set the safety off that is to change the operating mode from synchronous (high availability) to asynchronous (high performance) mode, use the following T-SQL statement from principal database instance. (Note: You will also need to turn off witness when turning off HIGH-SAFETY. Use Master; Alter Database <Database_Name> Set Partner SAFETY OFF; Go To set the safety back to synchronous (i.e. SAFETY=FULL) execute the following statement from Principal database: Use Master; Alter Database <Database_Name> Set Partner SAFETY FULL; Go

SQLFEST

Page | 34

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
To remove the witness use the following T-SQL statement from Principal database: Use Master; Alter Database <Database_Name> Set WITNESS OFF; To add a witness to support automatic failover, use the below statement from Principal database: If you have to add a witness back you must make sure that the database mirroring endpoint exists on the witness server instance and if it doesnt exists than you must create the endpoint before adding the witness to database mirroring partners. Following example assumes you have an endpoint called Database_Mirroring created on the witness server ServerC: Use Master; ALTER DATABASE <Database_Name> SET WITNESS = 'TCP://<Server_Network_Name>:<Port_number>'

Steps to take when rebooting, applying hot fixes or service packs


There may be times when you may have to perform maintenance on your principal SQL Server instance due to Service pack installation, reboots, etc and yet would like to continue providing availability to your servers, so lets see how you can achieve high availability and yet perform all the required maintenance tasks for a short period of time. If you have configured database mirroring in synchronous with or without automatic failover mode, you can switch to the mirror server instance and make it available to the clients while you perform hardware or software maintenance on the principal server instance. So lets see how we can do this: Step1: Always perform the maintenance on your mirror server instance first. You may perform reboots, install service packs, etc even without touching the principal server instance and once you are done performing maintenance on the mirror server instance you should make sure that the mirroring state on the principal server instance becomes SYNCHRONIZED Step2: Once you confirm that the mirroring state has become SYNCHRONIZED on the principal server instance, perform an manual failover from the principal server instance to

Page | 35

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

mirror server instance by running the Alter Database Failover statement from the Principal server instance: Use Master; Alter Database <Database_Name> SET PARTNER FAILOVER; Above statement will perform a failover from your principal server instance to the mirror server instance, during this failover all the users connected to the principal server instance will be disconnected and any new users connecting to the database will be auto-redirected to the mirror server. It is recommended that you stop the application for a brief moment of manual failover and restart after the failover succeeds. In this case, you will need to point your application to the new principal database server. You can now perform the hardware and software changes on the old principal server. As soon as you are done with the change and the database becomes available, it automatically re-establishes the mirroring session and assumes the role of the mirror.

SQLFEST

Q) How do you check if the database is a principal database or not?


A) You can query Sys.Databases object from the master database to view the status of the database. Use Master; Select Name, Mirroring_Role_Desc from Sys.Databases where Name-DBName; If the server instance is the principal, the value of Mirroring_Role_Desc column will be Principal else it will be Mirror

Step3: If you have a witness configured you can now perform the same maintenance on the witness server without affecting the database mirroring session.

Changing the default auto-failover timeout value


The default timeout for communication between principal, mirror & a witness is 10 seconds. Meaning if any of the partners are not ping-able for 10 seconds it can throw a timeout message and the database can failover.

Page | 36

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Note: There are several other errors @ the O/S level that can cause failures and some of them are: Network errors I/O errors Process errors, etc. You can make changes to the default timeout setting by configuring the partner timeout value as shown in the following T-SQL statement: Use Master; ALTER DATABASE <Database_Name> Set Partner TIMEOUT <number of seconds>; Note: To keep a connection open, a server instance must receive a ping on that connection within the time-out period defined by the mirroring time-out value, plus the time 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. In asynchronous sessions, the default time-out value of 10 seconds cannot be changed. In synchronous sessions, however, you can control the time-out period. We recommend that you keep the time-out value at 10 seconds or greater, to avoid false failures.

Performing Manual Failover


When the mirrored database is synchronized (that is, when the database is in the SYNCHRONIZED state), the database owner can initiate manual failover to the mirror server. During a manual failover, the principal and mirror server roles are swapped for the database on which the failover occurs. The mirror database becomes the principal database and the principal database becomes the mirror. Server ServerA ServerB Before failover PRINCIPAL MIRROR After failover MIRROR PRINCIPAL

Note that the server roles for other database mirroring sessions are not affected

Page | 37

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Performing manual failover using SQL Server Management Studio:


Steps for manually failing over database mirroring from SQL Server management studio. From the object explorer in SQL Server Management studio: 1) Expand Databases and select the database that you would like to failover to mirror. 2) Right click on the database and select All Tasks and select Mirror from within All Tasks. 3) From the buttons on the right side Click on Failover it will than prompt you for a confirmation and once confirmed database mirroring has failed over. Alternatively, you can use the following T-SQL statement to perform a manual failover of your database: (Below statement must be used from the Principal server) Use Master; Alter Database <Database_Name> SET PARTNER FAILOVER; Where <Database_Name> is the name of the database being mirrored The above statement initiates an immediate transition of the principal database to the mirror server. Once the database is successfully failed over to mirror server instance, it will now become the principal for all the clients and the clients connected to the old principal server are disconnected and the in-flight transactions are rolled back.

SQLFEST

Performing forced failover


When the database mirroring is set asynchronous (high-performance) mode (Safety=OFF, Witness=OFF) and if the principal server instance goes down you will need to perform a forced failover to the mirror server instance using the below statement. You will need to execute the below statement from the mirror server instance: Use Master; Go ALTER DATABASE <Database_Name> SET PARTNER FORCE_SERVICE_ALLOW_DATA_LOSS; Go <Database_Name> is the database name of the mirrored database.

Page | 38

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Once the above statement is issued, the mirror server immediately transitions to principal server, and mirroring is suspended because the principal server is not available but if the old principal server (the one that had crashed) becomes available will act as a mirror server after being recovered and will establish connection with the current principal server but the mirroring session will be suspended. You can use the following statement on the mirror server to resume database mirroring session: Use Master; Go ALTER DATABASE <Database_Name> SET PARTNER RESUME; Go 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.

SQLFEST

Setting up database mirroring on low-bandwidth networks / modems


Rule of thumb: You must configure database mirroring in high-bandwidth network only. For low bandwidth networks meaning lesser then the 10 mega-bits per second or by using modem (56 kbps or 33 kbps), throughput and response time degrades drastically. But if you have no other option other than to set it up on low bandwidth networks than you must not use synchronizing / high availability mode as it may just be too slow or may just freeze up your connection and this completely depends upon your business requirements and resources & budgets allocated for the project.

Page | 39

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

The network bandwidth recommendation is completely based on the log generation rate of your application as setting up database mirroring in lower bandwidth networks can adversely impact the performance of database mirroring. Therefore, we highly recommend that you test your environment and the log generation rate and based on that make the decision. Our recommendation is to use high network bandwidth for database mirroring. You must always make sure both in high and low bandwidth network that your network bandwidth is significantly more than the log generation rate of your application. Otherwise, Database Mirroring performance will be a major bottleneck for your application environment.

SQLFEST

Setting up database mirroring on a local area network


Since its local area network and the network latency is low you may setup database mirroring in high-availability (synchronous) mode with a witness for automatic failover. Within a reliable LAN, synchronous mirroring with a witness is recommended if availability is of higher importance than performance. However, if performance is of high importance, asynchronous mirroring is preferred. You need to make this design tradeoff based on the performance and availability requirements of your application and the performance impact of synchronous mirroring on your application.

Geo-redundancy with Database mirroring


You can setup database mirroring in Metropolitan Area Network or Wide Area Network primarily as a disaster-recovery solution. Several companies have lost their precious data during Katrina and Tsunamis, therefore its always a good idea to think ahead and setup your database mirroring environment with geo-redundancy. You must also decide whats important for you, is it the data or the availability if its the availability than you will need to have powerful network backbone to be able to communicate with all the mirroring participants. Generally, in MAN and WAN environments roundtrip times ranges between 2 to 300 millisecond (based on your internet bandwidth)

Cloud Cloud

2 300 milliseconds roundtrip

Skyscraper

New York Seattle

Page | 40

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Environment Local area network Metropolitan area network Wide area network Typical roundtrip times (RTT) in milliseconds (ms) 0 to 2 2 to 20 20 to 300 If the network latency between the principal and mirror server is >=2 milliseconds you must evaluate the performance with respect to the performance goals of your application and business requirements and only then you can determine if synchronous mirroring is the right choice for your environment. Also, with high network latency, the log send queue on the principal server can build up significantly under heavy workload, which may result in longer failover time and increased transaction loss in the event of a failover.

Keep the following points in mind:


If roundtrip <=2 then you can setup synchronous database mirroring If roundtrip >=3 then you can setup asynchronous database mirroring

Preparing the Mirror Server for Failover


You must perform failover tests in your test environment or in the production environment before going live with your application or before setting expectations for your production environment. In the event of a failover, you must make sure that the mirror database is ready to take up the full workload of the principal database. Therefore, you must use identical servers (in terms of CPU, memory, storage, and network capacity) as principal and mirror partners.

Best practices recommendations are to use:


Identical partner servers (in terms of CPU, memory, storage, network capacity). The same service pack and patch levels for the operating system and SQL Server on both partners. When performing rolling upgrades, the service pack and patch levels can be temporarily different on the principal and the mirror. However, for steady state operations, they should be identical. The same edition of SQL Server on both partners. An identical directory structure for the SQL Server install and database files on both partners.

Page | 41

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

The same SQL Server configuration (trace flags, startup options, memory settings, etc.) for the principal and mirror instances. If the principal and mirror servers are not identical in terms of CPU, memory, storage, and network capacity, you might experience undesirable performance when you fail over. Using the same edition of SQL Server, and the same version and service pack level of SQL Server and the operating system on both the partners minimizes the risks of encountering SQL Server or operating system issues. Ensuring that both servers have the same directory structure, same disk partitioning scheme, and SQL Server configuration eliminates the need for changes to these during or after the failover to the mirror partner. The granularity of database mirroring is a single database. Each database in an instance of SQL Server is mirrored independently. The entire instance is not mirrored. For full instance failover capabilities (not database level), consider failover clustering. Moreover, only user databases can be mirrored. You cannot mirror the Master, MSDB, TempDB, or Model databases. Therefore, you need to perform some administrative tasks to prepare the mirror server to take over the role of principal in the event of a failover. Several considerations apply to the mirror server:

SQLFEST

Make sure that applications can connect and execute all necessary actions, and that all active SQL Server logins (and their permissions) on the principal server are also present on the mirror server. You can use the Transfer Logins task of SQL Server 2005 Integration Services to accomplish this. (For details on the Transfer Logins task, see SQL Server 2005 Books Online.) Copy the SQL Agent jobs, alerts, SSIS packages, support databases, linked server definitions, backup devices, maintenance plans, database mail profiles, etc. from the principal server to the mirror server. The jobs on the mirror server are typically disabled. Make sure to enable them in the event of a failover. If you add a disk volume on the principal partner on which you plan to put data or log files for the database that is being mirrored, add a disk volume with the same drive letter on the mirror server as well. Otherwise, when you add a data file on the new drive on the principal server, database mirroring tries to add the same file on the mirror database server and will fail because the new drive doesnt exist on the mirror server. Have a process in place so that when you make any changes (such as changes to hardware, software, SQL Server settings, or any database support objects) to the principal, you repeat or transfer the changes on the mirror server. Test server failover and make sure that all objects, logins, permissions, etc. work on the mirror the same as on the principal.

Page | 42

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Mirroring Multiple Databases
If you have more than one database that needs to be mirrored, you need to mirror each database individually. Although it is possible to choose a different mirror server for each database, it is a best practice recommendation that you make the decision based on your application and environment. Note: Mirroring can occur on 10 or so databases per server. (This again depends upon the resources available on the system) One of the problem that you might experience with multiple databases is that if in case if just one database fails over and the others dont then what happens? Lets take an example of the same environment we used for setting up database mirroring using SQL Server Management Studio, lets add one more database to the principal server called DBM_Demo_Automation, your environment would look like this: Server Name ServerA ServerA ServerB ServerB ServerC Role Principal Principal Mirror Mirror Witness Database Name DBM_Demo DBM_Demo_Automation DBM_Demo DBM_Demo_Automation N/A Endpoint Name Mirroring_Endpoint Uses same endpoint Mirroring_Endpoint Uses same endpoint Mirroring_Endpoint Port Number 5001 Same port 5001 Same port 5001

So now you have two databases that are being mirrored and if only DBM_Demo database fails-over to the mirror server instance than what happens to your application? if both the databases belong to the same application your application will be not function properly as one of the database is on a separate principal server instance and the other one is on a separate. Therefore, it is recommended that you think carefully before implementing mirroring on multiple databases. It is recommended that if you have multiple databases and multiple applications connecting to them than its a good practice to have a separate mirror server instance for each of the database.

Tip: If you have one Application with multiple databases then choose one mirror server for all the databases that belong to the same application.

Page | 43

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
If you have multiple databases for different applications, then you can choose different mirror servers for them, but doing so adds complexity & maintenance to the configuration. In the event of the failure of the SQL Server service or the server or network, both databases will fail over in approximately the same time. However, what happens if one database experiences a disk failure? In that case, only that database fails over. Or, if the network is experiencing sporadic issues and the mirroring session of one database times out, but the other databases do not, one database might fail over, but not the others. Therefore, if your application consists of multiple databases, develop an alert mechanism to detect if one database fails over while others dont. In such a situation, you must manually fail over the other databases. Based on the resource (memory and threads) utilization by database mirroring, it is a best practices recommendation to mirror not more than 10 databases in one instance. The recommended limit of 10 is only approximate and not an exact number. The limit can vary depending upon your application and workload.

Real-Life Scenarios: What happens when you lose the mirror server?
If the mirror server instance is lost, the principal continues functioning, but the mirroring state is DISCONNECTED and the principal is running exposed. Once the mirror database becomes operational, it automatically assumes the role of the mirror and starts synchronizing with the principal. For as long as the mirroring state stays DISCONNECTED, the transaction log space on the principal cannot be reused, even if you back up the transaction log. If the log file grows and reaches its maximum size limit or runs out of disk space, the complete database comes to a halt. To prevent this you have two optionseither plan for enough disk space for the transaction log to grow and bring back the mirror database before the space fills up, or break the database mirroring session.

What happens when you lose the witness server?


If the witness server instance is lost, database mirroring continues functioning without interruption, except that automatic failover is not possible. Once the witness becomes operational, it automatically joins the database mirroring session.

What happens when you lose both mirror and witness servers?
Assume you have configured database mirroring session with a witness. When the mirror is unavailable, the principal runs exposed. While the mirror is unavailable, if the witness is also lost, the principal server instance becomes isolated and cant service the clients. Even though the principal database is running, it is not available to the clients. If you attempt to connect to the database, you get the message Database <dbname> is enabled for database

Page | 44

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

mirroring, but neither the partner nor witness server instances are available: the database cannot be opened.

SQLFEST

Viewing Database Mirroring Information using T-SQL


SQL Server 2005 provides several system catalogs that can help you view the database mirroring information using T-SQL. Alternatively, you can use Database Mirroring monitor. Just so that it eases up the life of a DBA the below stored procedure can be run on either partners to obtain database mirroring related information. Alternatively, you can do that by using Database Mirroring Monitor. Below provided script can be used to query sys.database_mirroring object. It provide the following information in the result set: Mirror Database Name Current State of the database Current role of the database Current transaction safety level Endpoint string for Mirror server Name of the mirror server Endpoint string for witness server State of the witness server Connection timeout value Redo Queue and type

Create Procedure usp_DBMStatus as Set NOCOUNT on --Author: Saleem Hakani (Microsoft Corporation) --Purpose: This procedure helps you query the current state of --database mirroring environment, whos playing what role and --their safety levels, endpoint names, etc. Select db_name(database_id) as 'Mirror DB_Name', case mirroring_state When 0 then 'Suspended' When 1 then 'Disconnected from other partner' When 2 then 'Synchronizing' When 3 then 'Pending Failover' When 4 then 'Synchronized' When null then 'Database is inaccesible or is not mirrored' end as 'Mirroring_State',

Page | 45

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

case mirroring_role When 1 then 'Principal' When 2 then 'Mirror' When null then 'Database is not mirrored or is inaccessible' end as 'Mirroring_Role', case mirroring_safety_level When 0 then 'Unknown state' When 1 then 'OFF (Asynchronous)' When 2 then 'FULL (Synchronous)' When null then 'Database is not mirrored or is inaccessible' end as 'Mirror_Safety_Level', Mirroring_Partner_Name as 'Mirror_Endpoint', Mirroring_Partner_Instance as 'Mirror_ServerName', Mirroring_Witness_Name as 'Witness_Endpoint', Case Mirroring_Witness_State When 0 then 'Unknown' When 1 then 'Connected' When 2 then 'Disconnected' When null then 'Database is not mirrored or is inaccessible' End as 'Witness_State', Mirroring_Connection_Timeout as 'Failover Timeout in seconds', Mirroring_Redo_Queue, Mirroring_Redo_Queue_Type from sys.Database_mirroring where mirroring_role is not null

SQLFEST

Querying Witness Server


You can also query the witness server by using the following T-SQL statement. (Needs to be run on the witness server) Use Master; Select * from sys.database_mirroring_witnesses;

Querying Endpoint Information


You can find detailed information about the endpoints you created earlier by querying sys.database_mirroring_endpoints, sys.endpoints, sys.tcp_endpoints, etc. Below query can provide you with the following information: Endpoint Name Type of protocol being used Port number on which it communicates Current role Encryption status

Page | 46

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Type of connection Type of encryption

SQLFEST

Use Master; Select a.Name as 'Endpoint Name', a.Protocol_Desc as 'Protocol', b.port as 'Port', a.Type_Desc as 'Endpoint Payload Type', a.State_Desc as 'Mirroring State', a.Role_Desc as 'Current_Role', Case a.Is_Encryption_Enabled When 1 then 'Yes' When 0 then 'No' End as 'Is_Encryption_Enabled', a.Connection_Auth_Desc as 'Type of Connection', a.Encryption_Algorithm_Desc as 'Encryption_Type' From sys.database_mirroring_endpoints a join sys.tcp_endpoints b on a.endpoint_id=b.endpoint_id It is always a good practice to store mirroring related information in a document, just in case if you have to re-setup or troubleshoot some part of it.

Querying Mirroring Connections


Sometimes you may have to look into current mirroring connections for either troubleshooting purpose or to make sure things are working fine and one of the best way you can query SQL Mirroring connections and their state is by querying sys.dm_db_mirroring_connections DMV. You can use the below query to query the current state of database mirroring connections: Use Master; Select Connection_id, Case state When 1 then 'NEW' When 2 then 'CONNECTING' When 3 then 'CONNECTED' When 4 then 'LOGGED_IN' When 5 then 'CLOSED' End as 'Connection_State', Convert(Varchar(24),Connect_Time) as 'Connection_Time', Convert(Varchar(24),Login_Time) as 'Login_Time',

Page | 47

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Authentication_Method, Principal_Name, Remote_User_Name, Convert(Varchar(24),Last_Activity_Time) as 'Last_Activity_Time', Login_state_Desc as 'Login_State', Encryption_Algorithm_Desc as 'Encryption_Algorithm', Case Is_Send_flow_Controlled When 0 then 'Network is not busy' When 1 then 'Network is busy' end as 'Is_Network_Busy', Ltrim(str(Total_bytes_sent)) as 'Total_Bytes_Sent', Ltrim(str(Total_bytes_Received)) as 'Total_Bytes_Received', Ltrim(str(Total_Fragments_sent)) as 'Total_Message_Fragment_Sent', Ltrim(str(Total_Fragments_Received)) as 'Total_Message_Fragment_Received', Ltrim(str(Total_sends)) as 'Total_Network_Requests_Sent', Ltrim(str(Total_receives)) as 'Total_Network_Requests_Received' from sys.dm_db_mirroring_connections;

SQLFEST

Monitoring database mirroring performance


You have already seen queries in the previous topics that can be used to look for several database mirroring related information including performance, you may sometimes want to look at the performance of database mirroring by using PerfMON tool. To monitor the performance of database mirroring, SQL Server provides a System Monitor performance object (SQLServer:Database Mirroring) on each partner (principal and mirror). The Databases performance object provides some important information as well, such as throughput information (Transactions/sec counter). You may want to keep and eye on the following counters when troubleshooting any database mirroring performance related issues: What counters to use on the Principal server: Performance counter Purpose Log Bytes Sent / Sec Number of bytes sent to mirror database transaction log every second. Log Send Queue KB Transaction Delay Total kilobytes of log that hasnt been sent to mirror Delay in waiting for acknowledgement from mirror. It reports total delay for all the transactions in process at that time. You can divide this counter by Transactions/Sec counter to determine the average delay per transaction.

Page | 48

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Transactions/Sec Log bytes flushed/sec Disk Write Bytes/Sec Transactions per second for database The rate at which log records are written to the disk The rate at which the disk is being written. This counter is in the logical disk performance object. What counters to use on the Mirror Server: Performance Counter Purpose Redo Bytes/Sec Number of bytes of T-Log applied on the mirror database per second. Redo Queue KB Total kilobytes of hardened log that remain to be applied to the mirror database to roll it forward. Disk Write Bytes/Sec The rate at which the disk is being written. This counter can be found in Logical Disk performance object.

Here is a list of performance impacts of database mirroring sessions:


If repeated messages reporting that the database mirroring session is switching from active to inactive in the SQL Server error log file exist then it is likely that network problems exist. Index maintenance can generate extreme amounts of transaction log. It is suggested that the mode be changed to High Performance (Async) during such maintenance windows to minimize the effect on concurrent OLTP operation. Production performance problems while in Synchronous modes High Availability or High Protection can be attributed to mirror log IO completions if performance increases after changing to asynchronous mode (high performance). Mirror redo increases and transaction delay (when using synchronous modes) decreases during the time when a transaction log backup is being created on the principal database.

The following short list of objects will not failover to the new principal as it is stored outside of the database which is the unit of failover. For a complete list see the latest SQL Server 2005 Books Online: o o Logins Linked Servers

Page | 49

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

o o

Scheduled Jobs (via SQL Agent) Database snapshots

SQLFEST

Although, scheduled jobs will not failover, due to the fact that the database is unavailable on the mirror server instance, jobs will succeed performing no action so the best solution is to create the same job on both principal and mirror servers for the mirrored database so that it will run regardless of which server is holding the principal copy. To set this up on the mirror server instance where the database is unavailable, either failover temporarily to create the job or create a job that runs on all user databases and it will perform the action when the database is serving as the principal. Note: If any of the SQL Jobs were running when the failover occurred, the job execution will not failover to the mirror server instance. You will have to restart the job from where it stopped.

Suspending and resuming a mirroring session


There may come a time when you might consider suspending mirroring session and then later may consider resuming the mirroring session just to gain some performance (example: when performing index maintenance). The database owner can pause and later resume the mirroring session which preserves the session state while in a suspended state. This can be helpful for improving performance on the principal server during bottlenecks.

Keep the following points in mind before you suspend database mirroring session:
Log records accumulate during the suspended mode T-Logs on the principal server cannot be truncated (even backing up T-Log doesnt help) If you keep the mirroring session suspended for an extended period of time, you may fill up the log space and the principal database may come to a halt. It is recommended that you resume a paused/suspended session quickly. Note: Whenever 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 to the mirror server.

Page | 50

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Once the session is resumed, 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.

SQLFEST

How to pause/suspend a database mirroring session?


You can pause/suspend a database mirroring sessions using the following T-SQL statement: Use Master; ALTER DATABASE <DB_Name> SET PARTNER SUSPEND; Alternatively, you can use SQL Server Management studio to suspend database mirroring by following below steps: Step1: In the object explorer of the principal server expand databases Step2: Right click on the mirror database and select Tasks and then click on Mirror option which opens up Mirroring page of the Database Properties Step3: Click on the Pause button to pause the session. You will be asked for a confirmation click on Yes and the session is paused and the button caption changes to Resume How to resume a suspended database mirroring session? Once you are ready to resume the suspended/paused database mirroring session you can use the below statements to resume the session: Use Master; ALTER DATABASE <DB_Name> SET PARTNER RESUME; Important: Following a forced service, when the original principal server reconnects, mirroring is suspended. Resuming mirroring in this situation could possibly cause some data loss to the original principal server. Also, resuming database mirroring session places the mirror database in the SYNCHRONIZING state, If the safety level is FULL, the mirror catches up with the principal and the mirror database enters the SYNCHRONIZED state, At this point, failover becomes

Page | 51

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

possible. If the witness is present and ON, automatic failover is possible. In the absence of a witness, manual failover is possible. Alternate to the T-SQL resume, you can also use SQL Server Management studio to resume database mirroring session using the following steps: Step1: In the object explorer of the principal server expand databases Step2: Right click on the mirror database and select Tasks and then click on Mirror option which opens up Mirroring page of the Database Properties Step3: Click on the Resume button to resume the session. You will be asked for a confirmation click on Yes and the session is resumed and the button caption changes to Pause

SQLFEST

How to stop database mirroring session?


At any time, the database owner can manually stop a database mirroring session by removing mirroring from the database. Important: Before mirroring can be restated, any log backups taken on the principal database after mirroring was removed must all be applied to the mirror database. Following T-SQL statement will stop database mirroring session: Use Master; ALTER DATABASE <DB_Name> SET PARTNER OFF; Alternatively, you can use SQL Server Management studio to stop database mirroring session using the following steps: Step1: In the object explorer of the principal server instance expand databases Step2: Right click on the mirror database and select Tasks and then click on Mirror option which opens up Mirroring page of the Database Properties Step3: Click on the Stop Mirroring button to stop the session. You will be asked for a confirmation click on Yes and the session is stopped.

How to remove database mirroring session from a server? You can remove database mirroring using the following T-SQL statement: Use Master;

Page | 52

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

ALTER DATABASE <DB_Name> SET PARTNER OFF;

SQLFEST

Above statement causes a restart of the principal database by disconnecting all sessions currently using that database, and drops all information about the mirroring session. The principal and the mirror databases become independent of each other. You can now recover the former mirror database from the mirror server using the following statement: Use Master; RESTORE DATABASE <DB_Name> WITH RECOVERY; Alternatively, you can remove database mirroring using SQL Server Management studio by following the below steps: Step1: In the object explorer of the principal server expand databases Step2: Right click on the mirror database and select Tasks and then click on Mirror option which opens up Mirroring page of the Database Properties Step3: Click on the Remove Mirroring button to remove database mirroring. You will be asked for a confirmation click on Yes and database mirroring is removed.

Making Replication Mirror-aware


This is one of the most powerful features I like about Database mirroring and that is to make your publication database mirror-aware. This means that your replication will continue even after the publisher database goes down if the publisher is configured to be mirror-aware. Replication failover to a mirror is supported for publication databases only; it is not supported for distribution database or subscription databases. Some of the requirements for enabling this feature include: The principal and mirror server instance must use a shared distributor. We recommend that this be a remote distributor, which provides greater fault tolerance if the publisher has an unplanned failover. Both Publisher and Distributor must be using SQL Server 2005. Replication supports mirroring the publication database for merge replication and for transactional replication with read-only subscribers or queued updating subscribers only.

Page | 53

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Immediate updating subscribers, Oracle Publishers, Publishers in peer-to-peer topology, and republishing are not supported. Metadata and objects that exist outside the database are not copied to the mirror, including Logins, jobs, linked servers, and so on. (If you require the metadata and objects at the mirror, you must copy them manually).

Steps for Configuring Replication with Database Mirroring


Configuring replication with database mirroring is very easy if you do it couple of times Following are the five steps for successfully configuring replication with database mirroring: 1) 2) 3) 4) 5) First configure the publisher Second configure database mirroring Configure the mirror to use the same distributor as the principal Configure Replication agents for failover Add the principal and mirror to the replication monitor

Implementing database mirroring in production environment


It is always better to be safe than be sorry. Before you setup database mirroring in your production environment you must make sure that you have successfully tested all the operating modes and have concluded which operating mode can best suite your production environment. Sometimes even the test environment does not give you the right picture because of several barriers. Optimal database mirroring performance is obtained using asynchronous operation. A mirroring session that uses synchronous operation might experience slowed performance when its workload generates large amounts of transaction log data. It is important to understand how your network functions in the real world so that you can predict how database mirroring will work there. Synchronous mode with automatic failover is designed for a high-service network configuration that minimizes the sources of possible network failures. Such a high quality network environment is essential for high-safety mode with automatic failover and is recommended for database mirroring sessions. However, asynchronous mode and synchronous without automatic failover are much less affected by network reliability. For production environments, therefore we recommend that you follow these deployment guidelines:

Page | 54

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

1) Begin 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 running your system asynchronously until you are confident that your bandwidth supports mirroring and you have developed a solid knowledge of mirroring setup and of the performance of asynchronous mode in your environment. (Throughout testing, we recommend that you monitor your sessions for network errors that cause database mirroring to fail) 2) Once you are confident that asynchronous operation is meeting your business needs, you might want to try synchronous operation to improve your data protection. 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 your database performance. 3) Wait to enable automatic failover until you are confident that high-safety mode without automatic failover is meeting your business needs and that the network errors are not causing failures.

SQLFEST

Querying mirrored database using database snapshots


In the database mirroring environment Principal interacts with all the users but the mirror server only receives transaction log data from the principal server and other than that mirror database doesnt do anything as its in RECOVERING state all the time. With Database Snapshots you can take advantage of the mirror database that you are maintaining for high availability purposes to offload reporting. You can create a database snapshot on the mirror database and direct client connection requests to the most recent snapshot. You can create a database snapshot on the mirror database only when the database is fully SYNCHRONIZED. As long as both mirror and principal server are communicating with each other database snapshots can be accessible to clients. Keep in mind that as database snapshot is static, new data is not available. You must create new database snapshots periodically and have applications direct incoming client connections to the newest snapshot. The new database is almost empty, but it grows over time as more and more database pages are updated for the first time. Because every snapshot on a database grows incrementally in this way, each database snapshot consumes as much resources as a normal database. Depending on the configurations of the mirror server and principal server, having an excessive number of database snapshots on a mirror database might decrease performance on the principal database. Therefore, it is recommended that if you can live without touching

Page | 55

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

the mirror databases/servers, great and if not you can keep only a few relatively recent snapshots on your mirror databases. If role switching occurs, the database and its snapshots are restarted, temporarily disconnecting users. Afterwards, the database snapshots remain on the server instance where they were created, which has become the new principal database. Users can continue to use the snapshots after the failover. However, this places an additional load on the new principal server. If performance is a concern in your environment than it is recommended that you create a snapshot on the new mirror database when it becomes available and redirect clients to the new snapshot, and drop all of the database snapshots from the former mirror database. Note: For a dedicated reporting solution that scales out well, consider replication. Lets create a snapshot on the mirror database, make sure you are connected to the mirror database: Use Master; CREATE DATABASE MSNPE_Collect_SnapSHOT_0400 on (Name=MSNPE_Collect_0400_Data, FILENAME= H:\MSSQL\DATA\MSNPE_Collect_0400.snp) As SNAPSHOT OF MSNPE_Collect; You are now ready to use database snapshots for querying mirrored databases. How and where to view database snapshots? In the object explorer, connect to the instance of Microsoft SQL Server and expand Databases and then expand Database Snapshots and select the snapshot you want to view.

SQLFEST

Once you are done working with database snapshots, you may drop the database snapshots the same way as you would any user databases: Use Master; Drop Database MSNPE_Collect_SnapSHOT_0400;

Documenting database mirroring environment:

Page | 56

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Documentation is a very crucial and is a very major part of your H/A solution design. It is critical to produce complete, accurate documentation addressed to everyone who is involved with the solution. Out-of-date, inaccurate, or incomplete documentation is a great risk to the success of any H/A solution. Every software or infrastructure solution must be documented to ensure that it is implemented, operated, and tested properly. Documentation is the ley to maintaining high availability, because unless proper procedures are followed and change control is in place, it is likely that human errors or misunderstandings will lead to downtime. Clear, concise documentation for the audiences level of expertise will ensure the success of the solution. It is strongly recommended that you document your database mirroring environment so that you have a record of how it was setup and what change was made by whom and why and when. Below we are providing you with a template that can be used to document your Database Mirroring configuration. This document may be stored on a shared location so that all the DBAs or the service operations people can access it when needed. Feel free to make any changes to the template based on your environment.

SQLFEST

Page | 57

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
BUSINESS CONTACT INFORMATION Primary DBA: Secondary DBA: Primary DBA Phone #: Secondary DBA Phone # Alternate Ph # Primary DBA: Alternate Ph # Secondary DBA: Managers Name Managers Ph # Alternate Ph # Primary DBA E-mail: Secondary DBA E-mail:

SERVER INFORMATION (SOFTWARE / HARDWARE) PRINCIPAL SERVER INFORMATION O/S version Softwares Installed along with Version number: Service Accounts and Passwords Backup Location

SLA: Disaster Recovery Document Location:

Other miscellaneous document related to this server:

Principal Server Information

Principal Server Name:

Principal Server IP Address:

Page | 58

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Backups Location: Database being mirrored: Description of this database:

Endpoint Name:

Port #

Operating Mode

Transaction Safety:

List of jobs and other dependencies:

Server Network Address (use IPCONFIG /ALL)

Mirroring Script Location and Instructions:

Mirroring Troubleshooting Guide Location:

Other Information:

MIRROR SERVER INFORMATION Mirror Server Information Mirror Server Name: Mirror Server IP Address:

Page | 59

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Backups Location: Database being mirrored: Description of this database:

Endpoint Name:

Port #

Operating Mode

Transaction Safety:

List of jobs and other dependencies:

Server Network Address (use IPCONFIG /ALL)

Mirroring Script Location and Instructions:

Mirroring Troubleshooting Guide Location:

Other Information:

WITNESS SERVER INFORMATION Witness Server Information Endpoint Name: Witness Server Name: Port # Witness Server IP Address: Operating Mode

Page | 60

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Server Network Address (use IPCONFIG /ALL) Mirroring Script Location and Instructions:

Database Mirroring Troubleshooting Guide Location:

http://sqlcommunity.com

Page | 61

Author: Saleem Hakani | SQL Server Community


Copyright 2007 by www.sqlcommunity.com

Vous aimerez peut-être aussi