Interview Prep/Shell Scripting/Scenarios: text processing and scheduling decisions

A cleanup job runs from cron on all 3 nodes of a cluster but must execute on exactly one. How do you do it?

AdvancedScenarioScenarios: text processing and scheduling decisions
Answer

Situation read → Local locks do not coordinate across hosts. You need leader election or a shared lock.

What I'd do →

  1. Simplest: schedule it in one place (a single admin host, a Kubernetes CronJob with concurrencyPolicy: Forbid, or a CI schedule).
  2. If it must run from the nodes, use a shared lock with a TTL:
    # DynamoDB conditional put as a lock that expires after 30 minutes
    now=$(date +%s)
    aws dynamodb put-item --table-name locks \
      --item "{\"id\":{\"S\":\"cleanup\"},\"owner\":{\"S\":\"$(hostname)\"},\"exp\":{\"N\":\"$((now + 1800))\"}}" \
      --condition-expression 'attribute_not_exists(id) OR exp < :now' \
      --expression-attribute-values "{\":now\":{\"N\":\"$now\"}}" 2>/dev/null || exit 0
    
  3. Or a Postgres advisory lock, Consul consul lock, or etcd.
  4. Make the job idempotent anyway, in case two runs happen.

Why → A distributed lock with expiry avoids both double runs and a stuck lock after a crash.

Interview tip → Lead with "move the schedule to one place"; it is simpler than any lock.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: text processing and scheduling decisions