Interview Prep/Shell Scripting/Scenarios: deployments, user management and fleet operations

Three app servers run the same deploy script, and each tries to run database migrations at the same time. How do you ensure only one does?

AdvancedScenarioScenarios: deployments, user management and fleet operations
Answer

Situation read → flock only works on one host. You need a lock that all hosts share.

What I'd do →

  1. Use the database itself as the lock: Postgres advisory locks are held for the session.
    psql -v ON_ERROR_STOP=1 <<'SQL'
    SELECT pg_advisory_lock(424242);
    \! ./migrate up
    SELECT pg_advisory_unlock(424242);
    SQL
    
    Most migration tools (Flyway, Liquibase, Alembic with care, golang-migrate) already take such a lock.
  2. Or run migrations once, as a separate pipeline step or a Kubernetes Job, before rolling out app servers.
  3. Alternatives: a DynamoDB conditional write, Consul or etcd locks.

Why → Concurrent migrations can apply a change twice or interleave DDL, corrupting the schema.

Interview tip → The cleanest answer is "migrations are a separate, single step in the pipeline". Locks are a fallback.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: deployments, user management and fleet operations