nakov sql server 2008 transactions ms devdays 2008

31
Best Practices for Optimizing Transactional Code in SQL Server 2008 Svetlin Nakov Director Training and Consulting Activities National Academy for Software Development (NASD) http://academy.devbg.org

Upload: myjlokesh

Post on 08-Nov-2015

224 views

Category:

Documents


5 download

DESCRIPTION

SQL Server 2008 Transactions

TRANSCRIPT

  • Best Practices for Optimizing Transactional Code in SQL Server 2008Svetlin NakovDirector Training and Consulting ActivitiesNational Academy for Software Development (NASD)http://academy.devbg.org

  • :

    *

    AgendaACID Transactions and Transaction Modes in SQL ServerUnderstanding Isolation LevelsConcurrency ProblemsLocking vs. VersioningAllowing Snapshot Isolation in SQL ServerSQL Server vs. Oracle Transactions

  • Transactions in SQL Server 2008

    *

    Database TransactionsTransactions are a sequence of modifications in the database executed as a single unit of work:Either all of them execute successfullyOr none of the themExample:A bank transfer from one account into another (withdrawal + deposit)If either the withdrawal or the deposit fails the whole operation is cancelled

    *

    ACID Properties of TransactionsAtomicityEither all modifications are performed, or noneConsistencyWhen completed, transactions leave all data and all related structures in a consistent stateIsolationTransactions don't see other's transaction's uncompleted work (intermediate state)DurabilityTransactions persist despite of system failure

    *

    ACID Transactions in SQL ServerHandled automatically across databases on the same instanceHandled through MSDTC automatically or explicitly across instancesControlled by Transaction Mode of the sessionCan be defined explicitly, at connection level and at server levelRequires error handling logicProgramming errors do not cause transaction rollback unless XACT_ABORT setting on

    *

    Transaction ModeAutocommit transactions (default)Statement level implicit transactionEach statement commits as a single unitExplicit transactions (user-defined)BEGIN TRANSATION COMMIT / ROLLBACK TRANSACTIONImplicit transactionsSession Level Setting SET IMPLICIT_TRANSACTIONS ON

  • Concurrency Problems and Isolation

    *

    Concurrency ProblemsSQL Server transaction isolation solves four major concurrency problemsDirty read occur when a reader reads uncommitted dataUnrepeatable read occurs when existing row change within a transactionLost updates occur when two writers modify the same piece of statePhantoms occur when new rows are added and appear within a transaction

    *

    Locking StrategiesOptimistic concurrencyLocks are not used readers never waitConflicts are possibleCan be resolved before commitHigh concurrency scale wellPessimistic concurrencyUse exclusive and shared locksTransactions wait for each otherLow concurrency does not scale

    *

    Isolation Levels and LockingANSI Isolation LevelsLevel 0 Read UncommittedLevel 1 Read CommittedLevel 2 Repeatable ReadsLevel 3 SerializableDefault isolation level in both SQL Server 2005/2008 is ANSI Level 1, Read CommittedIn implementation this default level uses lockingPessimistic concurrency

    *

    Isolation Levels and Concurrency in SQL Server 2008* Optimistic concurrency uses row versioning instead of row locking** Lost updates in snapshot isolation level are prevented by conflict detection instead of locking

    Isolation Level Dirty ReadsNonrepeat-able ReadsLost UpdatesPhantom ReadsConcurrency ModelRead uncommitted YesYesYesYesPessimisticRead committed snapshotNoYesYesYesOptimistic*Read committed NoYesYesYesPessimisticRepeatable read NoNoNoYesPessimisticSnapshot NoNoNo**NoOptimistic*Serializable NoNoNoNoPessimistic

  • Live DemoConcurrency Problems

  • Transactions Isolation: Locking vs. Versioning

    *

    Basic Locking TypesSQL Server insures isolation by means of lockingWrite locks are exclusive locks, read locks (shared locks) allow other readersA well-formed transaction acquires the correct lock type prior to using stateA two-phased transaction holds all locks until all locks have been acquiredIsolation levels determine how long locks are held

    *

    Traditional TransactionsSQL Server accomplishes isolation via lockingWriters wait on read locksBoth readers and writers wait on write locksVariety of isolation levels supportedHow long locks are heldWhat is locked (data and/or metadata)

    *

    Transactions and ConsistencySQL Server cannot guarantee statement-level consistency by lockingEven at serializable transaction levelRows are locked as they are readRows can be changed after the execution of the reading statement beginRead-consistency not guaranteed when multiple statements read multiple tablese.g. data warehouse unload jobsReaders cannot read old values when data is being updated

    *

    Transaction Isolation & VersioningSQL Server 2008 can also use row versioningIsolation accomplished by combination of locking and versioningWrite locks block other writersWrite locks do not block readersReaders do not lock by defaultReaders do not block writers by defaultKnown as snapshot isolationOld rows kept in tempdb for readingEases conversion from versioning databases

    *

    Snapshot ReadsSnapshot always reads coherent dataNo read lock needed even though data being changedVersion of each value maintained as long as neededTransaction reads version of value corresponding to its start time

    *

    Snapshot WritesWrites store the old version of changed rows in tempdbThis takes time and consume storage but allows better concurrencySnapshot Transactions are ACIDFailures may be deferredWrite fails if version later than that when transaction startedSerialization isolation holds off transaction until safe to proceed

    *

    Snapshot Isolation TypesTwo styles of snapshot isolationStatement-level snapshot like read committedConsistent as of last statementSee changes others commit during transactionTransaction-level snapshot like serializable Consistent as of beginning of transactionDon't see changes others commit during transactionProvides mandatory conflict detection

    *

    Using Snapshot IsolationMust be explicitly enabled at database levelSet ALLOW_SNAPSHOT_ISOLATION option ONmaster and msdb are snapshot enabled by defaultTransaction isolation level must be SNAPSHOTUSE master GOALTER DATABASE pubs SET ALLOW_SNAPSHOT_ISOLATION ON GO...SET TRANSACTION ISOLATION LEVEL SNAPSHOTBEGIN TRAN

    *

    Using Statement-Level Snapshot IsolationMust be explicitly enabled at database levelSet READ_COMMITTED_SNAPSHOT option ONTransaction isolation level must be READ COMMITTEDUSE master GOALTER DATABASE pubs SET READ_COMMITTED_SNAPSHOT ON GO...SET TRANSACTION ISOLATION LEVEL READ COMMITTEDBEGIN TRAN

  • Live DemoSnapshot vs. Serializable Isolation Levels

    *

    Versioning DrawbacksVersioning is not without costTakes up space in tempdbVersions kept regardless of usageSpace usage must be plannedUp to twice as much I/O for updatesReaders must read through saved versionsMore versions, slower readsConflict detection can cause updates to roll backMsg 3960, Level 16, State 1, Line 1. Cannot use snapshot isolation to access table 'authors' in database 'pubs'. Snapshot transaction aborted due to update conflict. Retry transaction.

    *

    Snapshot Isolation And LockingYou can lock explicitly during snapshot transaction if neededUse hint READCOMMITTEDLOCKPermits combination of versioning and lockingEquivalent of "SELECT FOR UPDATE"FOR UPDATE supported only in DECLARE CURSOR in SQL Server

    *

    SQL Server vs. Oracle TransactionsOracle uses optimistic concurrency by defaultUses the REDO log (transaction log) to implement row versioning (save changes only)Read locks (pessimistic concurrency) can be acquired explicitly only (SELECT FOR UPDATE)

    SQL Server Isolation LevelOracle Isolation LevelSQL Server ConcurrencyOracle ConcurrencyRead uncommitted PessimisticRead committed snapshotRead committedOptimisticOptimisticRead committed PessimisticRepeatable read (manual locks)PessimisticPessimisticSnapshot SerializableOptimisticOptimisticSerializable (manual locks)Pessimistic

    *

    SummaryTransaction Isolation with Locking (Pessimistic concurrency)Data read as of exact point in time or lockedFour transaction isolation levelsREAD UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLEAccomplished by adjustable lock type/durationBut...No statement level read consistency and multi table read consistency within transactionNo way to read old value of row being updated

    *

    SummaryTransaction Isolation with Versioning (Optimistic concurrency)Data read as of beginning of transactionTwo transaction isolation levelsSNAPSHOT and READ_COMMITTED_SNAPSHOTStatement level and multi-statement read consistencyBut...Extra versions of data kept (extra I/O)Update conflicts possible - rollback if snapshot is used

    *

    Optimizing Transactions Code in SQL Server 2008Questions?

    **** SQLskills.com SYSolutions, Inc. All rights reserved.**** SQLskills.com SYSolutions, Inc. All rights reserved.** SQLskills.com SYSolutions, Inc. All rights reserved.* SQLskills.com SYSolutions, Inc. All rights reserved.* SQLskills.com SYSolutions, Inc. All rights reserved.* SQLskills.com SYSolutions, Inc. All rights reserved.* SQLskills.com SYSolutions, Inc. All rights reserved.* SQLskills.com SYSolutions, Inc. All rights reserved.* SQLskills.com SYSolutions, Inc. All rights reserved.* SQLskills.com SYSolutions, Inc. All rights reserved.*