Scrivio Interview library
ScenarioAdvanced6 min read · updated 12 November 2026

A runaway query from one service locked up a shared database for 20 minutes. What timeout and hint policies would you introduce across services?

We would require a query timeout on every user-facing query, through hints or a default per data source, and set a statement timeout such as PostgreSQL's statement_timeout on each service's database user as a backstop that no code can forget. Lock timeouts stop writers from waiting forever behind a lock, comments and application names make every query traceable to its service, and heavy queries get reviewed, with reports moved to read replicas.

Why this question is asked

A single runaway query can take down every service that shares a database: it holds locks, saturates disk and CPU, and lets connection pools everywhere fill up with waiting requests. After an incident like this, the useful question is not who wrote the query but why nothing stopped it. Interviewers ask this scenario to see whether we can design layered limits that work even when someone forgets. In this answer, we will look at how one query locks up a database, then go through application timeouts, database backstops, lock timeouts, attribution, and moving heavy work off the primary.

1How One Query Locks Up a Shared Database

Consider what likely happened. A report query from the billing service, with a missing index, started a full scan of a large table and a big sort. It used most of the disk bandwidth, so every other query slowed down. If it ran inside a transaction that had also updated rows, or used select for update, it held row locks too, and writers from other services queued behind them. Their connection pools ran out of connections, their request threads blocked, and their health checks started failing. Twenty minutes later someone found the session and cancelled it.

Two things were missing: a limit on how long a statement may run, and a way to see quickly whose query it was. We will add both, at several layers, so that each catches what the others miss.

Step throughLayers of protection against runaway queries
  1. Query hint per methodjakarta.persistence.query.timeout for user-facing queries
  2. Transaction timeout@Transactional(timeout = ...) bounds the unit of work
  3. Database user limitsstatement_timeout, lock_timeout per service user
  4. Attributionapplication_name and SQL comments name the service
  5. Workload placementreports on replicas, heavy jobs reviewed

5 layers, from the top down. Step through them one at a time.

Each layer catches what the one above it misses.

2Timeouts in the Application

Every user-facing query should have a timeout shorter than the time the user is willing to wait. In Spring Data we can set it per method with a hint, or for a whole unit of work with a transaction timeout, which Spring applies to each query it executes through JPA.

Java
@QueryHints(@QueryHint(name = "jakarta.persistence.query.timeout", value = "3000"))
@Query("select i from Invoice i where i.customer.id = :id")
List<Invoice> findForCustomer(@Param("id") Long id);
@Transactional(readOnly = true, timeout = 5) // seconds, for everything in this method
public InvoiceSummary summary(long customerId) { ... }

These are good, but they rely on every developer remembering, and a policy that relies on memory will fail eventually. That is why the next layer matters most.

3The Database Backstop

Each service connects with its own database user, and we set limits on that user. In PostgreSQL, statement_timeout cancels any statement that runs longer than the limit, no matter which code sent it. MySQL has max_execution_time for selects. Because the limit is on the user, it applies even to queries written in a hurry or sent from a console with the service's credentials.

SQL
-- PostgreSQL: limits per service user
alter role billing_svc set statement_timeout = '30s';
alter role billing_svc set lock_timeout = '5s';
alter role billing_svc set idle_in_transaction_session_timeout = '60s';
-- a reporting user gets a longer limit, and connects to a replica
alter role billing_reports set statement_timeout = '10min';

Notice the third setting. A session that opens a transaction and then waits on the application, for example because of a slow remote call, holds its locks the whole time. idle_in_transaction_session_timeout ends such sessions. The values are a starting point; we set them from the slowest legitimate query each service runs, measured, plus a margin. Batch jobs that really need longer can set a higher limit for their own session explicitly, which makes the exception visible in code review.

4Lock Timeouts for Writers

A statement timeout bounds how long a query runs, but a writer waiting for a lock can still wait up to that limit. A separate, shorter lock timeout makes writers give up quickly when a row is held: lock_timeout on the user in PostgreSQL, innodb_lock_wait_timeout in MySQL, or jakarta.persistence.lock.timeout on pessimistic lock queries. A failed lock attempt becomes an error the application can retry or report, instead of a thread silently parked for minutes while its pool drains.

5Making Every Query Traceable

During the incident, the first twenty minutes were partly spent finding out whose query it was. We fix that by having every service set an application name on its connections, which PostgreSQL shows in pg_stat_activity, and by tagging important queries with comments.

Java
# application.yml for the billing service
spring:
datasource:
url: jdbc:postgresql://db:5432/app?ApplicationName=billing-service
jpa:
properties:
hibernate.use_sql_comments: true
-- what the on-call engineer now sees
select application_name, now() - query_start as running, left(query, 60)
from pg_stat_activity where state = 'active' order by running desc;
-- billing-service | 00:19:42 | /* monthly invoice report */ select ...

Comments come from the org.hibernate.comment hint on repository methods. With both in place, an engineer can identify and cancel the offending query, with pg_cancel_backend, in a minute instead of twenty.

6Reviewing Heavy Queries and Moving Reports

Limits stop the damage; reviews prevent it. We would ask teams to check the plan, with explain analyze on production-like data, for any new query over a large table, and to review the top queries by total time from pg_stat_statements every few weeks. Reports and exports, which legitimately take long, move to a read replica with their own user and their own longer timeout, so they can never compete with transactional work on the primary.

7Follow-up questions

Why not rely only on statement_timeout in the database?

It is the backstop, but it is one number for all of a service's queries, so it must be generous enough for the slowest legitimate one. User-facing queries need much tighter limits than that, which only the application can set per method. Both layers together give tight limits where they matter and a hard ceiling everywhere.

What happens to the transaction when a statement times out?

In PostgreSQL, the statement fails and the transaction is aborted, so it must be rolled back; Spring does that when the exception leaves the @Transactional method. The application then decides whether to retry, show an error, or fall back to a cached result.

Do connection pool timeouts help?

They help a different problem. HikariCP's connectionTimeout limits how long a thread waits to get a connection from the pool, which stops threads piling up forever. It does nothing to a query that is already running, so it complements query timeouts rather than replacing them.

8Conclusion

In this answer, we built layered limits after a runaway query locked a shared database: query timeouts on user-facing queries through hints and transaction timeouts, statement_timeout and related limits on each service's database user as a backstop, lock timeouts so writers fail fast, application names and SQL comments so every query is traceable, and regular review of heavy queries with reports moved to replicas.

What to say in the interviewAbout 70 seconds aloud

Open with

I would introduce limits in layers, because any single one can be forgotten. In the application, every user-facing query gets a timeout, either the jakarta.persistence.query.timeout hint on the repository method or a transaction timeout, which Spring applies to each query in the unit of work.

Then, if they want more

Then the backstop: each service has its own database user, and on that user I set statement_timeout, so any statement running longer is cancelled no matter which code sent it, plus idle_in_transaction_session_timeout so a session waiting on the application cannot hold locks forever. Reports get a separate user with a longer limit.

For writers I set a lock timeout, lock_timeout on PostgreSQL or innodb_lock_wait_timeout on MySQL, so they fail fast with an error instead of waiting behind a lock while their pool drains.

For attribution, every service sets ApplicationName in its JDBC URL and tags important queries with Hibernate comments, so during an incident we can see in pg_stat_activity in a minute whose query is running. Finally, prevention: review plans for queries on large tables, look at pg_stat_statements regularly, and move reports and exports to read replicas.

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.
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 runaway query from one service locked up a shared database for 20 minutes. What...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/3a5d0bddef/