When Databases Misbehave

Recognize deadlocks, lock contention, connection exhaustion, replication lag and data loss scenarios before they hit you.

Intermediate · about 5 hours · difficulty 4/5

Learn first: Transactions, ACID and Isolation, Indexes and Query Performance

Databases fail in a handful of recurring ways. Knowing them turns a scary outage into a checklist.

Common failure modes

  • Deadlocks: two transactions each hold a lock the other needs. The database kills one. Fix by locking rows in a consistent order and keeping transactions short; retry the victim.
  • Lock contention: a long transaction or migration holds a lock and hundreds of queries queue behind it. Look at pg_stat_activity and pg_locks.
  • Connection exhaustion: each database connection costs memory, and servers have a hard limit. Many app instances with large pools hit it quickly, producing "too many connections" errors. Use a pooler such as PgBouncer.
  • Runaway queries: a missing index or accidental cross join saturates CPU. Use statement_timeout.
  • Disk full: logs, bloat or a stuck replication slot fill the disk and writes stop.
  • Data loss: accidental DELETE without WHERE, bad migrations, or hardware failure. Backups plus point-in-time recovery are the safety net.

Defensive defaults

  • Set statement and idle-in-transaction timeouts.
  • Alert on connection count, replication lag, disk usage and long-running queries.
  • Rehearse restores regularly.

You are ready to move on when you can deliberately cause a deadlock in two psql sessions, read the error, and explain how you would prevent it in application code.

Key concepts

  • Deadlocks
  • Lock contention and pg_stat_activity
  • Connection limits
  • Statement timeouts
  • Point-in-time recovery
  • Table bloat

Mini project

Write a short runbook for your app's database covering how to find blocking queries, kill a runaway query, check connection usage and restore to a point in time, and test each step locally.

Check yourself

Twenty app instances each have a pool of 20 connections and Postgres allows 100. What happens and how would you fix it?

Free resources