Re: Efficiently advancing a sequence without risking it going backwards.

From: Jeremy Schneider <schneider(at)ardentperf(dot)com>
To: Paul McGarry <paul(at)paulmcgarry(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Efficiently advancing a sequence without risking it going backwards.
Date: 2020-07-09 16:59:11
Message-ID: F83A0107-9919-47EA-9C1A-B00C03BEEC4B@ardentperf.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


> On Jul 6, 2020, at 19:06, Paul McGarry <paul(at)paulmcgarry(dot)com> wrote:
>
> I don't think I can use setval(), because it risks making sequences go backwards, eg:
>
> 1) Check values
> DB1sequence: 1234
> DB2sequence: 1233 (1 behind)
> 2) setval('DB2sequence',1234);
>
> but if between (1) and (2) there are 2 nextval(DB2sequence) calls on another process, (2) would take the sequence back from 1235 to 1234 and I would end up trying to create a duplicate key ID from the sequence.

An ability to “lock” the sequence momentarily would give you the tool you need, but I don’t think it’s there.

Total hack, but if your application or users can retry when the rare error is encountered then one idea is to rename the sequence momentarily while you do the setval() then rename it back. Do an initial check without renaming, then re-check after renaming and before the setval() call.

If you put retry logic into your application then make sure to include back-off logic so you don’t get an outage induced by thundering herd.

-Jeremy

Sent from my TI-83

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2020-07-09 19:36:10 Re: Is this a bug in pg_current_logfile() on Windows?
Previous Message Laurent FAILLIE 2020-07-09 15:47:02 Re: Clustering solution ?