Project Lock Lifecycle#
Overview#
Atlantis uses project-level locks (models.ProjectLock) to prevent concurrent plan or apply operations on the same Terraform project/workspace. These are distinct from the pull-level working-dir lock that serializes webhook-triggered commands within a single PR โ project locks persist to durable storage (BoltDB or Redis) and gate cross-operation exclusivity by project identity.
The lock client interface is locking.Locker, implemented by locking.Client which delegates to a db.Database backend. A NoOpLocker is available for contexts where locking is not required .
Lock key format: {repoFullName}/{path}/{workspace}/{projectName} โ produced by models.GenerateLockKey and validated by locking.IsCurrentLocking.
Acquisition#
TryLock creates a ProjectLock struct (containing project, workspace, pull request, user, and timestamp) and delegates to the database. If the lock is already held, the existing lock is returned with LockAcquired: false. The returned LockKey is used for targeted releases via Unlock.
Locks are acquired during the plan phase. The locking context carries a pull that identifies the owner โ for API operations, this is a synthetic negative pull number (see below).
Synthetic Pull Numbers for API Operations#
Command endpoints (/api/plan, /api/apply) require api in the server's experiments list and api-secret. Drift endpoints require the separate drift-detection permission, api-secret, and enable-drift-detection; remediation apply additionally requires enable-drift-remediation. Routes without their experiment permission return HTTP 404. Enabled experimental settings without the required permissions or prerequisites prevent startup. See Experiments for configuration details.
API endpoints (/api/plan, /api/apply, /api/drift/detect, /api/drift/remediate) do not operate against a real VCS pull request. Each invocation generates a synthetic negative pull number via nextNonPRPullNum():
-int((time.Now().UnixNano() & 0x3fffffff) + nonPRPullCounter.Add(1))
This ensures uniqueness across concurrent calls in the same process. The negative sign distinguishes synthetic locks from PR-backed ones (positive pull numbers).
Release: Normal Path#
Release is performed by UnlockByPull โ called as a defer immediately after apiPlan returns successfully. Each handler registers this defer only after a successful plan, not unconditionally:
| Handler | Defer registered at |
|---|---|
Plan | After apiPlan succeeds |
Apply | After apiPlan succeeds |
DetectDrift | After apiPlan succeeds |
ExecutePlan (remediate) | After apiPlan succeeds |
ExecuteApplyProjects | After apiPlan succeeds |
ExecuteApply | After apiPlan succeeds |
UnlockByPull deletes all locks in the store whose repoFullName and pullNum match the synthetic pull number for that invocation.
For PR-backed API calls (when PR field is a positive number in the request), the same mechanism applies but with the real PR number โ the defer releases whichever projects were locked under that PR.
Release: Error Path inside apiPlan#
apiPlan has a named error return and a defer that, if it returns an error and ctx.CommandSkipped is false, calls Locker.UnlockByPull(ctx.HeadRepo.FullName, ctx.Pull.Num). This releases the locks of projects already planned in that request, for example after a pre-workflow hook failure with --fail-on-pre-workflow-hook-error or a missing policy check runner. The handlers' own defers are still registered only after a successful apiPlan and still handle the success path.
Parallel Planning#
When --parallel-pool-size is greater than 1 and the projects have parallel_plan enabled, API plan requests plan multiple projects concurrently through a bounded pool. All locks are still released by UnlockByPull for the request's synthetic pull number.
Storage Backend Semantics#
BoltDB#
UnlockByPull scans the runLocks bucket using repoFullName as a cursor prefix, collects all locks matching pullNum, then calls Unlock for each . This is a two-phase scan-then-delete; a process crash between scan and delete can leave partial state.
Keys follow the 4-part format {repoFullName}/{path}/{workspace}/{projectName}. At startup, New() migrates old 3-part keys to the new format .
Redis#
Redis lock keys use the format pr/{repoFullName}/{path}/{workspace}/{projectName} . UnlockByPull performs a SCAN over keys matching the repository prefix, fetches each lock, and calls Unlock for pull-number matches. UnlockIfOwnedByPull (used for ownership-checked cleanup) uses an atomic Lua script to delete only if the pull number matches .
Known Failure Modes#
1. Locks Not Released on apiPlan Error (Resolved)#
The handlers' UnlockByPull defers are registered after apiPlan returns successfully, so on their own they would leave locks behind when apiPlan fails mid-run (e.g., a pre-workflow hook error on a later project when --fail-on-pre-workflow-hook-error is set) . apiPlan now releases the locks itself when it returns an error (see Release: Error Path inside apiPlan), so errors returned from apiPlan no longer leave locks behind. Issue #6956 is addressed by PR #6963 for the apiPlan error path.
Remaining caveat: process shutdown (failure mode 2) can still leave locks behind.
2. Locks Not Released on Process Shutdown#
API controllers have no reference to the Drainer. On SIGTERM, Atlantis drains only webhook-triggered operations (RunAutoplanCommand, RunCommentCommand) โ API requests running synchronously in HTTP handlers are cut off immediately . This means:
- The
UnlockByPulldefer in a killed HTTP handler never executes. - Locks with negative synthetic pull numbers persist in BoltDB or Redis after restart.
- No automatic cleanup occurs after restart; negative pull numbers are never reused or reclaimed by any existing process.
Workaround options (from the issue):
- On startup, delete all locks with a negative
PullIDโ no live process can own them after a restart . - Wire the
DrainerintoAPIControllerso API requests participate in graceful shutdown .
Manual Lock Inspection and Removal#
Active locks are visible via GET /api/locks (or the Atlantis web UI). The lock-listing endpoint requires api in the server's experiments list and returns HTTP 404 without it; the drift-detection permission alone does not expose this route. With api permitted, lock listing remains available without api-secret (see Experiments). Each entry exposes PullID, ProjectRepoPath, Time, etc. . A lock with a negative PullID indicates a synthetic API-operation lock that may be stale.
Locks can be deleted individually via the UI (/lock?id=<key>) or released programmatically via Unlock(key) .
Key Files and References#
| File | Role |
|---|---|
server/core/locking/locking.go | Locker interface, TryLock, Unlock, UnlockByPull, UnlockIfOwnedByPull |
server/controllers/api_controller.go | nextNonPRPullNum, handler defer registration pattern |
server/core/boltdb/boltdb.go | BoltDB UnlockByPull, startup key migration |
server/core/redis/redis.go | Redis UnlockByPull, UnlockIfOwnedByPull (Lua script), key schema |
Open issues: