w3resource

Automatically Abort Queries with Excessive Lock Waits


Set a Statement Timeout to Abort Long Lock Waits

Write a PostgreSQL query to set a statement timeout that aborts queries waiting too long for locks.

Solution:

-- Set the statement timeout to 5000 milliseconds (5 seconds).
SET statement_timeout = 5000; -- Abort queries taking longer than 5 seconds.

-- Attempt a query that may wait for a lock.
SELECT * FROM Orders
FOR UPDATE;

Explanation:

  • Purpose of the Query:
    • The goal is to limit the wait time for queries, thereby reducing the risk of long lock waits and potential deadlocks.
    • This demonstrates how to configure a statement timeout for locking scenarios.
  • Key Components:
    • SET statement_timeout = 5000; : Sets the maximum allowed execution time for a query.
    • A subsequent SELECT FOR UPDATE that will abort if the lock is not acquired in time.
  • Real-World Application:
    • Prevents system hang-ups in high-concurrency environments by automatically terminating long-waiting queries.

Notes:

  • The timeout is measured in milliseconds.
  • Adjust the timeout based on the application's performance requirements.

For more Practice: Solve these Related Problems:

  • Write a PostgreSQL query to set a statement timeout of 3000 milliseconds and then execute a SELECT FOR UPDATE query on the Orders table.
  • Write a PostgreSQL query to configure a statement timeout of 5000 milliseconds and attempt to lock a row in the Inventory table.
  • Write a PostgreSQL query to set a statement timeout and then execute an UPDATE query on the Users table that might wait for a lock.
  • Write a PostgreSQL query to set a statement timeout for a transaction that involves multiple locking operations on the Sessions table.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous PostgreSQL Exercise: Prevent Deadlocks with Short Transactions.
Next PostgreSQL Exercise: Test Lock Contention with pg_try_advisory_lock.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.