Suppose there’s a multi-tenant application where users can create some kind of documents with basic structure like
CREATE TABLE users (id SERIAL PRIMARY KEY, email TEXT);
CREATE TABLE documents (
id SERIAL PRIMARY KEY
, document_id INT NOT NULL
, user_id INT NOT NULL
, text TEXT);
For each user document_id
starts with 1 and increases preferably with gaps being a rare occurrence. The obvious solution is to create a sequence for each user get the document_id
from there. But according to this databases don’t behave well when there are lots of relations there. Another solution is to store next_document_id
in users
table and update it as necessary, but that means the lock on this row will be highly contested slowing simultaneous transactions from the same user. Any other ideas?