1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?
-
Upload
livia-pinto-klettenberg -
Category
Documents
-
view
216 -
download
0
Transcript of 1. Como o SQL Server gere toda a problemática dos locks 2 Lock Model, o que é ?
SQL Server Lock Model
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
Locks
4
Problemática dos locks
5
carga
tps
Duração
“Phantoms”
Integridade
“Dirty Read”
Escalabilidade
“Non repeatable Reads”
Problemas “estranhos”
Concurrência
Propriedades das transacçõesACIDA)tomicity (tudo ou nada)C)onsistency I)solation (grau de independência)D)urability
6
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
Granularidade dos LocksRow (RID)Key (KEY)Page (PAG)Extent (EXT)Table (TAB)Database (DB)
8
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
Row : até 8Kb (8060 Bytes)
Extent (8 pages) 8 x 8Kb =64KbMixed exents (8 objectos)
Page : 8Kb (8192 Bytes)
10
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
Gestão da concorrência:a) Níveis de Isolamento
Read UncomitedRead CommittedRead Commited
SnapshotRepeatable ReadSerialzableSnapshot
12
b) Lock Hints
“Sistema Solar” do SQL
13
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 - -
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.
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
P: Como definir o isolation level ?
R: DBCC USEROPTIONS
17
R: SET TRANSACTION ISOLATION LEVEL
P: Como saber qual o isolation level ?
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
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
Modo de compatibilidade (full)
20
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
Deadlock
22
Tipos de Locks especiaisIntent LockLatches
23
Ferramentassp_lockSQL Server Management StudioProfilerPerformance counter
24
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
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
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
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
Q & A
29
30
fim.