Re: Long living and expiring locks? - Mailing list pgsql-general

From Laurenz Albe
Subject Re: Long living and expiring locks?
Date
Msg-id 6b66751bfdf9954404348a60b93959188b620dc9.camel@cybertec.at
Whole thread Raw
In response to Long living and expiring locks?  (Tim Uckun <timuckun@gmail.com>)
List pgsql-general
On Fri, 2022-05-20 at 15:43 +1200, Tim Uckun wrote:
> I have multiple processes connecting to the same database. In order to
> prevent race conditions the I would like the process to  issue a
> SELECT FOR UPDATE  to lock the records that need to be processed.
> 
> The problem is that the locks are not inside of a single translation.
> The process is multi step. Records are selected and presented to the
> user, the user does some stuff and submits a form, the submitted form
> updates those records and frees the lock.
> 
> Ideally I would do a select for update when the form is shown to the
> user but with an expiry time so that if the user decides to move on
> and not submit any changes the locks will expire.
> 
> I could do this with a locked_at field that I can update on select but
> I would prefer to let postgres handle the locks if possible.

The customary solution to this is to use optimistic locking:

During the UPDATE, you check if a concurrent transaction modified
the row since you read it, and if yes, you redo the whole operation.

That could look like:

SELECT id, col_to_change, othercol1, othercol2
FROM tab
WHERE id = 42;

[user interaction]

UPDATE tab
SET col_to_change = 'newvalue'
WHERE id = 42
  AND othercol1 = 'original value'
  AND othercol2 = 'original value';

If the UPDATE modifies no row, something must have changed, and you
redo the whole operation.

The advantage is that you don't have to keep a transaction open.
(Regular) long transactions are a big problem in relational databases.

In PostgreSQL you could use the system columns "ctid" and "xmin"
to check if the row changed, so you don't have to fetch and check
all columns.

Yours,
Laurenz Albe
-- 
Cybertec | https://www.cybertec-postgresql.com



pgsql-general by date:

Previous
From: Dominique Devienne
Date:
Subject: Re: No default for (user-specific) service file location on Windows?
Next
From: Koen De Groote
Date:
Subject: Re: In case of network issues, how long before archive_command does retries