⚡ ~/naveed Interview Prep
⚡ Portfolio Home 👤 About Naveed Bio & Credentials ⚖️ Editorial Policy Standards & Trust 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →
← Back to All Databases & Storage Interview Questions Scenario 67 of 69 in Databases & Storage
Senior DevOps / SRE Database PostgreSQL & MySQL Triage Production Runbook
🎯 Target Role / Context: Senior DevOps / SRE Supabase Connection Management Interview Scenario

Q: How do you resolve connection pool exhaustion and transaction mode prepared statement errors in Supabase?

Supabase interview questions on connection pooling: transaction vs session mode, prepared statement errors, pg_stat_activity triage and serverless patterns.

#Supabase #Supavisor #PgBouncer #Connection Pooling #PostgreSQL #Prisma
🎙️ Candidate Opening & Architectural Context
"Connection errors are a staple of supabase interview questions because two separate limits cause them. PostgreSQL has a max_connections ceiling on real server backends. The pooler in front of it (Supavisor on current projects, with PgBouncer-style behavior) has its own limit on client connections, which is normally far higher. Exhaustion happens when clients hold backends too long, or when too many app instances each open their own pool. A second failure shows up after you switch to transaction mode: prepared statements stop working. I walk through diagnosis first, then connection choice, then the driver settings. I avoid quoting plan-specific numbers, since they change by compute size and plan; check the dashboard for your project."
Advertisement
⚡ Recommended Practice Lab

Want to master this scenario in a live sandbox? KodeKloud's PostgreSQL Database Administration & High Availability Course covers this exact problem with hands-on terminal drills.

🛠️ Production Runbook & Step-by-Step Resolution

Direct Answer: Connection errors are a staple of supabase interview questions because two separate limits cause them. PostgreSQL has a max_connections ceiling on real server backends. The pooler in front of it (Supavisor on current projects, with PgBouncer-style behavior) has its own limit on client connections, which is normally far higher. Exhaustion happens when clients hold backends too long, or when too many app instances each open their own pool. A second failure shows up after you switch to transaction mode: prepared statements stop working. I walk through diagnosis first, then connection choice, then the driver settings. I avoid quoting plan-specific numbers, since they change by compute size and plan; check the dashboard for your project.

1

Inspect pg_stat_activity to See Who Holds the Backends

Start from the server's view. Group backends by state and role. A large count of idle connections means pools that are sized too big or never released. A large count of idle in transaction means application code opened a transaction and is waiting on something else, which holds a backend and any locks. Compare the total with max_connections so you know how close to the ceiling you are.

SHOW max_connections;

SELECT usename, application_name, state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY 1,2,3
ORDER BY count(*) DESC;
--  usename   | application_name | state                | count
--  postgres  | api-server       | idle                 | 38
--  postgres  | worker           | idle in transaction  | 12
2

Pick the Right Connection Mode for Each Workload

Supabase exposes three paths. A direct connection goes straight to Postgres and uses one backend per client, which suits long-lived servers that need session features. Session mode through the pooler also pins a backend to a client for the whole session, but works where direct IPv6 access is a problem. Transaction mode through the pooler assigns a backend only for the duration of a transaction, so many short-lived clients can share few backends. I use transaction mode for serverless functions and request-per-connection apps, and direct or session mode for migrations, LISTEN/NOTIFY and tools that depend on session state. Copy exact hosts and ports from the project's connection settings.

# Direct (one backend per client)
postgresql://postgres:[PASSWORD]@db.[PROJECT_REF].supabase.co:5432/postgres

# Pooler, session mode (copy host and port from the dashboard)
postgresql://postgres.[PROJECT_REF]:[PASSWORD]@[POOLER_HOST]:5432/postgres

# Pooler, transaction mode (typically port 6543)
postgresql://postgres.[PROJECT_REF]:[PASSWORD]@[POOLER_HOST]:6543/postgres
Advertisement
3

Fix Prepared Statement Errors in Transaction Mode

In transaction mode, consecutive statements from one client can land on different backends, so a named prepared statement created on one backend does not exist on the next. You see errors such as prepared statement "s1" does not exist or already exists. The fix is to turn off prepared statements in the driver. For postgres.js set prepare to false. For Prisma add pgbouncer=true to the pooled URL and keep a separate direct URL for migrations. With node-postgres, avoid giving queries a name.

// postgres.js
import postgres from 'postgres'
const sql = postgres(process.env.DATABASE_URL, { prepare: false, max: 1 })

# Prisma: pooled URL for runtime, direct URL for migrations (.env)
DATABASE_URL="postgresql://postgres.[REF]:[PW]@[POOLER_HOST]:6543/postgres?pgbouncer=true"
DIRECT_URL="postgresql://postgres:[PW]@db.[REF].supabase.co:5432/postgres"

// schema.prisma
// datasource db { provider = "postgresql"  url = env("DATABASE_URL")  directUrl = env("DIRECT_URL") }
4

Clear Idle-in-Transaction Sessions and Set Guard Rails

Backends stuck in idle in transaction are the usual reason a pool looks full while the database is quiet. I find the oldest ones, fix the code path that forgets to commit, and set a timeout so the server cleans up after future bugs. Setting idle_in_transaction_session_timeout at the role level protects every connection that role opens. Terminate sessions manually only after you confirm they are not doing legitimate long work.

SELECT pid, usename, now() - xact_start AS xact_age, left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY xact_start LIMIT 5;

-- After confirming they are stuck
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction' AND now() - state_change > interval '10 minutes';

ALTER ROLE postgres SET idle_in_transaction_session_timeout = '30s';
5

Use Serverless-Friendly Connection Patterns

Every function instance that opens its own pool multiplies connections. I create the client once at module scope so warm invocations reuse it, cap each instance at a very small pool size, and point it at the transaction-mode pooler. Total demand then equals concurrent instances times pool size, which I compare against the pooler's client limit and the backend pool size. If that product is still too large, I reduce concurrency, batch work, or move to a larger compute size.

// Module scope: reused across warm invocations
import postgres from 'postgres'
const sql = postgres(process.env.POOLER_URL, {
  prepare: false,
  max: 1,            // one connection per function instance
  idle_timeout: 20,  // seconds
})

export async function handler(req) {
  const rows = await sql`select id, title from todos limit 20`
  return Response.json(rows)
}
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"For supabase interview questions on pooling, separate the two limits (client connections at the pooler, max_connections on Postgres), use transaction mode for short-lived serverless clients with prepared statements disabled, keep direct or session connections for migrations, and use pg_stat_activity plus idle_in_transaction_session_timeout to keep backends from being held."
⚡ 60-Second Elevator Pitch Talking Points
  • I check pg_stat_activity by state and role to see whether backends are idle, active or stuck in transaction.
  • I send serverless and short-lived clients through the pooler in transaction mode and keep migrations on a direct or session connection.
  • I disable prepared statements in the driver, using prepare false in postgres.js or pgbouncer=true in Prisma.
  • I cap per-instance pool size and set idle_in_transaction_session_timeout so leaks clear themselves.
⛔ Critical Candidate Mistakes to Avoid in This Scenario

Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:

  1. Running Prisma migrations through the transaction-mode pooler Migrations rely on session features and prepared statements, so use a direct URL for them.
  2. Leaving driver pool size at its default in every serverless instance Total connections equal instances times pool size, which can exhaust the pooler or backends quickly.
  3. Raising max_connections as the first fix More backends increase memory use and contention, while the real cause is often idle or idle-in-transaction clients.
  4. Quoting connection limits from memory in an answer Limits depend on plan and compute size, so say where you would look them up.
Advertisement
Want more Databases & Storage scenarios?
Explore our complete collection of scenario-based Databases & Storage interview runbooks.
Browse All Databases & Storage Questions →