Quick revision
The short answer
We reduce lock interference by keeping each lock small, short and inside one tenant's rows. At the job level, bulk work runs in small key-range batches with short transactions, limited concurrency per tenant and strict lock and statement timeouts. At the schema level, indexes lead with tenant_id so locks stay inside one tenant, and partitioning or moving the largest tenants to their own schema or database isolates both locks and I/O, with per-tenant lock monitoring to find noisy neighbours.
What to remember
In this answer, we saw that lock interference between tenants comes from big transactions, locks that reach beyond one tenant's rows, and shared resources. Small key-range batches with short transactions limit lock duration, indexes and keys that start with tenant_id keep locks inside a tenant, partitioning and separate schemas or databases isolate the largest tenants, and per-tenant concurrency limits, timeouts and lock-wait monitoring keep it that way.
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.
We reduce lock interference by keeping each lock small, short and inside one tenant's rows. At the job level, bulk work runs in small key-range batches with short transactions, limited concurrency per tenant and strict lock and statement timeouts. At the schema level, indexes lead with tenant_id so locks stay inside one tenant, and partitioning or moving the largest tenants to their own schema or database isolates both locks and I/O, with per-tenant lock monitoring to find noisy neighbours.
Why this question is asked
Shared-table multi-tenancy is the cheapest way to run a SaaS product, and it works well until one customer's monthly import starts slowing down everyone else. Interviewers ask this design question because the answer has to span three layers: how the database locks rows, how jobs are written, and how the platform protects tenants from each other. In this answer, we will recap why big tenants hurt small ones, then go through the job changes, the schema changes, the platform guard rails and the monitoring, and finish with when a tenant deserves its own database.
1Why One Tenant's Job Slows the Others
In a shared-table design, every tenant's rows live in the same tables, told apart by a tenant_id column. A bulk job for a large tenant might update 3 million invoice rows in one transaction. While it runs, it holds row locks on all of them, and depending on the database and the indexes, it may lock far more than that: in MySQL under REPEATABLE READ, a search that is not narrowed by an index locks every row it reads, and in SQL Server enough row locks escalate to a whole-table lock.
Small tenants then feel it in three ways. Their writes wait for locks on shared structures or neighbouring rows, their reads wait in databases where readers take locks, and everyone competes for the same I/O, buffer cache and connection pool. The fix is not one setting but a set of rules at each level, so that a lock taken for tenant A can never cover tenant B's rows and never lasts long.
2Job Level: Small Batches and Short Transactions
The most effective change is in the jobs themselves. Instead of one transaction for 3 million rows, the job walks the tenant's rows by primary key in batches of, say, 2,000, committing after each batch. Each transaction then holds about 2,000 row locks for about 50 milliseconds, and any other session waits for at most one batch. The job also becomes resumable: it records the last key it finished, so a restart continues where it stopped.
Notice that the batch query and the update both filter on tenant_id. That is what makes the next rule, about indexes, pay off.
3Schema Level: Indexes and Partitions That Respect Tenants
Locks are taken on what the database reads, so the indexes decide how far a lock reaches. If queries filter on tenant_id, the indexes they use should start with tenant_id, for example (tenant_id, status, due_date) instead of (status, due_date). Then a search for one tenant reads, and locks, only that tenant's index range. A primary key of (tenant_id, id) does the same for range scans by key, and also keeps one tenant's rows physically close together.
The next step is partitioning. In PostgreSQL we can partition a table by list or hash of tenant_id, so a big tenant gets its own partition and its maintenance, vacuum and bulk deletes stay there. Beyond that, the largest tenants can move to their own schema or their own database. That isolates locks completely and also isolates I/O and buffer cache, which partitioning alone does not.
| Option | Isolates | Cost |
|---|---|---|
| Indexes lead with tenant_id | row and range locks | index design work only |
| Batches, timeouts, per-tenant limits | lock duration and concurrency | job framework changes |
| Partition by tenant or tenant group | locks, vacuum, bulk deletes | partition management, query planning care |
| Schema per large tenant | locks and catalog objects | migrations run per schema |
| Database per large tenant | locks, I/O, cache, connections | more servers, routing, upgrades |
4Platform Level: Scheduling, Timeouts and Fair Limits
Even good jobs need guard rails, because the next team will write a new one. The job framework should limit concurrency per tenant, for example at most two bulk workers per tenant and twenty in total, so a large tenant cannot take every worker. Heavy jobs should be scheduled in the tenant's own quiet hours, which differ by time zone, rather than all at 2 a.m. server time.
Timeouts turn a hidden wait into a fast, visible failure. In PostgreSQL, the job's sessions can run with lock_timeout = '2s' and statement_timeout = '30s', set per role (ALTER ROLE batch_jobs SET lock_timeout = '2s') so every job gets it by default. Online traffic can have even shorter lock timeouts. A job that hits a lock timeout simply retries the batch a little later, which is cheap because the batch is small.
5Monitoring Lock Waits per Tenant
To know which tenants cause trouble, we need lock waits labelled by tenant. The simplest way is to put the tenant in the session's application_name or in a query comment, then sample the blocking chains.
Sampling this every few seconds into a metric gives us lock wait time per blocking tenant. In MySQL, performance_schema.data_lock_waits joined with the threads table gives the same picture. Once we see that tenant 12 causes most waits, we can decide on data rather than complaints whether it is time to move it out.
6Follow-up questions
When is a database per tenant worth its operational cost?
It pays off for tenants that are large enough to dominate shared resources, that have contractual isolation or data residency needs, or whose workload is very different from the rest. The cost is real: more servers to patch and back up, migrations run hundreds of times, connection routing, and cross-tenant reporting becomes harder. A common middle path is a pool model for small tenants and dedicated databases for the top few, with tooling that can move a tenant between them.
Does row-level security help with locking?
No. Row-level security in PostgreSQL filters which rows a tenant can see, which is a security feature, but locks are still taken on whatever rows the query reads. Indexes that start with tenant_id are what keep a query, and therefore its locks, inside one tenant's rows.
Why not just raise the lock timeouts so jobs never fail?
Longer timeouts hide the problem: small tenants' requests wait longer instead of failing fast, connection pools fill, and latency spreads to unrelated endpoints. Short timeouts with small retryable batches keep the online system responsive and make contention visible in metrics.
7Conclusion
In this answer, we saw that lock interference between tenants comes from big transactions, locks that reach beyond one tenant's rows, and shared resources. Small key-range batches with short transactions limit lock duration, indexes and keys that start with tenant_id keep locks inside a tenant, partitioning and separate schemas or databases isolate the largest tenants, and per-tenant concurrency limits, timeouts and lock-wait monitoring keep it that way.
Open with
I'd attack it at three levels. First the jobs: no bulk job should hold locks on millions of rows in one transaction. I'd rewrite them to walk the tenant's rows by key in batches of a couple of thousand, commit each batch, record progress so they can resume, and throttle on replica lag.
Then, if they want more
That alone turns minute-long locks into fifty-millisecond ones. Second the schema: locks follow what a query reads, so indexes used by tenant queries should start with tenant_id, and the primary key can be tenant_id plus id. That keeps a tenant's locks inside its own key range.
For the biggest tenants I'd partition by tenant or tenant group, and for the very largest consider a separate schema or database, which also isolates I/O and cache.
Third the platform: the job framework limits concurrency per tenant, schedules heavy work in each tenant's quiet hours, and job roles get lock_timeout and statement_timeout by default, so a blocked batch fails fast and retries.
Finally I'd measure lock waits per blocking tenant by putting the tenant in application_name and sampling pg_blocking_pids, so moving a tenant out is a decision based on data.
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 "A multi-tenant SaaS database has one big table per entity shared by all tenants. Large...": https://scrivio-interview-library.netlify.app/databases/database-locking/472f684df3/