1. como o sql server gere toda a problemática dos locks 2 lock model, o que é ?

30
SQL Server Lock Model 1

Upload: livia-pinto-klettenberg

Post on 07-Apr-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

SQL Server Lock Model

1

Page 2: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Como o SQL Server gere toda a problemática dos locks

2

Lock Model, o que é ?

Page 3: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Lock Model, porquê ?Os locks, em conjunto com os índices, são as

2 coisas que mais contribuem para escalabilidade do SQL Server, ou para a falta dela.

Conhecer o lock model é uma grande ajuda, nos despiste de problemas “estranhos”, como por exemplo a aplicação estar lenta e o CPU, IO não ter utilização significativa ou ainda um determinado job às vezes não terminar.

3

Page 4: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Locks

4

Page 5: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Problemática dos locks

5

carga

tps

Duração

“Phantoms”

Integridade

“Dirty Read”

Escalabilidade

“Non repeatable Reads”

Problemas “estranhos”

Concurrência

Page 6: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Propriedades das transacçõesACIDA)tomicity (tudo ou nada)C)onsistency I)solation (grau de independência)D)urability

6

Page 7: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Uma transação

7

BEGIN TRYBEGIN TRANSACTION T1INSERT INTO dbo.t1 SELECT p.ProductID FROM Production.Product AS pINSERT INTO dbo.t1

VALUES (1)COMMIT TRANSACTION T1

END TRY

BEGIN CATCHROLLBACK TRANSACTION T1PRINT 'An error occurred'RETURN

END CATCH

Page 8: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Granularidade dos LocksRow (RID)Key (KEY)Page (PAG)Extent (EXT)Table (TAB)Database (DB)

8

Page 9: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Background informationP:Qual a dimensão máxima de uma row ?R:8060 bytes

P:Qual é a dimensão de uma página ?R:8Kb

P:Qual é a dimensão de um extent ?R:8 Páginas, 64 Kb

9

Page 10: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Row : até 8Kb (8060 Bytes)

Extent (8 pages) 8 x 8Kb =64KbMixed exents (8 objectos)

Page : 8Kb (8192 Bytes)

10

Page 11: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Tipos de LockShared (S)Update (U)Exclusive (X)Intent Shared (IS)Intent Exclusive (IX)Shema Modification (Sch-M)Shema Stability (Sch-S)RangeS-SEtc..

11

Page 12: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Gestão da concorrência:a) Níveis de Isolamento

Read UncomitedRead CommittedRead Commited

SnapshotRepeatable ReadSerialzableSnapshot

12

b) Lock Hints

Page 13: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

“Sistema Solar” do SQL

13

Page 14: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Comportamentos Permitidos

14

Transaction Level

Comportamento Outros Locks

X Lock

Read Uncommited Dirty ReadsNon repeatable ReadsPhantoms

- -

Read Commited (Locking)

Non repeatable ReadsPhantoms

SProcess.

Fim

Read Commited (Snapshot)

Non repeatable ReadsPhantoms

- -

Repeatable Read Phantoms C:KEY LockNC:S,IS : index e table pag.Fim

Fim

Serializable None RangeS-S fim

Fim

Snapshot None - -

Page 15: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Lock Hints

15

hint DescriptionHOLDLOCK Hold a shared lock until completion of the transaction instead of releasing the lock as

soon as the required table, row, or data page is no longer required. HOLDLOCK is equivalent to SERIALIZABLE.

NOLOCK Do not issue shared locks and do not honor exclusive locks. When this option is in effect, it is possible to read an uncommitted transaction or a set of pages that are rolled back in the middle of a read. Dirty reads are possible. Only applies to the SELECT statement.

PAGLOCK Use page locks where a single table lock would usually be taken.READCOMMITTED Perform a scan with the same locking semantics as a transaction running at the READ

COMMITTED isolation level. By default, SQL Server 2000 operates at this isolation level.

READPAST Skip locked rows. This option causes a transaction to skip rows locked by other transactions that would ordinarily appear in the result set, rather than block the transaction waiting for the other transactions to release their locks on these rows. The READPAST lock hint applies only to transactions operating at READ COMMITTED isolation and will read only past row-level locks. Applies only to the SELECT statement.

READUNCOMMITTED Equivalent to NOLOCK.REPEATABLEREAD Perform a scan with the same locking semantics as a transaction running at the

REPEATABLE READ isolation level.ROWLOCK Use row-level locks instead of the coarser-grained page- and table-level locks.

SERIALIZABLE Perform a scan with the same locking semantics as a transaction running at the SERIALIZABLE isolation level. Equivalent to HOLDLOCK.

TABLOCK Use a table lock instead of the finer-grained row- or page-level locks. SQL Server holds this lock until the end of the statement. However, if you also specify HOLDLOCK, the lock is held until the end of the transaction.

TABLOCKX Use an exclusive lock on a table. This lock prevents others from reading or updating the table and is held until the end of the statement or transaction.

UPDLOCK Use update locks instead of shared locks while reading a table, and hold locks until the end of the statement or transaction. UPDLOCK has the advantage of allowing you to read data (without blocking other readers) and update it later with the assurance that the data has not changed since you last read it.

XLOCK Use an exclusive lock that will be held until the end of the transaction on all data processed by the statement. This lock can be specified with either PAGLOCK or TABLOCK, in which case the exclusive lock applies to the appropriate level of granularity.

Page 16: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Qual estratégia esclher ?

16

Isolation Level

Lock Hints Hibrido

Controlo Standard Mais fino Mais finoPrevisibilidade

Previsível Imprevisível Imprevisível

Escalation Sim Não Não

Page 17: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

P: Como definir o isolation level ?

R: DBCC USEROPTIONS

17

R: SET TRANSACTION ISOLATION LEVEL

P: Como saber qual o isolation level ?

Page 18: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

SET TRANSACTION ISOLATION LEVEL

SET TRANSACTION ISOLATION LEVEL    { READ UNCOMMITTED | READ COMMITTED     | REPEATABLE READ     | SNAPSHOT     | SERIALIZABLE   }Nota : Se READ_COMMITTED_SNAPSHOT está

ON, O SQL Server usa “row versioning” (tempdb).

18

Page 19: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

IS S U IX X Sck-S Sch-M

Intent Shared I S Sim Sim Sim Sim Sim

Shared S Sim Sim Sim Sim

Update U Sim Sim Sim

Intent Exclusive I X Sim Sim Sim

Exclusive X Sim

Schema Stability Sck-S Sim Sim Sim Sim Sim Sim

Schema Modification Sch-M

Modo de compatibilidade

19

Lock Compatível ?

SimNão

Grant

Wait SET LOCK_TIMEOUT timeout_period@@LOCK_TIMEOUT

S > S > GrantX > S > Wait

Page 20: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Modo de compatibilidade (full)

20

Page 21: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Quais os locks na alteração e porquêP: S ⇒ X ou S ⇒ U ⇒ X ?R: S ⇒ U ⇒ X

21

0 1 2 3 4S U X - -S U X

Page 22: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Deadlock

22

Page 23: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Tipos de Locks especiaisIntent LockLatches

23

Page 24: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Ferramentassp_lockSQL Server Management StudioProfilerPerformance counter

24

Page 25: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

sp_lock

25

Spid The SQL server process ID NumberDbid The Database Id NumberObjid The oject Id number of object beeing lockedType Lock Type

DB DatabaseFIL FileIDX IndexPAG PageKEY KeyTAB TableEXT ExtentRID Row Identifier

Resource Page LockPAG file#:page#pairRID file#:page#slot#tripleEXT file#:page#pairKey Hashed value

Mode ModeStatus GRANT, WAIT, CNVRT

S,X,U,etc

Page 26: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

RecomendaçõesManter transacções pequenas evitando operações

“caras”.Optimizar queries usando índices.Evitar perder controlo no âmbito da transacção.Monitorizar “long running processes”.Investir no tratamento de erros ou usar SET

XACT_ABORT ON para evitar uma transacção ficar aberta no surgimento de uma condição de erro.

Usar o nível de isolamento o mais baixo possível,

26

Page 27: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Problemática dos locks

27

carga

tps

DuraçãoLock timoutControlo errosSET XACT_ABORT ON

“Phantoms” Serializable

Integridade

“Dirty Read”Read commitedRepetable readsSerializable

Escalabilidade Baixar isolation level “Non repeatable Reads”

Repeatable read

Problemas “estranhos”sp_lock

ConcurrênciaBaixar isolation level

Page 28: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

BibliografiaHand on SQL 2000 Troubleshooting locking

and blocking (net impress)Inside Microsoft SQL Server 2005. The

Storage Engine (microsoft)Microsoft SQL Server 2008 Internals

(microsoft)SQL Server 2008 Query Performance Tuning

Distilled (apress)

28

Page 29: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

Q & A

29

Page 30: 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?

30

fim.