Scrivio Interview library

Locks inside the database

31 questions in 9 subtopics.

Row, page and table locks

ConceptFoundations6 min read
Explain lock granularity in relational databases: row locks, page locks and table locks. Which granularity do PostgreSQL, MySQL InnoDB and SQL Server use for an ordinary UPDATE ... WHERE id = 42, and what is the trade-off between fine and coarse locks?
DebuggingIntermediate8 min read
In MySQL 8.4 with REPEATABLE READ, this statement blocks inserts of new orders by other sessions even though it changes only a few rows:
UPDATE orders
SET status = 'LATE'
WHERE created_at < '2026-01-01' AND status = 'OPEN';
there is no index on created_at or status. Explain why and how you would fix it.
DesignAdvanced6 min read
A multi-tenant SaaS database has one big table per entity shared by all tenants. Large tenants run bulk jobs that lock many rows and slow small tenants. Design changes at the schema, job and platform levels to reduce lock interference between tenants.

Shared and exclusive locks

ConceptFoundations6 min read
What are shared (S) and exclusive (X) locks and their compatibility? In PostgreSQL, why does a plain SELECT not block an UPDATE of the same row, while SELECT ... FOR SHARE does?
DebuggingIntermediate6 min read
In PostgreSQL, inserting order lines (with a foreign key to orders) during a big job that updates orders.status sometimes waits. Another time, a job that updates orders.id-referenced columns blocks all inserts. Explain the lock modes involved and how to avoid the waits.
ScenarioAdvanced6 min read
A reporting team runs long analytical queries against the primary SQL Server database, and the online system sees blocking whenever reports run. The DBA proposes enabling READ_COMMITTED_SNAPSHOT. Explain what changes and what risks you would review before approving.

SELECT FOR UPDATE

CodingFoundations6 min read
Two requests withdraw money from the same account at the same time. Write the SQL and the Spring Data JPA repository method that prevent a lost update with pessimistic locking, and explain how long the lock is held.
DebuggingFoundations6 min read
This query fails in PostgreSQL with 'FOR UPDATE is not allowed with GROUP BY clause':
SELECT customer_id, sum(amount)
FROM invoice
WHERE status = 'OPEN'
GROUP BY customer_id
FOR UPDATE;
Also, a version with a LEFT JOIN to an optional table fails. Explain the rules and how to rewrite.
ScenarioIntermediate6 min read
A reservation service does SELECT ... FOR UPDATE on a seat row, then calls a payment provider over HTTP, then updates the seat and commits. Under load, connections run out and p99 latency goes to 30 seconds. Explain the problem and redesign the flow.
DesignPrincipal6 min read
Pessimistic locking, optimistic locking with versions, and lock-free designs (append-only events, conditional writes, CRDTs) all exist. Thinking about the next decade of your company's systems, how would you guide the choice of concurrency control strategy for new domains?

SKIP LOCKED and queue tables

CodingFoundations6 min read
Write the SQL a worker uses to take up to 10 pending jobs from a jobs(id, status, run_at, payload, locked_by, locked_at) table in PostgreSQL so that several workers never take the same job and never wait for each other.
DebuggingIntermediate6 min read
A PostgreSQL queue table processes a million jobs a day. After a few weeks, claiming a job takes 2 seconds instead of 2 milliseconds, although only a few hundred rows are PENDING. What is going on and how would you fix it?
DesignAdvanced6 min read
Teams want to use PostgreSQL tables as queues for outbox events and background jobs instead of running Kafka or RabbitMQ. As the architect, when would you approve it, and what design rules would you require?
LeadershipPrincipal6 min read
A decade ago your company built its own job and messaging system on top of database tables. It now runs thousands of job types and is critical, but only two engineers understand it. How would you decide whether to keep, rebuild or replace it?

Lock escalation

ConceptFoundations6 min read
What is lock escalation, which databases do it, and why does PostgreSQL not escalate row locks? What symptom would you see in SQL Server when it happens?
ScenarioIntermediate6 min read
A nightly SQL Server job deletes 2 million old rows with one DELETE statement, and during that time the online order API times out on the same table. Explain why and how you would rewrite the job.

Deadlock detection and victims

DebuggingFoundations6 min read
Two transactions run at the same time. T1:
UPDATE account
SET balance = balance - 10
WHERE id = 1;
UPDATE account
SET balance = balance + 10
WHERE id = 2;
T2 does the same transfer in the opposite direction (id 2 first, then id 1). Sometimes one fails with 'deadlock detected'. Explain and fix it.
DebuggingIntermediate7 min read
MySQL reports frequent deadlocks between two INSERT statements into the same table under REPEATABLE READ, even though they insert different rows. SHOW ENGINE INNODB STATUS mentions 'lock_mode X locks gap before rec insert intention waiting'. Explain the mechanism and the options.
LeadershipAdvanced6 min read
Deadlock errors across your 60 services are rising, and each team handles them differently: some retry forever, some fail the request, some catch and ignore. Write the engineering standard you would publish.
LeadershipPrincipal6 min read
Most locking problems your company has suffered came from application design, not from the database: long transactions, remote calls inside them, and missing indexes. How would you change how the organisation learns and designs, so these problems stop repeating across teams?

Advisory locks

ConceptFoundations6 min read
What are PostgreSQL advisory locks? Explain pg_advisory_lock, pg_try_advisory_lock and pg_advisory_xact_lock, and give one use case where they are better than a row lock.
DebuggingIntermediate6 min read
A Spring Boot service uses session-level pg_advisory_lock to make one pod run a nightly job. Behind PgBouncer in transaction pooling mode, two pods sometimes run the job together, and other times the lock is never released. Explain why.
DesignAdvanced7 min read
Several teams use the main PostgreSQL database for distributed locking (advisory locks, lock tables, SELECT FOR UPDATE on a dummy row) to coordinate jobs across pods. Others use Redis or ZooKeeper. What standard would you set for distributed locks and why?
LeadershipPrincipal6 min read
Over the years, engineers have built many ad hoc coordination mechanisms on top of databases (advisory locks, flag rows, polling tables). A new platform team proposes replacing them all with a workflow engine. How would you assess the proposal?

Lock timeouts

ConceptFoundations7 min read
Explain lock_timeout, statement_timeout and idle_in_transaction_session_timeout in PostgreSQL, and innodb_lock_wait_timeout in MySQL. How do you set them for a Spring Boot service using HikariCP?
ScenarioIntermediate7 min read
An analyst's session opened a transaction in a SQL tool, ran an UPDATE on a customer row, and went to lunch. The order API now times out for that customer and the pool is exhausted. Walk through how you find the blocker, resolve it, and prevent it happening again.
LeadershipAdvanced7 min read
After several outages caused by lock waits, you are asked to define timeouts across the stack: client, gateway, service, connection pool, transaction and database locks. How would you set and govern them across 100 services?

Locks taken by DDL

DebuggingFoundations7 min read
In PostgreSQL, ALTER TABLE orders ADD COLUMN note text; normally finishes in milliseconds, but during a deploy it hung and all queries on orders stopped for minutes. Explain why.
CodingIntermediate7 min read
You must add an index and a NOT NULL foreign key column to a 500 GB PostgreSQL table that serves traffic around the clock. Write the migration steps that avoid long blocking locks, and note which steps cannot run inside a transaction.
DesignAdvanced7 min read
Design a schema change process for 80 services and 30 databases (PostgreSQL and MySQL) that allows deploying several times a day without outages caused by DDL locks.
LeadershipPrincipal7 min read
Your largest databases have grown to tens of terabytes, and every schema change is now a planned event with risk of outage. What long-term strategy would you set for schema evolution, data ownership and database size to keep change safe?