Module 11 Creating Highly Concurrent SQL Server® 2008 R2 Applications.

Slides:



Advertisements
Similar presentations
Applied Database II Transactions In Database The ACID Test Atomicity The whole transaction or none of it Consistency Remains in a consistent state -
Advertisements

Chapter 16 Concurrency. Topics in this Chapter Three Concurrency Problems Locking Deadlock Serializability Isolation Levels Intent Locking Dropping ACID.
1 Lecture 11: Transactions: Concurrency. 2 Overview Transactions Concurrency Control Locking Transactions in SQL.
Module 17 Tracing Access to SQL Server 2008 R2. Module Overview Capturing Activity using SQL Server Profiler Improving Performance with the Database Engine.
Transaction Processing. Objectives After completing this lesson, you should be able to do the following: –Define transactions effectively for an application.
Module 20 Troubleshooting Common SQL Server 2008 R2 Administrative Issues.
1 Data Concurrency David Konopnicki 1997 Revised by Mordo Shalom 2004.
Transactions and Locking Rose-Hulman Institute of Technology Curt Clifton.
Transactions and Locks
Module 15: Managing Transactions and Locks. Overview Introduction to Transactions and Locks Managing Transactions SQL Server Locking Managing Locks.
Database Administration Chapter Six DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Transaction Management and Concurrency Control
Transaction Management and Concurrency Control
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
9 Copyright © 2009, Oracle. All rights reserved. Managing Data Concurrency.
Database Administration Part 1 Chapter Six CSCI260 Database Applications.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Transaction Management and Concurrency Control.
Managing Concurrency in Web Applications. DBI 2007 HUJI-CS 2 Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses.
Transactions and Locks Lesson 22. Skills Matrix Transaction A transaction is a series of steps that perform a logical unit of work. Transactions must.
Managing Transaction and Lock Vu Tuyet Trinh Hanoi University of Technology 1.
1 IT420: Database Management and Organization Transactions 31 March 2006 Adina Crăiniceanu
Transactions and Exception Handling Eric Allsop SQLBits 6 th October 2007.
Module 12 Handling Errors in T-SQL Code. Module Overview Understanding T-SQL Error Handling Implementing T-SQL Error Handling Implementing Structured.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 10 Transaction Management.
Oracle Locking Michael Messina Principal Database Analyst Indiana University.
1cs Intersection of Concurrent Accesses A fundamental property of Web sites: Concurrent accesses by multiple users Concurrent accesses intersect.
Department of Computer Science and Engineering, HKUST 1 More on Isolation.
ITEC 3220M Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220m.htm
Module 16: Performing Ongoing Database Maintenance
Concurrency and Transaction Processing. Concurrency models 1. Pessimistic –avoids conflicts by acquiring locks on data that is being read, so no other.
Unit 9 Transaction Processing. Key Concepts Distributed databases and DDBMS Distributed database advantages. Distributed database disadvantages Using.
DB2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/DB01/003 Version No:2.0a Session Plan Introduction to Concurrency Control Different types.
1 IT420: Database Management and Organization Session Control Managing Multi-user Databases 24 March 2006 Adina Crăiniceanu
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 136 Database Systems I SQL Modifications and Transactions.
How transactions work A transaction groups a set of Transact-SQL statements so that they are treated as a unit. Either all statements in the group are.
Database structure and space Management. Database Structure An ORACLE database has both a physical and logical structure. By separating physical and logical.
Transactions and Locks A Quick Reference and Summary BIT 275.
© 2002 by Prentice Hall 1 Database Administration David M. Kroenke Database Concepts 1e Chapter 6 6.
Random Logic l Forum.NET l Transaction Isolation Levels Forum.NET Meeting ● Nov
Module 6: Data Protection. Overview What does Data Protection include? Protecting data from unauthorized users and authorized users who are trying to.
SQLintersection Understanding Transaction Isolation Levels Randy Knight Wednesday, 3:45-5:00.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_JDBC_MySQL 1 Transations.
Module 11: Managing Transactions and Locks
©Bob Godfrey, 2002, 2005 Lecture 17: Transaction Integrity and Concurrency BSA206 Database Management Systems.
3 Database Systems: Design, Implementation, and Management CHAPTER 9 Transaction Management and Concurrency Control.
Module 14: Managing Transactions and Locks. Overview Introducing Transactions and Locks Managing Transactions Understanding SQL Server Locking Architecture.
In this session, you will learn to: Implement triggers Implement transactions Objectives.
Does the Optimistic Concurrency resolve your blocking problems Margarita Naumova, SQL Master Academy.
Locks, Blocks & Isolation Oh My!. About Me Keith Tate Data Professional for over 14 Years MCITP in both DBA and Dev tracks
Read Dirty to Me: SQL Server Isolation Levels Wendy Pastrick Arrow IT Consulting.
Database Transactions  Transaction Management and Concurrency Control.
Transaction Management and Concurrency Control
LAB: Web-scale Data Management on a Cloud
Isolation Levels Understanding Transaction Temper Tantrums
The Vocabulary of Performance Tuning
On transactions, and Atomic Operations
Batches, Transactions, & Errors
Transactions, Locking and Query Optimisation
Chapter 10 Transaction Management and Concurrency Control
Understanding Transaction Isolation Levels
On transactions, and Atomic Operations
Batches, Transactions, & Errors
Introduction of Week 13 Return assignment 11-1 and 3-1-5
The Vocabulary of Performance Tuning
Objectives Define and describe transactions
Transactions and Concurrency
Database Administration
Isolation Levels Understanding Transaction Temper Tantrums
The Vocabulary of Performance Tuning
Module 13: Creating Highly Concurrent SQL Server 2012 Applications
Presentation transcript:

Module 11 Creating Highly Concurrent SQL Server® 2008 R2 Applications

Module Overview Introduction to Transactions Introduction to Locks Management of Locking Transaction Isolation Levels

Lesson 1: Introduction to Transactions What are Transactions? Auto Commit Transactions Explicit Transactions Implicit Transactions Transaction Recovery Considerations for using Transactions Demonstration 1A: Transactions

What are Transactions? A transaction is an atomic unit of work A transaction leaves data in a consistent state A transaction is isolated from other concurrent transactions A transaction is durable

Auto Commit Transactions Default transaction mode Every TSQL statement is committed or rolled back when it has completed. Committed if successful; Rolled back if error Compile errors result in entire batch not being executed Run time errors may allow part of the batch to commit Database engine operates in autocommit until an explicit transaction is started. XACT_ABORT setting ON converts statement terminating errors into batch terminating errors; compile errors not affected by XACT_ABORT ON SET XACT_ABORT ON;

Explicit Transactions A transaction in which start and end of transaction is explicitly declared BEGIN TRANSACTION COMMIT TRANSACTION ROLLBACK TRANSACTION SAVE TRANSACTION Transaction Log – Use WITH MARK to specify transaction marked in log BEGIN TRANSACTION FundsTransfer; EXEC Banking.DebitAccount '100', 'account1'; EXEC Banking.CreditAccount '100', 'account2'; COMMIT TRANSACTION; BEGIN TRANSACTION FundsTransfer; EXEC Banking.DebitAccount '100', 'account1'; EXEC Banking.CreditAccount '100', 'account2'; COMMIT TRANSACTION;

Implicit Transactions Setting implicit transaction mode on An implicit transaction starts when one of the following statements is executed and the statement is not part of an existing transaction Transaction must be explicitly completed with COMMIT or ROLLBACK TRANSACTION SET IMPLICIT_TRANSACTIONS ON; ALTER TABLEINSERT CREATEOPEN DELETEREVOKE DROPSELECT FETCHTRUNCATE TABLE GRANTUPDATE

Transaction Recovery Action Required None CheckpointSystem Failure Roll forward Roll back Roll forward Roll back

Considerations for using Transactions Considerations for nested transactions Allowed by syntax but true nesting not supported Use to determine nesting level When a nested transaction rolls back, it rolls back the outer transaction as well Considerations for nested transactions Allowed by syntax but true nesting not supported Use to determine nesting level When a nested transaction rolls back, it rolls back the outer transaction as well Keep transactions as short as possible Do not require user input Do not browse data Access the least amount of data possible Do not open the transaction before it is required Keep transactions as short as possible Do not require user input Do not browse data Access the least amount of data possible Do not open the transaction before it is required Try to access resources in the same order Accessing resources in the same order within transactions can help avoid deadlocks This is not always possible Try to access resources in the same order Accessing resources in the same order within transactions can help avoid deadlocks This is not always possible

Demonstration 1A: Transactions In this demonstration you will see how transactions work how blocking affects other users Note that blocking is discussed further in the next lesson.

Lesson 2: Introduction to Locks Methods of Concurrency Control What are Locks? Blocking vs. Locking What Concurrency Problems are Prevented by Locking Lockable Resources Types of Locks Lock Compatibility

Methods of Concurrency Control Two main concurrency control types: Pessimistic -Locks data when data is read in preparation for update -Other users are blocked until lock is released -Use where a high contention for data exists Optimistic -Locks data when an update is performed -Error received if data is changed since initial read -Use where a low contention for data exists

What are Locks? Mechanism to sync access by multiple users to the same data at the same time Two main types of lock: Read locks – Allow others to read but not write Write locks – Stop others from reading or writing Locks prevent update conflicts Locking ensures that transactions are serialized Locking is automatic Locks enable concurrent use of data

Blocking vs. Locking These two terms are often confused: Locking - The action of taking and potentially holding locks - Used to implement concurrency control Blocking - Normal occurrence for systems using locking - One process needs to wait for another process to release locked resources - Only a problem if it lasts too long

What Concurrency Problems are Prevented by Locking? Without locking mechanisms, the following problems can occur: Lost updates Uncommitted dependency (dirty read) Inconsistent analysis (non-repeatable read) Phantom reads Missing and double reads caused by row updates

Lockable Resources SQL Server can lock these resources: RID A row identifier used to lock a single row within a heap. KEY A row lock within an index used to protect key ranges in serializable transactions. PAGE An 8-kilobyte (KB) page in a database, such as data or index pages. EXTENT A contiguous group of eight pages, such as data or index pages. HoBT A heap or B-tree. A lock protecting a B-tree (index) or the heap data pages in a table that does not have a clustered index. TABLEThe entire table, including all data and indexes. FILEA database file. APPLICATIONAn application-specified resource. METADATAMetadata locks. ALLOCATION_UNITAn allocation unit. DATABASEThe entire database.

Types of Locks Lock mode Description Shared (S)Used for read operations. Update (U)Used on resources that can be updated. Exclusive (X) Used for data-modification operations, such as INSERT, UPDATE, or DELETE. IntentUsed to establish a lock hierarchy. SchemaUsed when an operation dependent on the schema of a table is executing. Bulk Update (BU) Used when bulk copying data into a table and the TABLOCK hint is specified. Key-rangeProtects the range of rows read by a query when using the serializable transaction isolation level.

Lock Compatibility Not all locks are compatible with other locks. As a simple (but incomplete) example: Refer to Books Online for a complete list Lock Incompatible with Shared (S)Exclusive (X) Update (U)All but Shared (S) Exclusive (X)All other locks

Lesson 3: Management of Locking Locking Timeout Lock Escalation What are Deadlocks? Locking-related Table Hints Methods to View Locking Information Demonstration 3A: Viewing Locking Information

Locking Timeout How long should you wait for a lock to be released? SET LOCK_TIMEOUT specifies number of milliseconds to wait -1 (default) waits forever When timeout expires, error is returned and statement rolled back Not used often as most applications include query timeouts READPAST locking hint – available but rarely used SET LOCK_TIMEOUT 5000;

Lock Escalation Lock escalation converts many fine- grain locks to fewer coarse-grain locks Large numbers of rows are often processed This brings a need for large numbers of locks Acquiring and releasing a large number of locks can have a significant impact on processing performance and memory availability SQL Server will escalate from row locks to the table level as needed For partitioned tables, it can escalate to the partition level

What are Deadlocks? Occurs when two or more tasks permanently block each other by each task having a lock on a resource which the other tasks are trying to lock. -Task T1 has a lock on resource R1 (arrow from R1 to T1) and has requested a lock on resource R2 (arrow from T1 to R2). -Task T2 has a lock on resource R2 (arrow from R2 to T2) and has requested a lock on resource R1 (arrow from T2 to R1). -Because neither task can continue until a resource is available and neither resource can be released until a task continues, a deadlock state exists. SQL Server automatically detects this situation and raises an error 1205 Task 1 Task 2 Resource 1 Resource 2

Locking-related Table Hints HintDescription HOLDLOCKHolds shared locks until the end of the transaction NOLOCKDoes not take or honor locks PAGLOCKTakes page locks rather than row locks ROWLOCKTakes row locks rather than page or table locks TABLOCKTakes a table lock rather than a row or page lock TABLOCKXTakes an exclusive lock on the whole table UPDLOCKTakes an update lock and holds it until the end of the transaction XLOCKExclusive locks are taken and held until the end of the transaction

Methods to View Locking Information Activity Monitor Dynamic Management Views SQL Server Profiler Reliability and Performance Monitor

Demonstration 3A: Viewing Locking Information In this demonstration, you will see how to: View lock information using Activity Monitor Use dynamic management views to view lock info

Lesson 4: Transaction Isolation Levels SQL Server Transaction Isolation Levels Read Committed Snapshot Isolation-related Table Hints

SQL Server Transaction Isolation Levels Isolation LevelDirty Read Nonrepeatable Read Phantoms Read uncommittedYes Read committed (default)NoYes Repeatable readNo Yes SnapshotNo SerializableNo Transaction Isolation Level can be set at the session level separately for each transaction

Read Committed Snapshot SNAPSHOT isolation level is useful but typically requires modifications to the application  In particular many reporting applications could benefit from it Read Committed Snapshot is a database option that requires no modifications to the application Statements that use Read Committed are automatically promoted to use Read Committed Snapshot instead Locks are only held for the duration of the statement, not the duration of the transaction ALTER DATABASE Sales SET ALLOW_SNAPSHOT_ISOLATION ON; ALTER DATABASE Sales SET READ_COMMITTED_SNAPSHOT ON; ALTER DATABASE Sales SET ALLOW_SNAPSHOT_ISOLATION ON; ALTER DATABASE Sales SET READ_COMMITTED_SNAPSHOT ON;

Isolation-related Table Hints HintDescription READCOMMITTEDUse read committed transaction isolation level READCOMMITTEDLOCKForces locking to be used when implementing read committed (when read committed snapshot has been enabled) READUNCOMMITTEDUse read uncommitted transaction isolation level REPEATABLEREADUse repeatable read transaction isolation level SERIALIZABLEUse serializable transaction isolation level

Lab 11: Creating Highly Concurrent SQL Server Applications Exercise 1: Detecting Deadlocks Challenge Exercise 2: Investigating Transaction Isolation Levels (Only if time permits) Logon information Estimated time: 45 minutes

Lab Scenario In this lab, you will perform basic investigation of a deadlock situation. You are trying to determine an appropriate transaction isolation level for a new application. If you have time, you will investigate the trade-off between concurrency and consistency.

Lab Review What transaction isolation levels does SQL Server offer? How does blocking differ from locking?

Module Review and Takeaways Review Questions Best Practices