[PostgreSQL] sequence 대신에 max(pk) + 1 을 쓰면 안되는 이유

식빵·2023년 5월 3일
0

postgresql-memo

목록 보기
16/34
post-thumbnail

sequence 대신 select max(pk)+1 을 사용하는 방식이 왜 위험한지를 잘 설명해주는
글이 있어서 퍼왔습니다. (출처: https://qr.ae/pyTBa3)

Question :

why shouldn't one select max (primary key column) instead of using an id column or sequence?

Answer :

The most important reason is that two clients could both select
max(primary_key)+1 at almost the same exact instant, 
both get the same result, and both try to use the same value in 
their subsequent insert statement. One will execute their insert first,
and then the other will fail, because they're trying to insert a primary key
value that now exists in the table. This is called a race condition.

To avoid this, you would have to do the following steps for every insert:

Lock the entire table
Select max(primary_key)+1
Insert new row
Release your table lock (maybe not until the end of your transaction)

In an environment where you want multiple concurrent clients inserting 
rows rapidly, this keeps the table locked for too long. 
Clients queue up against each other, waiting for the table lock. 
You end up having a bottleneck in your application.

Auto-increment mechanisms work differently:

Lock the auto-increment generation object
Get the next id
Release the auto-increment lock
Insert new row using the id your thread just generated

The auto-increment generator is also a single resource that the threads are
contending for, but the usage of it is extremely brief, and is released
immediately after the id is generated, instead of persisting 
until the end of the transaction.

Using auto-increment features allows for greater scalability -- i.e. 
more concurrent clients inserting rows to the same table without queueing unnecessarily.

You said your superior doesn't think there will be a lot of users inserting rows. 
But it doesn't take a lot of users, it only takes two -- if they're close together.
There's an old saying about the likelihood of rare occurrences: one in a million is next Tuesday.

Besides, you haven't described any legitimate reason not to use an auto-increment.
profile
백엔드를 계속 배우고 있는 개발자입니다 😊

0개의 댓글