473,837 Members | 1,741 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

select for update & lock contention


I think I'm seeing table-level lock contention in the following function
when I have many different concurrent callers, each with mutually distinct
values for $1. Is there a way to reimplement this function using
select-for-update (or equivalent) in order to get a row-level lock (and
thus less contention) while maintaining the function interface? The docs
seem to suggest so, but it's not clear how to return the SETOF queued_item
and also use select-for-update to get the row-level locks. TIA.

CREATE OR REPLACE FUNCTION getqueuedupdate s (character)
RETURNS SETOF queued_item AS '
DECLARE
rows record;
BEGIN
FOR rows IN SELECT * FROM queued_item where subscriber=$1 LOOP
RETURN NEXT rows;
DELETE FROM queued_item WHERE key=rows.key;
END LOOP;
RETURN;
END;'
LANGUAGE plpgsql;

---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 23 '05 #1
4 4095
This is on 7.3.4/7.3.6. Thx.

On Wednesday May 5 2004 10:42, Ed L. wrote:
I think I'm seeing table-level lock contention in the following function
when I have many different concurrent callers, each with mutually
distinct values for $1. Is there a way to reimplement this function
using select-for-update (or equivalent) in order to get a row-level lock
(and thus less contention) while maintaining the function interface? The
docs seem to suggest so, but it's not clear how to return the SETOF
queued_item and also use select-for-update to get the row-level locks.
TIA.

CREATE OR REPLACE FUNCTION getqueuedupdate s (character)
RETURNS SETOF queued_item AS '
DECLARE
rows record;
BEGIN
FOR rows IN SELECT * FROM queued_item where subscriber=$1 LOOP
RETURN NEXT rows;
DELETE FROM queued_item WHERE key=rows.key;
END LOOP;
RETURN;
END;'
LANGUAGE plpgsql;

---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 23 '05 #2
On Wednesday May 5 2004 10:42, Ed L. wrote:
I think I'm seeing table-level lock contention in the following function
when I have many different concurrent callers, each with mutually
distinct values for $1. Is there a way to reimplement this function
using select-for-update (or equivalent) in order to get a row-level lock
(and thus less contention) while maintaining the function interface? The
docs seem to suggest so, but it's not clear how to return the SETOF
queued_item and also use select-for-update to get the row-level locks.
TIA.

CREATE OR REPLACE FUNCTION getqueuedupdate s (character)
RETURNS SETOF queued_item AS '
DECLARE
rows record;
BEGIN
FOR rows IN SELECT * FROM queued_item where subscriber=$1 LOOP
RETURN NEXT rows;
DELETE FROM queued_item WHERE key=rows.key;
END LOOP;
RETURN;
END;'
LANGUAGE plpgsql;


I should also mention what leads me to suspect lock contention. First, the
table is frequently vacuum analyzed, so I'm reasonably confident its not a
planner stats issue. Second, the table usually contains a small number of
rows (tens to a couple hundred), so I reason its unlikely that a planner
issue would slow it down much. Third, I have put in "RAISE NOTICE"
statements before and after each statement in the function, and can see the
stalls of several seconds in the server log within the deleting loop.

So, I tried to get a less conflicting lock by using SELECT FOR UPDATE as
follows with the "PERFORM" line (syntax corrections welcome; contextual
examples of how to do this were not plentiful on google or docs)...

CREATE OR REPLACE FUNCTION getqueuedupdate s (character)
RETURNS SETOF queued_item AS '
DECLARE
rows record;
BEGIN
-- obtain row-level locks...
PERFORM * FROM queued_item WHERE subscriber = $1 FOR UPDATE OF
queued_item;
FOR rows IN SELECT * FROM queued_item where subscriber=$1 LOOP
RETURN NEXT rows;
DELETE FROM queued_item WHERE key=rows.key;
END LOOP;
RETURN;
END;'
LANGUAGE plpgsql;
Then I watched the locks with the following command, which I think basically
shows which backends are locking which tables in which modes from which SQL
statements:

while test 1; do psql -c "select now(), d.datname||':'| |r.relname as table,
l.transaction as xact, l.pid, l.mode, l.granted,
pg_stat_get_bac kend_activity(S .backendid) AS sql from pg_locks l, pg_class
r, pg_database d, (SELECT pg_stat_get_bac kend_idset() AS backendid) AS S
where l.relation = r.oid and l.database = d.oid and d.datname = 'testdb'
and r.relname = 'queued_item' and pg_stat_get_bac kend_pid(S.back endid) =
l.pid and d.oid = pg_stat_get_bac kend_dbid(S.bac kendid)"; sleep 1; done
And with that command above, I notice several things leading to other
questions:

1) I can now see the lock modes for the function's delete statements have
changed from RowExclusiveLoc k (a table-level lock?) to RowShareLock (a
row-level lock, a good thing).

2) The contention appears to continue. I am now wondering if my assumption
that RowShareLock would reduce contention over RowExclusiveLoc k is sound in
such a case where you have multiple writers with each deleting a distinct
set of rows (one set per subscriber)...? What else could explain the
delays I see in the delete loop?

3) This table is populated by INSERT triggers on other tables; each of
those inserts results in N triggered INSERTs into queued_item, one insert
for each of N subscribers. Given I also see the RowExclusiveLoc k mode from
those inserts, I'm also wondering if those inserts aren't momentarily
blocking the delete statements in the function above? The 7.3.4 docs
(http://www.postgresql.org/docs/7.3/s...LOCKING-TABLES)
seem to me to suggest RowExclusiveLoc k will not interfere with
RowShareLock, but the modes seen above and the modes in the docs leave room
for doubt.

One last thought: This table does at times have a fairly high volume of
rows being inserted and then quickly deleted (as much as 100
inserts/deletes per second). So the volume of change is large, but the
number of rows present remains in flux within a range of maybe 0-1000.
Vaccuum/analyze is done via autovacuum maybe every 5-20 minutes, so I guess
the planner could be out of touch with actual index distributions.

Idears?

TIA.
---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 23 '05 #3
"Ed L." <pg***@bluepolk a.net> writes:
I think I'm seeing table-level lock contention in the following function


I think you're barking up the wrong tree entirely. There's nothing in
that function that would acquire a conflicting table lock.

I'm wondering about foreign key lock contention, myself. Look to what
the DELETE must do.

regards, tom lane

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 23 '05 #4
On Thursday May 6 2004 6:11, Tom Lane wrote:
"Ed L." <pg***@bluepolk a.net> writes:
I think I'm seeing table-level lock contention in the following
function


I think you're barking up the wrong tree entirely. There's nothing in
that function that would acquire a conflicting table lock.

I'm wondering about foreign key lock contention, myself. Look to what
the DELETE must do.


We've dropped all foreign key constraints on the queued_item table and moved
the delete out of the loop as follows...
DECLARE
rows record;
BEGIN
PERFORM * FROM queued_item WHERE subscriber = $1 FOR UPDATE OF
queued_item;
RAISE NOTICE 'getupdates(%): going to call select', $1;
FOR rows IN SELECT * FROM queued_item where subscriber=$1 LOOP
RAISE NOTICE 'getupdates(%): in select loop, returning %', $1,
rows.key;
RETURN NEXT rows;
END LOOP;
RAISE NOTICE 'getupdates(%): going to call delete', $1;
DELETE FROM queued_item WHERE subscriber = $1;
RAISE NOTICE 'getupdates(%): done calling delete', $1;
RETURN;
END;
So the delete seems a non-factor. The delay is now occurring inside the
loop, sometimes for 4-8 seconds. During this delay, it is possible that
other triggers are inserting into the queued_item table. Other ideas as to
what is going on?

TIA.
---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3848
by: jayson_13 | last post by:
Hi, I need to implement a counter and i face problem of locking so hope that u guys can help me. I try to do test like this : 1st connection SELECT * FROM nextkey WHERE tblname = 'PLCN' FOR Update; (when i execute this statement and i guess that this will lock the
7
9152
by: Paul Serby | last post by:
Why does '*select count(id) from "tblContacts"'* do a sequential scan when the field '*id*' is indexed using a btree? MySql simply looks at the index which is keeping a handy record of the number of rows. Can anybody explain how and why postgres does this query like it does? Many thanks
18
3332
by: Frank Rizzo | last post by:
Hello, I have a class with all static methods that is called by multiple threads. I was wondering what effect that has on the competing threads. Does Thread2 have to wait until Thread1 is done with the StaticClass.Method1 before it can use it? What if I removed static methods and made all the threads instantiate its own copy of the class? Would that remove the waiting contention?
5
4070
by: Bob Bins | last post by:
Is there a way to create a shared lock using the Monitor class or any other synchronization class in .NET? So I have one resource that may have multiple threads using it at once but a second thread that when called must have exclusive access and cause the other threads to wait. I can't figure out how to do this with .Net. Thanks.
4
9609
by: pike | last post by:
DB2 UDB 8.1 FP7 We are getting intermittent deadlocks (911 RC 2) even when U row-lock has been secured. The transaction is as follows: 1) Select current application number value from table. To guarantee uniqueness of the application number SELECT FOR UPDATE statement is used. 2) Calculate new application number value.
19
8388
by: Steve | last post by:
ASP error number 13 - Type mismatch with SELECT...FOR UPDATE statement I got ASP error number 13 when I use the SELECT...FOR UPDATE statement as below. However, if I use SELECT statement without FOR UPDATE, it is fine and no error. I also tried Set objRs = objConn.Execute("SELECT * FROM EMP UPDATE OF EMPNO"), but it still couldn't help. any ideas? I tried to search in the web but couldn't find similar
17
2005
by: djc | last post by:
I got great info on related question previously. This link <http://www.yoda.arachsys.com/csharp/threads/volatility.shtml> from Brian Gideon was especially informative. 1) the lock statement does *not* make the processor finish all code in the code block before giving another thread from your process a slice of processor time, it only makes sure other threads cannot run the same code *if* they also adhere to the same lock object....
0
1798
by: PeterC | last post by:
We're getting numerous deadlocks in a multi-user system where users are coming in and updating their own data. In our troubleshooting/traces, the deadlocks seem to be coming from lock contention on a Primary Key Clustered Index, not on the table itself. Also, from what we can see, the application is requesting multiple locks on the Primary Key Index as it proceeds to perform the update on the primary table. Can anybody shed some light...
5
13539
by: sticky | last post by:
Hi I need to be able to lock a table against INSERT and UPDATE, but not SELECT, for the duration of a transaction. The transaction will be defined at the application level in c#, and then use stored procedures to make multiple selects and then an insert. What is the best way of doing this? Description of the system:
0
9846
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9683
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10883
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10579
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10633
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7814
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5674
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4479
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3126
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.