Quick revision
The short answer
Each order line insert checks its foreign key by locking the parent orders row FOR KEY SHARE. A job that updates only orders.status takes FOR NO KEY UPDATE, which is compatible, so normally nothing waits; inserts wait when the job takes FOR UPDATE instead, either through an explicit SELECT ... FOR UPDATE or by updating a referenced key or unique column. The fix is to lock with FOR NO KEY UPDATE, never update key columns, and keep the job's transactions short.
What to remember
In this answer, we saw that a child insert locks its parent row FOR KEY SHARE, which conflicts only with FOR UPDATE. A job that updates non-key columns takes FOR NO KEY UPDATE and never blocks inserts, but explicit SELECT ... FOR UPDATE, updates of referenced or unique key columns, and deletes all take FOR UPDATE and make inserts wait. pg_stat_activity, pg_blocking_pids and pg_locks show who waits for whom, and the fix is the weaker lock mode, immutable keys and short batches.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Each order line insert checks its foreign key by locking the parent orders row FOR KEY SHARE. A job that updates only orders.status takes FOR NO KEY UPDATE, which is compatible, so normally nothing waits; inserts wait when the job takes FOR UPDATE instead, either through an explicit SELECT ... FOR UPDATE or by updating a referenced key or unique column. The fix is to lock with FOR NO KEY UPDATE, never update key columns, and keep the job's transactions short.
Why this question is asked
Foreign keys are one of the places where application code takes locks without asking for them, and the resulting waits look random until we know the lock modes. Interviewers ask this because it tests whether we can connect an innocent INSERT to a batch job through the parent row, and whether we know PostgreSQL's finer row lock modes. In this answer, we will recap how a foreign key check locks the parent, see why a status update normally does not conflict, find the two ways the job ends up blocking inserts, diagnose it with pg_locks and pg_blocking_pids, and then fix it.
1A Quick Recap of the Foreign Key Check
order_line.order_id references orders.id. When we insert an order line, PostgreSQL must guarantee that the parent order exists when we commit. Checking once is not enough, because another session could delete the order a moment later. So the check, which runs as an internal trigger, locks the parent row with FOR KEY SHARE, the weakest of PostgreSQL's four row lock modes. It means: the key of this row must not change and the row must not be deleted until my transaction ends.
The other modes, from strongest to weakest, are FOR UPDATE, FOR NO KEY UPDATE and FOR SHARE. FOR KEY SHARE conflicts only with FOR UPDATE. That one fact explains both behaviours in the question.
2Why a Status Update Normally Does Not Block Inserts
An ordinary UPDATE that changes only non-key columns, such as status, takes FOR NO KEY UPDATE on each row it changes. That mode conflicts with FOR SHARE and stronger, but not with FOR KEY SHARE. So while the big job holds its locks on thousands of orders, inserts of order lines for those same orders still pass their foreign key check without waiting.
| Job statement | Lock on orders row | Child insert |
|---|---|---|
| UPDATE orders SET status = ... | FOR NO KEY UPDATE | no wait |
| SELECT ... FOR NO KEY UPDATE | FOR NO KEY UPDATE | no wait |
| SELECT ... FOR UPDATE | FOR UPDATE | waits until job commits |
| UPDATE orders SET id = ... or a unique column | FOR UPDATE | waits until job commits |
| DELETE FROM orders ... | FOR UPDATE | waits, then fails if row gone |
3When the Waits Appear
The first case is the job that sometimes waits. The usual cause is an explicit lock. Many jobs read rows with SELECT ... FOR UPDATE before updating them, often through JPA with LockModeType.PESSIMISTIC_WRITE, which Hibernate typically renders as FOR UPDATE on PostgreSQL (check the SQL your version logs). FOR UPDATE is the strongest mode, so it conflicts with FOR KEY SHARE, and every child insert for a locked order waits until the job commits. It happens only sometimes because it needs an insert for an order that the job has locked at that moment.
The second case is the job that blocks all inserts. Updating a column that has a unique index usable by a foreign key, such as orders.id or an order_number referenced by another table, takes FOR UPDATE even when the value does not really change in a way that matters to us. If that job touches many orders in one transaction, nearly every insert hits a locked parent. Deleting orders has the same effect.
4Diagnosing the Wait
We confirm the cause by looking at the waiting session, its blocker, and the lock modes involved. pg_stat_activity shows wait_event_type = 'Lock' and a wait_event such as 'tuple' or 'transactionid' for row lock waits. pg_blocking_pids(pid) gives the sessions in the way, and pg_locks shows the modes each holds and requests.
Row locks are stored in the rows, not in pg_locks, so the waiter often appears as waiting on the blocker's transaction id. The blocker's query and its xact_start, the time its transaction began, tell us which job statement and how long it has been holding the locks. The pgrowlocks extension can show the mode stored on a specific row if we need to be sure.
5Fixing It
The first fix is to take the lock the job really needs. If the job locks rows only to update non-key columns, SELECT ... FOR NO KEY UPDATE gives the same protection against concurrent updates and does not block foreign key checks. Even simpler, a single UPDATE ... WHERE status = 'PAID' locks the rows itself with FOR NO KEY UPDATE, so the separate SELECT may be unnecessary.
The second fix is a design rule: never update primary key or referenced key values. Keys should be immutable; if a business number can change, it should not be the referenced column. And if the job must touch referenced keys or delete parents, it should do so in small batches with short transactions, so inserts wait milliseconds rather than minutes. A lock_timeout on the API's sessions, for example 2 seconds, keeps a rare wait from becoming a pile-up of requests.
6Follow-up questions
Why does PostgreSQL treat an update of a unique column as a key update?
A foreign key can reference any column set with a unique constraint or unique index, not only the primary key. PostgreSQL does not look up whether a foreign key actually references that column, so it takes FOR UPDATE for any update that changes a column covered by such a unique index. Partial and expression indexes are not counted, because a foreign key cannot use them.
Does an index on order_line.order_id matter here?
Not for the insert's lock, which is taken on the parent row. It matters a lot for the reverse direction: deleting an order or changing its key makes PostgreSQL search order_line for referencing rows, and without an index on order_id that is a full scan of order_line for every parent row, which makes the job's transaction, and its locks, last much longer.
How do I find out what Hibernate sends for PESSIMISTIC_WRITE?
Turn on SQL logging (for example the org.hibernate.SQL logger at debug) and run the repository method in a test against PostgreSQL. The logged statement ends with the lock clause the dialect chose. If it is FOR UPDATE and we only update non-key columns, a native query with FOR NO KEY UPDATE is an option.
7Conclusion
In this answer, we saw that a child insert locks its parent row FOR KEY SHARE, which conflicts only with FOR UPDATE. A job that updates non-key columns takes FOR NO KEY UPDATE and never blocks inserts, but explicit SELECT ... FOR UPDATE, updates of referenced or unique key columns, and deletes all take FOR UPDATE and make inserts wait. pg_stat_activity, pg_blocking_pids and pg_locks show who waits for whom, and the fix is the weaker lock mode, immutable keys and short batches.
Open with
The insert's foreign key check locks the parent order FOR KEY SHARE, which only guarantees the key won't change or disappear. A normal UPDATE of orders.status takes FOR NO KEY UPDATE, and those two modes don't conflict, so usually nothing waits.
Then, if they want more
FOR KEY SHARE conflicts only with FOR UPDATE. So the occasional waits mean the job sometimes holds FOR UPDATE on a parent, most likely because it reads with SELECT ... FOR UPDATE, or a JPA PESSIMISTIC_WRITE that renders as that, and an insert for one of those orders waits until the job commits.
The job that blocks everything is updating a column with a unique index a foreign key can use, like the id, which PostgreSQL treats as a key update and locks FOR UPDATE, across many rows in one long transaction. I'd confirm it in pg_stat_activity, with wait_event_type Lock and pg_blocking_pids pointing to the job's pid and its xact_start.
To fix it I'd change the explicit lock to FOR NO KEY UPDATE or just let the UPDATE lock the rows, keep keys immutable, and run the job in small batches with short transactions, with a lock_timeout on the API side.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "In PostgreSQL, inserting order lines (with a foreign key to orders) during a big job...": https://scrivio-interview-library.netlify.app/databases/database-locking/2618b31223/