Docsity

Lock Thrashing - E-Commerce - Lecture Slides, Slides of Fundamentals of E-Commerce

Toggle sidebar
bg1
1
2/15/05 1
8. C oncurrency C ontrol
for Transactions
Part Tw o
545 Transaction Processing
2
/
15
/
05 2
Outline
1. A Model for C oncurrency Control
2. Serializab ility Theory
3. Synchronization R equirem ents for Recoverab ility
4. Tw o-Phase Locking
5. Implem en ting Tw o-Phase Locking
6. Locking Performance
7. Multigran ularityLocking (revisited)
8. Hot Spot T echniques
9. Query-Update T echniques
10. Phantom s
11. Shared Disk System s
12. B-Trees
13. Tree locking
2
/
15
/
05 3
8.6 Locking Performance
• D eadlocks are rare
– up to 1% -2% of transactions deadlock
•The one exception to this is lock conversions
–r-lock a record and later upgrad e to w-lock
–e.g., Ti= read (x) … write(x)
–if two txnsdo this concurrently, they’ll deadlock
(both get an r-lock on x before either gets a w-lock)
–To av oid lock conversion deadlocks, get a w-lock first
and dow n-grade to an r-lock if you don’t need to write.
–Use SQ L Update statem en t or explicit program hints
2
/
15
/
05 4
C onversions in MS SQ L Server
• U pdate-lock prevents lock conversion d eadlock.
–Conflicts with other update and write locks, but not
with read locks.
–Only on pages and row s (not tab les)
• Y ou get an update lock by using the UPDLOCK
hint in the FR O M clause
Select Foo.A
From Foo (UPDLOCK)
Where Foo.B= 7
2
/
15
/
05 5
Blocking and Lock Thrashing
Throughput
Low
High
# of Active T xns
Low H igh
•The locking perform an ce problem is too much delay
due to blocking
–little delay until locks are saturated
–then major delay, due to the locking bottleneck
–thrashing -the point where throughput decre ases with
increasing load
thrashing
2
/
15
/
05 6
More on Thrashing
•It’s purely a blocking problem
–It happens ev en when the ab ort rate is low
•As num ber of transactions increase
– each additional tran saction is more likely to block
– but first, it gathers som e locks, increasing the
probability others will block (negative feedback )
Docsity.com
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Lock Thrashing - E-Commerce - Lecture Slides and more Slides Fundamentals of E-Commerce in PDF only on Docsity!

2/15/ 05 1

8.Concurrency Control

forTransactions

PartTwo

545 Transaction Processing

2/15/ 05 2

O utline

1.A M odelforConcurrency Control 2.Serializability Theory 3.Synchronization Requirem ents forRecoverability 4.Tw o-Phase Locking 5.Im plem enting Tw o-Phase Locking 6.Locking Perform ance 7.M ultigranularity Locking (revisited) 8.H otSpotTechniques 9.Q uery-U pdate Techniques 10.Phantom s 11.Shared D isk System s 12.B-Trees 13.Tree locking

2/15/ 05 3

8.6 Locking Perform ance

  • D eadlocks are rare
    • up to 1% -2% oftransactions deadlock
  • The one exception to this is lock conversions
    • r-lock a record and laterupgrade to w -lock
    • e.g.,T (^) i = read(x)… w rite(x)
    • if tw o txnsdo this concurrently,they’lldeadlock (both getan r-lock on x before eithergets a w -lock)
    • To avoid lock conversion deadlocks,geta w -lock first and dow n-grade to an r-lock if you don’tneed to w rite.
    • U se SQ L U pdate statem entorexplicitprogram hints

2/15/ 05 4

Conversions in M S SQ L Server

  • U pdate-lock prevents lock conversion deadlock.
    • Conflicts w ith otherupdate and w rite locks,butnot w ith read locks.
    • O nly on pages and row s (nottables)
  • Y ou getan update lock by using the U PD LO CK

hintin the FRO M clause

SelectFoo.A From Foo (U PD LO CK) W here Foo.B = 7

2/15/ 05 5

Blocking and Lock Thrashing

Throughput

Low

H igh

ofA ctive Txns

Low H igh

  • The locking perform ance problem is too m uch delay

due to blocking

  • little delay untillocks are saturated
  • then m ajordelay,due to the locking bottleneck
  • thrashing -the pointw here throughputdecreases w ith increasing load

thrashing

2/15/ 05 6

M ore on Thrashing

  • It’s purely a blocking problem
    • Ithappens even w hen the abortrate is low
  • A s num beroftransactions increase
    • each additionaltransaction is m ore likely to block
    • butfirst,itgathers som e locks,increasing the probability others w illblock (negative feedback)

2

2/15/ 05 7

A voiding Thrashing

  • Ifover30% ofactive transactions are blocked,

then the system is (nearly)thrashing

so reduce the num berofactive transactions

  • Tim eout-based deadlock detection m istakes
    • They happen due to long lock delays
    • So the system is probably close to thrashing
    • So ifdeadlock detection rate is too high (over2% ) reduce the num berofactive transactions

2/15/ 05 8

Interesting Sidelights

  • By getting alllocks before transaction Start,you

can increase throughputatthe thrashing point

because blocked transactions hold no locks

  • Butitassum es you getexactly the locks you need and retries ofget-all-locks are cheap
  • Pure restartpolicy -abortw hen there’s a conflict

and restartw hen the conflictdisappears

  • If aborts are cheap and there’s low contention for otherresources,then this policy produces higher throughputbefore thrashing than a blocking policy
  • Butresponse tim e is greaterthan a blocking policy

2/15/ 05 9

H ow to Reduce Lock Contention

  • Ifeach transaction holds a lock L fortseconds,

then the m axim um throughputis 1/ttxns/second

Start Lock L Com m it t

  • To increase throughput,reduce t(lock holding tim e)
    • Setthe lock laterin the transaction’s execution (e.g.,deferupdates tillcom m ittim e)
    • Reduce transaction execution tim e (reduce path length, read from disk before setting locks)
    • Splita transaction into sm allertransactions 2/15/ 05 10

Reducing Lock Contention (cont’d)

  • Reduce num berofconflicts
    • U se finergrained locks,e.g.,by partitioning tables vertically Part# Price O nH and PartN am eCatalogPage

Part# Price O nH and Part# PartN am eCatalogPage

  • U se record-levellocking (i.e.,selecta database system thatsupports it)

2/15/ 05 11

M athem aticalM odelofLocking

  • N transactions each ow n K /2 locks on average
    • KN /2 in total
  • Each lock requesthas probability K N /2D of

conflicting w ith an existing lock.

  • Each transaction requests K locks,so its probability

ofexperiencing a conflictis K 2 N /2D.

  • Probability ofa deadlock is proportionalto K 4 N /D 2
    • Prob(deadlock)/Prop(conflict)= K 2 /D
    • if K=10 and D = 10^6 ,then K 2 /D =. 0001
  • K locks pertransaction
  • D lockable data item s
  • N transactions
  • T tim e betw een lock requests

2/15/ 05 12

8.7 M ultigranularity Locking (M G L)

  • A llow differenttxnsto lock atdifferentgranularity
    • big queries should lock coarse-grained data (e.g.tables)
    • shorttransactions lock fine-grained data (e.g.row s)
  • Lock m anagercan’tdetectthese conflicts
    • each data item (e.g.,table orrow )has a differentid
  • M ultigranularity locking “trick”
    • exploitthe naturalhierarchy ofdata containm ent
    • before locking fine-grained data,setintention lockson coarse grained data thatcontains it
    • e.g.,before setting a read-lock on a row ,getan intention-read-lock on the table thatcontains the row

4

2/15/ 05 19

D elaying O perations U ntilCom m it

  • D ata m anagerlogs each transaction’s updates
  • O nly applies the updates (and sets locks)after

receiving Com m itfrom the transaction

  • IM S FastPath uses this for
    • D ata Entry D B
    • M ain Storage D B
  • W orks forw rite,insert,and delete,butnotread

2/15/ 05 20

Locking H igher-LevelO perations

  • Read is often partofa read-w rite pair,such as

Increm ent(x,n),w hich adds constantn to x,

butdoesn’treturn a value.

  • Increm ent(and D ecrem ent)com m ute
  • So,introduce Increm entand D ecrem entlocks

r w inc dec r y n n n w n n n n inc n n y y dec n n y y

  • Butif Inc and D ec have a threshold (e.g.a quantity of zero),then they conflict (w hen the threshold is near)

2/15/ 05 21

Solving the Threshold Problem A notherIM S FastPath Technique

  • U se a blind D ecrem ent(no threshold)and

V erify(x,n),w hich returns true ifx ‡ n

  • Re-execute V erify atcom m ittim e
    • If itreturns a differentvalue than itdid during norm al execution,then abort
    • It’s like checking thatthe threshold lock you didn’t setduring D ecrem entis stillvalid.

bEnough = Verify(iQuantity, n); If (bEnough) Decrement(iQuantity, n) else print (“not enough”); 2/15/ 05 22

O ptim istic Concurrency Control

  • The V erify trick is optim istic concurrency control
  • M ain idea -execute operations on shared data

w ithoutsetting locks.A tcom m ittim e,testifthere

w ere conflicts on the locks (thatyou didn’tset).

  • O ften used in client/serversystem s
    • Clientdoes allupdates in cache w ithoutshared locks
    • A tcom m ittim e,try to getlocks and perform updates

2/15/ 05 23

Batching

  • Transactions add updates to a m ini-batch and only

periodically apply the m ini-batch to shared data.

  • Each process has a private data entry file, in addition to a globalshared data entry file
  • Each transaction appends to its process’file
  • Periodically append the process file to the shared file
  • Tricky failure handling
  • Gathering up private files
  • A voiding holes in serialnum berorder

2/15/ 05 24

Partitioning

  • Splitup inventory into partitions
  • Each transaction only accesses one partition
  • Exam ple
    • Each ticketagency has a subsetofthe tickets
    • Ifone agency sells outearly,itneeds a w ay to getm ore tickets from otheragencies (partitions)

5

2/15/ 05 25

8.9 Q uery-U pdate Techniques

  • Q ueries run fora long tim e and lock a lotofdata —

a perform ance nightm are w hen trying also to run

shortupdate transactions

  • There are severalgood solutions
    • U se a data w arehouse
    • A cceptw eakerconsistency guarantees
    • U se m ultiversion data
  • Solutions trade data quality ortim eliness for

perform ance

2/15/ 05 26

D ata W arehouse

  • A data w arehouse contains a snapshotofthe D B

w hich is periodically refreshed from the TP D B

  • A llqueries run on the data w arehouse
  • A llupdate transactions run on the TP D B
  • Q ueries don’tgetabsolutely up-to-date data
  • H ow to refresh the data w arehouse?
    • Stop processing transactions and copy the TP D B to the data w arehouse.Possibly run queries w hile refreshing
    • Treatthe w arehouse as a D B replica and use a replication technique

2/15/ 05 27

D egrees ofIsolation

  • Serializability = D egree 3 Isolation
  • D egree 2 Isolation (a.k.a.cursorstability)
    • D ata m anagerholds read-lock(x)only w hile reading x, butholds w rite locks tillcom m it(asin 2PL)
    • E.g.w hen scanning records in a file,each get-next-record releases lock on currentrecord and gets lock on nextone
    • read(x)is not“repeatable” w ithin a transaction,e.g., rl 1 [x]r 1 [x]ru 1 [x]w l 2 [x]w 2 [x]w u 2 [x]rl 1 [x]r 1 [x]ru 1 [x]
    • D egree 2 is com m only used by ISA M file system s
    • D egree 2 is often a D B system ’s defaultbehavior! A nd custom ers seem to acceptit!!! 2/15/ 05 28

D egrees ofIsolation (cont’d)

  • Could run queries D egree 2 and updaters D egree 3
    • U pdaters are stillserializable w .r.t.each other
  • D egree 1 -no read locks;hold w rite locks to com m it
  • U nfortunately,SQ L concurrency controlstandards

have been stated in term s of“repeatable reads” and

“cursorstability” instead ofserializability,leading

to m uch confusion.

2/15/ 05 29

A N SISQ L Isolation Levels

  • U ncom m itted Read -D egree 1
  • Com m itted Read -D egree 2
  • Repeatable Read -U ses read locks and w rite locks,

butallow s “phantom s”

  • Serializable -D egree 3

2/15/ 05 30

M S SQ L Server

  • Lock hints in SQ L FRO M clause
    • A llthe A N SIisolation levels,plus …
    • U PD LO CK -use update locks instead ofread locks
    • REA D PA ST -ignore locked row s (if running read com m itted)
    • PA GLO CK -use page lock w hen the system w ould otherw ise use a table lock
    • TA BLO CK -shared table lock tillend ofcom m and or transaction
    • TA BLO CKX -exclusive table lock tillend of com m and ortransaction

7

2/15/ 05 37

8.10 Phantom s

  • Problem s w hen using 2PL w ith inserts and deletes

T 1 :Read A ccounts 1,2,and 3 T 2 :InsertA ccounts[4,Tacom a,100] T 2 :Read A ssets(Tacom a),returns 500 T 2 :W rite A ssets(Tacom a,600) T 1 :Read A ssets(Tacom a),returns 600 T 1 :Com m it

A cct# Location Balance Location Total 1 Seattle 400 2 Tacom a 200 3 Tacom a 300

Seattle 400 Tacom a 500

A ccounts A ssets

The phantom record

2/15/ 05 38

The Phantom Phantom Problem

  • Itlooks like T 1 should lock record 4,w hich isn’t

there!

  • W hich ofT 1 ’s operations determ ined thatthere

w ere only 3 records?

  • Read end-of-file?
  • Read record counter?
  • SQ L Selectoperation?
  • This operation conflicts w ith T 2 ’s Insert

A ccounts[4,Tacom a,100]

  • Therefore,InsertA ccounts[4,Tacom a,100]

shouldn’trun untilafterT 1 com m its

2/15/ 05 39

A voiding Phantom s -Predicate Locks

  • Suppose a query reads allrecords satisfying

predicate P.Forexam ple,

  • Select* From A ccounts W here Location = “Tacom a”
  • N orm ally w ould hash each record id to an integerlock id
  • A nd lock controlstructures.Too coarse grained.
  • Ideally,seta read lock on P
  • w hich conflicts w ith a w rite lock Q if som e record can satisfy (P and Q )
  • Forarbitrary predicates,this is too slow to check
  • N otw ithin a few hundred instructions,anyw ay

2/15/ 05 40

Precision Locks

  • Suppose update operations are on single records
  • M aintain a listofpredicate Read-locks
  • Insert,D elete,& U pdate w rite-lock the record and

check forconflictw ith allpredicate locks

  • Q uery sets a read lock on the predicate and check

forconflictw ith allrecord locks

  • Cheaperthan predicate satisfiability,butstilltoo

expensive forpracticalim plem entation.

2/15/ 05 41

8.11 Shared D isk System s

  • U se a version num beron the page and in the lock

Process A

P r 2

Process B

P

r 7

P

  • Can cache a page in tw o processes thatw rite-lock differentrecords
  • O nly one process ata tim e can have w rite privilege
  • U se a globallock m anager
  • W hen setting a w rite lock on P, m ay need to refresh the cached copy from disk (ifanotherprocess recently updated it)

2/15/ 05 42

Shared D isk System

  • W hen a process sets the lock,ittells the lock

m anagerversion num berofits cached page.

  • A process increm ents the version num berthe first

tim e itupdates a cached page.

  • W hen a process is done w ith an updated page,it

flushes the page to disk and then increm ents

version num berin the lock.

8

2/15/ 05 43

Logging

  • Since updates are happening on different

system s,w here is the log?

  • A single log serveris sim plest,butm akes

logging m ore expensive.

  • Be carefulnotto flush to the log until

necessary.

  • This requires locally-assigned LSN s
  • M ustflush the log before flushing an updated page

2/15/ 05 44

8.12 B-Trees

  • A n indexm aps field values to record ids.
    • Record id = [page-id,offset-w ithin-page]
    • M ostcom m on D B index structures:hashing and B-trees
    • D B index structures are page-oriented
  • H ashing uses a function H :V fi B,from field values

to block num bers.

  • V = socialsecurity num bers.B = {1 ..1000} H (v)= v m od 1000
  • If a page overflow s,then use an extra overflow page
  • A t90% load on pages,1.2 block accesses perrequest!
  • BU T,doesn’thelp forkey range access (10 < v < 75)

2/15/ 05 45

B-Tree Structure

K 1 P 1 ... K i Pi K i+1 ...K n- 1 Pn

K ´ 1 P´ 1 ... K ´i P´i K ´i+1...K ´n- 1 P´n

  • Index node is a sequence of[pointer,key]pairs
  • K 1 < K 2 < … < K (^) n- 2 < K (^) n- 1
  • P 1 points to a node containing keys < K (^1)
  • Pi points to a node containing keys in range [K (^) i- 1 ,K (^) i)
  • Pn points to a node containing keys > K (^) n- 1
  • So,K ´ 1 < K ´ 2 < … < K ´n- 2 < K ´n- 1

2/15/ 05 46

Exam ple n= 127 496

  • N otice thatleaves are sorted by key,left-to-right
  • Search forvalue v by follow ing path from the root
  • If key = 8 bytes,ptr= 2 bytes,page = 4K,then n = 409
  • So 3-levelindex has up to 68M leaves ( 4093 )
  • A t20 records perleaf,that’s 136M records

2/15/ 05 47

Insertion

  • To insertkey v,search forthe leafw here v should appear
  • If there’s space on the leave,insertthe record
  • If no,splitthe leafin half,and splitthe key range in its parentto pointto the tw o leaves

19 - -

12 14 17

X

X

To insertkey 15 •splitthe leaf •splitthe parent’s range [0,19) to [0,15)and [15,19) •ifthe parentw asfull,you’d splitthattoo (notshow n here) •this autom atically keeps the tree balanced

2/15/ 05 48

B-Tree O bservations

  • D elete algorithm m erges adjacentnodes < 50% full,

butrarely used in practice

  • Rootand m ostlevel-1 nodes are cached,to reduce

disk accesses

  • Secondary (non-clustered)index -Leaves contain

[key,record id]pairs.

  • Prim ary (clustered)index -Leaves contain records
  • U se key prefix forlong (string)key values
    • drop prefix and add to suffix asyou m ove dow n the tree