Skip to content

encore run fails with 'revoke public: deadlock detected (SQLSTATE 40P01)' when initializing multiple databases in parallel #2433

Description

@nickpokhilko

Bug description

When encore run brings up a local cluster that contains many databases, the role-setup step occasionally fails with a Postgres deadlock:

✔ Creating PostgreSQL database cluster... Done!
❌ Running database migrations... Failed: ensure db roles <db>: revoke public: ERROR: deadlock detected (SQLSTATE 40P01)
ensure db roles <db>: revoke public: ERROR: deadlock detected (SQLSTATE 40P01)

The failure is intermittent (race condition) and reproduces more often on machines with many local databases / namespaces, e.g. after switching between feature branches that each spawn their own cluster.

Root cause

In cli/daemon/sqldb/db.go, ensureRoles runs:

_, err = adm.ExecContext(ctx, "REVOKE ALL ON DATABASE "+safeDBName+" FROM public")
if err != nil {
    return fmt.Errorf("revoke public: %v", err)
}

ensureRoles is invoked concurrently for every database in the cluster. All of these REVOKE ... FROM public statements contend for locks on the shared public role / system catalogs and can deadlock.

The GRANT statements that follow already have a 5-attempt retry loop with the explicit comment:

// We've observed race conditions in Postgres to grant access. Retry a few times.

…but the REVOKE above it has no retry, so a single 40P01 aborts the whole cluster startup.

Suggested fix

Wrap the REVOKE ALL ON DATABASE ... FROM public call in the same retry loop used for the GRANT statements (5 attempts × 250 ms backoff is enough — deadlock resolution releases the loser immediately).

Happy to send a PR if it's helpful.

Environment

  • Encore CLI: v1.57.0
  • Postgres image: `encoredotdev/postgres:18` (also reproduced on `:15`)
  • OS: macOS 25.4.0 (darwin/arm64)
  • Cluster: 4 local databases across multiple namespaces

Reproduction

  1. Have several Encore apps / namespaces with local clusters running (4+ DBs total).
  2. Stop the daemon and remove the sqldb containers (`docker rm -f $(docker ps -aq --filter "name=sqldb-")`), keeping the volumes.
  3. Run `encore run`. After 1–3 attempts the deadlock surfaces on `revoke public`.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions