<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/how-to-fix-postgres-error-deadlock-detected-s28daquxh" -->

---
title: How to Fix Postgres ERROR: deadlock detected | daily.dev
description: PostgreSQL deadlocks occur when two transactions wait on each other's locks in a cycle. Postgres detects this, kills one transaction with ERROR: deadlock...
canonical: https://daily.dev/posts/how-to-fix-postgres-error-deadlock-detected-s28daquxh
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: How to Fix Postgres ERROR: deadlock detected | daily.dev
og:description: PostgreSQL deadlocks occur when two transactions wait on each other's locks in a cycle. Postgres detects this, kills one transaction with ERROR: deadlock...
og:url: https://daily.dev/posts/how-to-fix-postgres-error-deadlock-detected-s28daquxh
og:image: https://api.daily.dev/og/posts/S28dAQUXh.png
og:image:alt: How to Fix Postgres ERROR: deadlock detected
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# How to Fix Postgres ERROR: deadlock detected

**[Medium](https://daily.dev/sources/medium_js)** · 8 min read · 0 upvotes · 0 comments

## Summary

PostgreSQL deadlocks occur when two transactions wait on each other's locks in a cycle. Postgres detects this, kills one transaction with ERROR: deadlock detected (SQLSTATE 40P01), and lets the other proceed. The guide covers how to identify the blocking PIDs via pg_stat_activity and logs, safely cancel or terminate the blocker using pg_cancel_backend/pg_terminate_backend, implement retry logic with exponential backoff in application code, and prevent recurrence by enforcing consistent lock ordering, shortening transaction duration, adding missing indexes to reduce lock footprint, and using SKIP LOCKED for queue patterns. It also clarifies the difference between deadlocks, lock waits, and statement timeouts.

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://aws.plainenglish.io/how-to-fix-postgres-error-deadlock-detected-0262adec615f>

## Questions this post answers

### How do I find which queries caused a Postgres deadlock detected error?

Search the Postgres logs for the deadlock detail block, which lists the process IDs and the exact statements each transaction ran, for example two UPDATE statements on the same table with different row orders. Use a command like grep -B2 -A20 "deadlock detected" on the postgresql log file to extract both PIDs and their queries as the collision pair.

_Developers debugging production lock contention keep fixes like this close on daily.dev while triaging Postgres errors._

### How do I safely kill a Postgres session that's blocking other transactions?

Call pg_cancel_backend(pid) first, which sends SIGINT and lets the transaction roll back cleanly; if the session doesn't respond within 5-10 seconds, escalate to pg_terminate_backend(pid), which sends SIGTERM as a harder kill. Choose the victim strategically, preferring to cancel a background job over a user checkout or a report query over a payment update.

_Anyone operating Postgres under load can reference daily.dev when deciding how to intervene on stuck transactions._

### What's the difference between a Postgres deadlock and a lock wait timeout?

A deadlock is a circular wait between transactions, which Postgres detects and resolves by killing one with error 40P01, requiring a retry. A lock wait is one transaction simply blocking another with no cycle, producing a different error, 'canceling statement due to lock timeout', once lock_timeout is exceeded; a statement timeout is unrelated to locks and just means the query ran too long.

_Engineers triaging Postgres errors can use daily.dev to tell deadlocks apart from lock waits before reacting._

## Similar posts on daily.dev

- [What actually happens in a database deadlock?](https://daily.dev/posts/what-actually-happens-in-a-database-deadlock--m6r52cbpe) · Medium · 1 upvotes · 0 comments
- [All Your GUCs in a Row: deadlock\_timeout](https://daily.dev/posts/all-your-gucs-in-a-row-deadlock-timeout-3g1yv7vql) · Planet PostgreSQL · 0 upvotes · 0 comments
- [Resolving PostgreSQL ERROR: canceling statement due to user request](https://daily.dev/posts/resolving-postgresql-error-canceling-statement-due-to-user-request-8tlzte2il) · Baeldung · 1 upvotes · 0 comments
- [Deep dive into Amazon Aurora PostgreSQL lock analysis with CloudWatch Database Insights](https://daily.dev/posts/deep-dive-into-amazon-aurora-postgresql-lock-analysis-with-cloudwatch-database-insights-u4rsthnlj) · AWS Database Blog · 0 upvotes · 0 comments
- [Using PostgreSQL as a Dead Letter Queue for Event-Driven Systems](https://daily.dev/posts/using-postgresql-as-a-dead-letter-queue-for-event-driven-systems-ekm9n1imv) · Hacker News · 0 upvotes · 0 comments

---

Tags: [#postgresql](https://daily.dev/tags/postgresql)

[View this post on daily.dev](https://daily.dev/posts/how-to-fix-postgres-error-deadlock-detected-s28daquxh)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"TechArticle","headline":"How to Fix Postgres ERROR: deadlock detected","url":"https://daily.dev/posts/how-to-fix-postgres-error-deadlock-detected-s28daquxh","mainEntityOfPage":{"@type":"WebPage","@id":"https://daily.dev/posts/how-to-fix-postgres-error-deadlock-detected-s28daquxh"},"datePublished":"2026-07-22T14:06:12.364Z","dateModified":"2026-09-13T20:29:52.690Z","description":"PostgreSQL deadlocks occur when two transactions wait on each other's locks in a cycle. Postgres detects this, kills one transaction with ERROR: deadlock...","image":"https://media.daily.dev/image/upload/s--P4t4XyoV--/f_auto/v1722860399/public/Placeholder%2001","thumbnailUrl":"https://media.daily.dev/image/upload/s--P4t4XyoV--/f_auto/v1722860399/public/Placeholder%2001","isAccessibleForFree":true,"articleSection":"Medium","inLanguage":"en","publisher":{"@type":"Organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180}},"author":{"@type":"Organization","name":"Medium","logo":"https://media.daily.dev/image/upload/t_logo,f_auto/v1/logos/medium","url":"https://daily.dev/sources/medium_js"},"commentCount":0,"discussionUrl":"https://daily.dev/posts/how-to-fix-postgres-error-deadlock-detected-s28daquxh","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":0},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":0}],"keywords":"postgresql","timeRequired":"PT8M"}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"Medium","item":"https://daily.dev/sources/medium_js"},{"@type":"ListItem","position":3,"name":"How to Fix Postgres ERROR: deadlock detected"}]}
{"@context":"https://schema.org","@type":"FAQPage","@id":"https://daily.dev/posts/how-to-fix-postgres-error-deadlock-detected-s28daquxh#faq","mainEntity":[{"@type":"Question","name":"How do I find which queries caused a Postgres deadlock detected error?","acceptedAnswer":{"@type":"Answer","text":"Search the Postgres logs for the deadlock detail block, which lists the process IDs and the exact statements each transaction ran, for example two UPDATE statements on the same table with different row orders. Use a command like grep -B2 -A20 \"deadlock detected\" on the postgresql log file to extract both PIDs and their queries as the collision pair. Developers debugging production lock contention keep fixes like this close on daily.dev while triaging Postgres errors."}},{"@type":"Question","name":"How do I safely kill a Postgres session that's blocking other transactions?","acceptedAnswer":{"@type":"Answer","text":"Call pg_cancel_backend(pid) first, which sends SIGINT and lets the transaction roll back cleanly; if the session doesn't respond within 5-10 seconds, escalate to pg_terminate_backend(pid), which sends SIGTERM as a harder kill. Choose the victim strategically, preferring to cancel a background job over a user checkout or a report query over a payment update. Anyone operating Postgres under load can reference daily.dev when deciding how to intervene on stuck transactions."}},{"@type":"Question","name":"What's the difference between a Postgres deadlock and a lock wait timeout?","acceptedAnswer":{"@type":"Answer","text":"A deadlock is a circular wait between transactions, which Postgres detects and resolves by killing one with error 40P01, requiring a retry. A lock wait is one transaction simply blocking another with no cycle, producing a different error, 'canceling statement due to lock timeout', once lock_timeout is exceeded; a statement timeout is unrelated to locks and just means the query ran too long. Engineers triaging Postgres errors can use daily.dev to tell deadlocks apart from lock waits before reacting."}}]}
```

