The scheduler that died every five minutes: a deadlock between advisory locks and a Go connection pool

This is the story of a PostgreSQL advisory lock and an odd deadlock. A few weeks ago we moved Sima's scheduler from Laravel to Go. Everything ran fine on staging until we noticed the scheduler's container being recreated roughly every five minutes. No panic, no OOM, nothing odd in the logs. Just the healthcheck getting 503 three times in a row, and Docker Swarm killing the container.
It turned out to be a deadlock: each task's Postgres advisory lock and the connection pool in pgx had tied each other in a knot. The pattern is common and is probably in your code too, so here's the whole story.
Why an advisory lock?
When a scheduler runs on more than one replica, or two versions overlap for a few seconds during a rollout, a task must not run twice. Laravel has onOneServer() for that, backed by a cache lock. In Go we reached for something we already had, Postgres advisory locks:
func exclusively(ctx context.Context, db *pgxpool.Pool, name string, task func(context.Context) error) {
conn, err := db.Acquire(ctx)
if err != nil {
return
}
defer conn.Release()
var mine bool
err = conn.QueryRow(ctx, `select pg_try_advisory_lock(hashtext($1))`, name).Scan(&mine)
if err != nil || !mine {
return // someone else is running it
}
defer conn.Exec(context.Background(), `select pg_advisory_unlock(hashtext($1))`, name)
task(ctx) // the task queries db too
}
One important point: a session-level advisory lock belongs to the connection, not to a transaction. So we must keep that same connection until the task ends, or the unlock runs on another session and does nothing. So far the code is right.
Where it went wrong
The task itself talks to Postgres too, and takes its connection from the same pool. Say the pool has four connections, which is also pgxpool's default: the larger of 4 and runtime.NumCPU(). At minute zero, four tasks start together:
- Each task takes a connection for its lock. All four connections are now in use.
- Each task wants to run its first query and calls
Acquire. - The pool is empty, so everyone waits for a connection to come free.
- None ever does, because each connection's owner is itself waiting.
A classic deadlock, only this time over the pool as a resource rather than a mutex. Postgres notices nothing, because from its side no lock is waiting on another lock. pg_locks is clean and deadlock_timeout never fires.
The health endpoint (/up) used the same pool to check the database. It queued behind everyone, timed out and returned 503. After three failures Swarm killed the container. A new one came up, worked for a few minutes, and on the first minute when several tasks were due together, the same thing happened again.
Why we didn't catch it on a laptop
On a development laptop NumCPU is large, so the pool is large, and the number of tasks running together never reaches it. Staging was different: a smaller pool and more concurrent tasks. We'd always had the bug; only the threshold had moved. Any code that holds one connection and asks for another will end up here under load.
The fix: a separate pool for locks
We weighed these options first:
- A bigger pool: only moves the threshold. Add more tasks and the problem is back.
- Running the task on the lock's connection: clean, but every task's code would have to take a
conninstead of the pool, and tasks with their own concurrency can't. pg_try_advisory_xact_lockinside a transaction: the same problem, because the transaction also holds a connection until the task ends.- A separate pool for locks: locks come from one pool and tasks from another. No cycle can form.
We chose the last one, because it was the smallest change and touched no task:
// lockPool is only for advisory-lock sessions, so a lock held through
// a task never takes a connection the task (or /up) needs.
func lockPool(ctx context.Context) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
return nil, err
}
cfg.MaxConns = 32 // one per concurrently due task is plenty
cfg.MaxConnIdleTime = time.Minute
return pgxpool.NewWithConfig(ctx, cfg)
}
Now exclusively takes its lock from locks and the task works with db. Since that change went out, we haven't had a single restart of this kind.
A few lessons worth keeping
- Wherever you hold a connection and ask the same pool for another, you have a potential deadlock. It doesn't have to be a lock. An open transaction with a function in the middle calling
db.Queryis the same pattern. - Keep the healthcheck off the working pool, or at least give its
Acquirea short timeout. Otherwise database slowness turns into restart after restart, and the root cause gets harder to find. - Size the pool on the real environment. The default depends on CPU count and differs between a laptop and a server.
- Postgres can't see this deadlock. If
pg_stat_activityshows severalidleconnections holding locks while the app is stuck, look at the pool.
This is one of several lessons from rewriting Sima from Laravel to Go. Next posts cover the others, such as how we swapped the backend without a single database migration.
Before we found this advisory lock, we had arrested another suspect, described in GOMAXPROCS in a container. The whole scheduler was part of moving from Laravel to Go.
Comments
Sign in to leave a comment.
Sign inLoading…



