Understanding locks and deadlocks in PostgreSQL
Python script for monitoring and troubleshooting PostgreSQL locks and deadlocks in real-time
import psycopg2
import time
# Connect to the database
conn = psycopg2.connect(
host="your_host",
dbname="your_dbname",
user="your_user",
password="your_password"
)
while True:
# Retrieve information about current locks
cur = conn.cursor()
cur.execute("""
SELECT
pid,
mode,
locktype,
relation::regclass,
transactionid
FROM
pg_locks
WHERE
NOT granted
""")
rows = cur.fetchall()
print("Current locks:")
for row in rows:
print(row)
print()
# Retrieve information about current deadlocks
cur = conn.cursor()
cur.execute("""
SELECT
pid,
locktype,
relation::regclass,
transactionid
FROM
pg_stat_activity
WHERE
waiting
""")
rows = cur.fetchall()
print("Current deadlocks:")
for row in rows:
print(row)
print()
# Sleep for a few seconds before checking again
time.sleep(5)

Running this in production?
MinervaDB provides PostgreSQL Consulting, PostgreSQL Support and PostgreSQL Remote DBA with 24x7 coverage and a 15-minute S1 response. Talk to an engineer.