Download presentation
Presentation is loading. Please wait.
Published byQuentin McCormick Modified over 9 years ago
1
Honor that Transaction How to Design and Code Your Transactions Vineet Gupta Evangelist – Database and Integration Microsoft Corp. http://spaces.msn.com/members/vineetgupta/
2
Why Transactions? Correctness (programming model) ACID properties Atomicity All changes happen or nothing happens Consistency Data is transformed from one correct state to another Isolation Concurrent updaters are prevented from interfering with one another Durability Committed changes remain permanent despite failures
3
Scenario: Bank Funds Transfer Classical Savings Checking Withdraw from savings Deposit into checking Begin SQL Transaction Commit SQL Transaction Database Single Machine
4
Client-Server Savings Checking Withdraw from savings Deposit into checking Begin SQL Transaction Commit SQL Transaction Database Machine 1Machine 2
5
Three-Tier Components Savings Checking Database Withdraw Deposit Transfer TM Begin Tx Commit Tx Log
6
RM Distribution Savings Checking Withdraw Deposit Transfer TM Begin Tx Commit Tx Log
7
Roles in Transaction Systems Transaction Manager Transaction demarcation, participants, and stateTransaction demarcation, participants, and state Prepare result is made durablePrepare result is made durable Can Abort the transactionCan Abort the transaction Resource Manager Controls changes to resourcesControls changes to resources Uses a (durable) log for recoveryUses a (durable) log for recovery Can Abort the transactionCan Abort the transaction Client Application Begins the transaction,Begins the transaction, Makes changes to resources,Makes changes to resources, Can Commit or Abort the transactionCan Commit or Abort the transaction
8
Resource Manager
9
Resource Management ACID Transaction Design Requirements Atomicity Consistency Isolation Durability Isolation: A transaction either Sees data in the state it was in before another concurrent transaction modified it, Or it sees the data after the second transaction has completed, But it does not see an intermediate state
10
Isolation Levels Perfect Isolation of Transactions Leads to Resource Contention We actually use Degrees of Isolation Common Name Degree A.K.A. Lost Updates? Dirty Reads? Unrepeatable Reads? Phantoms? 0 Chaos Yes Yes Yes Yes 1 ReadUncommitted Browse Yes No Yes Yes 2 ReadCommitted CursorStability No No Yes Yes 3 Serializable Isolated No No No No 2.999 RepeatableRead No No No Yes
11
SQL-2000 locking Row-1 Tran2 (Select) Tran1 (Update) X-Lock S-LockBlocked Row-1
12
Microsoft® SQL Server™ 2005 Isolation Level Extensions Read-Committed Snapshot Isolation New flavor of read committed (non-locking) Statement-level Snapshot Isolation See most recent committed value of data as of the start of the statement Snapshot Isolation New isolation level Transaction-level Snapshot Isolation See most recent committed value of data as of the start of the transaction
13
SQL Server 2005 Isolation Levels Isolation Levels Dirty Read Non- Repeatable Read Phantoms Update Conflict Concurrency Control Read Uncommitted YesYesYesNo Read Committed 1 Locking 2 Snapshot No No Yes Yes No No Pessimistic Optimistic Repeatable Read NoNoYesNoPessimistic SnapshotNoNoNoYesOptimistic SerializableNoNoNoNoPessimistic Possible Anomalies
14
Read-Committed Snapshot New “flavor” of read committed Requires a database-level setting Readers see committed values as of beginning of statement Writers do not block Readers Readers do not block Writers Writers do block Writers Can greatly reduce locking / deadlocking without changing applications
15
Snapshot Isolation Represents a new isolation level Transitionally consistent database as of the beginning of the transaction Requires session-level setting Readers do not lock data Reduces deadlocks But at a cost of write-write conflicts Snapshot Isolation state is ON by default for master and msdb
16
Isolation Levels: In Summary READ UNCOMMITTED (Level 0) “Dirty Reads” – An option ONLY for readers Any data (even that which is in-flight/locked) can be viewed READ COMMITTED (Level 1 – Default) Only committed changes are visible Data in an intermediate state cannot be accessed READ COMMITTED SNAPSHOT (RCSI) Statement-level read consistency New non-blocking, non-locking (ex. SCH_S), version-based Level 1
17
Isolation Levels: In Summary (cont’d) REPEATABLE READS (Level 2) All reads are consistent for the life of a transaction Shared locks are NOT released after the data is processed Does not protect entire set (i.e. phantoms may occur) SERIALIZEABLE (Level 3) All reads are consistent for the life of a transaction Avoids phantoms – no new records Snapshot Isolation – 2005 Transaction-Level consistency using snapshot New non-blocking, non-locking, version-based transactions
18
Transaction Manager
19
A Brief History MTS 1.0 12/1996 DTC 1.0 4/1996 COM+ 1.0 12/1999 COM+ 1.5 8/2001 System.EnterpriseServices 2/2002 WS-Transaction 8/2002 MTS 2.0 12/1997 199619971998199920002001200219801990 IMS 1973 CICS ~1968 Encompass Tandem ACMS Digital Mid 80’s Tuxedo 1984 Tandem TMF ???? Encina 1993 JTS 12/1999 OMG OTS 1.2 5/2001 OASIS BTS 5/2002 JTA 4/1999 J2EE 12/1999 BTS 4/2000 1970 TIP 7/1998 OMG OTS 1.1 11/1997 XA (spec) 1991
20
Local Transactions DBMS Application Application Activity Activity Activity ADOConn Client 1 Client 2 Client N Transaction Manager LockManager Data VB Object ADOConn ADOConn
21
Distributed transaction Computer 3 RM3 - ORACLE Participating DTC Computer 2 RM2 -SQL Server Participating DTC Computer 1 The Coordinating DTC RM1 - MSMQ Data Data Your Tx COM+ Application Queue RM Proxy
22
Two-Phase Commit Transaction Manager Resource Manager Prepare Commit Prepare and Force write “Prepared” record to RM log Prepared Force write “Commit” record to TM log Lazy write “Committed” record to RM log and Release locks Committed Lazy write “Committed” record to TM log
23
Two Phase Commit – Failure Transaction Manager Resource Manager Prepare Commit Prepare & Write “Prepared” record to RM log Prepared Write “Commit” record to TM log Write “Committed” record to RM log & Release locks Committed Write “Committed” record to TM log Abort on Failure Commit Abort on Failure Indoubt on Failure Commit Will Abort Will Commit
24
Today MS-DTC API OLE Transactions DTC Proxy COM Interfaces App/TM, TM/RM, etc Local or Remote TM API and config Protocols OLE Transactions XA, TIP, LU6.2 Resource Managers SQL Server, MSMQ DB2, Oracle, …
25
Today COM+ Transactions High Level Programming Model supporting Declarative transaction model Provides execution environment and full support of all transaction features (e.g. commit coordination, isolation level, timeout, etc.) Support for Compensating Resource Managers (CRM) Evolution of MTS (think MTS 3.0) Building Block for.Net Transaction Model
26
Today Transaction Example Transaction automatically created Connections automatically enlisted Outcome automatically coordinated Root Sub2 Required or Requires New Root Client Sub1 Sub1 & Sub 2 = Required or Supported Transaction
27
Today Transactions in.Net System.EnterpriseServices namespace provides the programming model All COM+ features exposed via attributes All.Net language features available Provides full integration with the.Net runtime integration Full interop with existing COM+ components
28
Today System.EnterpriseServices Example using System; using System.Data.SqlClient; using System.EnterpriseServices; [assembly : ApplicationName("TxDemo")] [Transaction(TransactionOption.RequiresNew, Isolation = TransactionIsolationLevel.ReadCommitted, Timeout = 60)] public class Account : ServicedComponent { [AutoComplete(true)] [AutoComplete(true)] public void Credit() public void Credit() { // do some work // do some work }}
29
Tomorrow
30
New Architecture System.Transaction Lightweight Transaction Manager (LTM) DTC Resource Manager (SQL) Enterprise Services Cross App Domain Cross Computer
31
Lightweight Transaction Manager (LTM) Common Starting Point for Transactions Remove any actual and perceived initial penalties for use LTM is a full-fledged transaction manager for volatile resources Fast Transaction creation Minimum performance overhead when using volatile resource in the same app-domain Promotable Single Phase Enlistment (PSPE) support to remove overhead when using a single resource manager In this case, the RM manages the transaction Single log operation Supported by SQL 2005 Pay as you go – Dynamic Promotions
32
System.Transactions Typical Tasks: Define scope of transaction (consistency) Perform read/write operations on resource managers Specify consistency state upon completion Interfaces:TransactionScopeTransaction.Current Application Transaction Manager Resource Manager Managed Code Enlist in transactions Implements commit/abort notifications from the Transaction Manager ApplicationsResource Managers
33
Application Usage Example Unify database and collection error handling: Imports System.Transaction Imports System.Transaction Dim activeMembers As TransactedHashTable() Dim activeMembers As TransactedHashTable() Public Sub AddMembership (ByVal MemberName As String, _ Public Sub AddMembership (ByVal MemberName As String, _ ByVal Organization As String) ByVal Organization As String) Using ts As New TransactionScope() Using ts As New TransactionScope() activeMembers.Add (MemberName, Organization) activeMembers.Add (MemberName, Organization) … sqlCommand.ExecuteNonQuery (… add member insert…) sqlCommand.ExecuteNonQuery (… add member insert…) sqlCommand.ExecuteNonQuery (… add organization insert…) sqlCommand.ExecuteNonQuery (… add organization insert…) … AppBizLogic = new AppBizLogic AppBizLogic = new AppBizLogic AppBizLogic.UpdateState(… state …) AppBizLogic.UpdateState(… state …) … ts.Consistent = True ts.Consistent = True End Using End Using End Sub End Sub
34
Architecture System.Transaction Lightweight Transaction Manager (LTM) DTC Resource Manager (SQL) Enterprise Services Cross App Domain Cross Computer Indigo Service
35
Indigo Transaction Service Model Attribute based programming Need to consider the following points Service Contract Attribute: TransactionFlowAllowed send the transaction context Service Implementation Per method attribute TransactionRequired – Creates or derives a transaction context AutoComplete – Explicit or Implicit completion of the transaction
36
Indigo Transaction Service Model Major Differences from COM+/EnterpriseServices Transaction context does not flow by default Transaction flow is separate from transaction usage Transaction context is set at method invocation, and not at object creation time
37
Service Model - Example [ServiceContract(Binding = BindingMode.Internet)] public interface IBankAccount { [ServiceOperation(IsOneWay = true)] [ServiceOperation(IsOneWay = true)] string LookUpName(string text); string LookUpName(string text); [ServiceOperation(IsOneWay = false, TransactionFlowAllowed = true)] [ServiceOperation(IsOneWay = false, TransactionFlowAllowed = true)] [ServiceOperationSettings(TransactionRequired = true, AutoComplete = true)] [ServiceOperationSettings(TransactionRequired = true, AutoComplete = true)] void AddMembership(string memberName); void AddMembership(string memberName);} static TransactedHashtable activeMembers = new TransactedHashtable (); static TransactedHashtable allMembers = new TransactedHashtable (); void AddMembership (string memberName) { activeMembers.Add (memberName, organization); allMembers.Add (memberName, organization); … sqlCommand.ExecuteNonQuery (… add member insert…) sqlCommand.ExecuteNonQuery (… add organization insert…) }
38
Beyond Indigo Transacted Collection Classes Longhorn Integration Kernel Transaction Manager Transacted File System Transacted Registry
39
Questions?
40
Further Reading Principles of Transaction Processing Bernstein and Newcomer Transactional COM+ Tim Ewald SQL Server Architecture and Internals Ken Henderson SQL Server 2005 for Developers Neils Burglend and Bob Beauchmen Programming Indigo David Pallman
41
Your Feedback is Important! Please Fill Out the feedback form
42
© 2005 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.