Back to Playbook
System Architecture8 min read

How We Audit Rails Database Lockups

Slow queries aren't PostgreSQL limitations—they are data modeling bottlenecks. Here is how we analyze and fix lockups in high-traffic monoliths.

PostgreSQL is Fast. Your Data Model is Blocking it.

Startups often blame PostgreSQL or ActiveRecord when their database load hits 98% and transactions lock up. In 9 out of 10 audits we conduct, the database isn't the problem—the application code holds transactions open too long or reads excessive data volumes.

1. Identify Hold Times, Not Just Query Latency

We query PostgreSQL's system catalog to find active locks and queries that have been running for more than 5 seconds. We look specifically for queries in the active state holding exclusive row locks (typically caused by un-indexed updates or broad delete conditions).

-- Find long-running queries holding locks SELECT pid, age(clock_timestamp(), query_start), usename, query, state FROM pg_stat_activity WHERE state != 'idle' AND age(clock_timestamp(), query_start) > interval '5 seconds' ORDER BY age DESC;

2. Stop Querying inside ActiveRecord Transactions

ActiveRecord makes database updates simple, but wraps them in implicit transactions. If you trigger an external API call or perform heavy serialization *inside* a transaction block, you keep database locks open, blocking other web requests from writing to the same tables.

Anti-pattern:

ActiveRecord::Base.transaction do user.update!(status: :processing) payment_gateway.charge!(amount) # External API call: blocks database! user.update!(status: :completed) end

3. Prune Unused Indexes and Partition Large Tables

Too many indexes slow down database writes. We scan the database for indexes that have zero reads and drop them. For tables that grow past 50 million rows, we implement chronological PostgreSQL partitioning to keep index sizes small enough to fit completely in server RAM.

Looking to implement this architecture?

We partner with tech companies to resolve complexity, write robust codebases, and optimize system speed.

Work With Us