State Locking & Concurrency
Two engineers (or two pipeline runs) apply the same configuration at the same time. Each reads state version 7, each makes its changes, each writes its own version 8. Whichever writes last wins, and the other run's resources are now missing from state: real objects nobody manages, which the next plan will try to create again. That is a lost update, and locking exists to prevent it.
The race, in miniature
The model runs two "applies" against one shared state, first without a lock, then with one:
def apply(state, who, new_resource, log):
snapshot = dict(state["resources"]) # read state
log.append(f"{who}: read serial {state['serial']}")
return snapshot, new_resource
def write(state, who, snapshot, new_resource, log):
snapshot[new_resource] = f"created by {who}"
state["resources"] = snapshot # write the whole state back
state["serial"] += 1
log.append(f"{who}: wrote serial {state['serial']}")
def run(with_lock):
state, log, lock = {"serial": 7, "resources": {"vpc": "existing"}}, [], None
jobs = [("alice", "queue"), ("bob", "bucket")]
pending = []
for who, res in jobs: # both start before either finishes
if with_lock:
if lock is not None:
log.append(f"{who}: Error acquiring the state lock (held by {lock})")
continue
lock = who
pending.append((who, *apply(state, who, res, log)))
for who, snap, res in pending:
write(state, who, snap, res, log)
if lock == who:
lock = None
return state, log
for with_lock in (False, True):
state, log = run(with_lock)
print("with lock:" if with_lock else "without lock:")
print(" " + "\n ".join(log))
print(f" final state: {sorted(state['resources'])}")without lock:
alice: read serial 7
bob: read serial 7
alice: wrote serial 8
bob: wrote serial 9
final state: ['bucket', 'vpc']
with lock:
alice: read serial 7
bob: Error acquiring the state lock (held by alice)
alice: wrote serial 8
final state: ['queue', 'vpc']
Without a lock, Alice's queue exists in AWS but not in state. With a lock, Bob's run fails fast, and he simply runs again once Alice is done, now starting from her state.
Locks in practice
Every command that may write state takes the lock first and releases it at the end: plan (it refreshes), apply, destroy, import, the state subcommands. The local backend locks too, which you can see by starting a slow apply and planning while it runs:
mkdir l && cd l
cat > main.tf <<'HCL'
resource "terraform_data" "slow" {
input = "v1"
provisioner "local-exec" {
command = "sleep 4" # a slow API call, simulated
}
}
HCL
tofu init >/dev/null
tofu apply -auto-approve > first.log 2>&1 &
for i in $(seq 50); do [ -f .terraform.tfstate.lock.info ] && break; sleep 0.1; done
echo "--- the lock held by the running apply"
jq -c '{Operation, Who, Path}' .terraform.tfstate.lock.info
echo "--- a second run while it is held"
tofu plan 2>&1 | grep -v -E '^ (ID|Created|Info):'; echo "exit=${PIPESTATUS[0]}"
echo "--- wait for the lock instead of failing"
tofu plan -lock-timeout=30s | tail -1
wait
tail -1 first.log--- the lock held by the running apply
{"Operation":"OperationTypeApply","Who":"learner@tad","Path":"terraform.tfstate"}
--- a second run while it is held
Error: Error acquiring the state lock
Error message: resource temporarily unavailable
Lock Info:
Path: terraform.tfstate
Operation: OperationTypeApply
Who: learner@tad
Version: 1.13.2
OpenTofu acquires a state lock to protect the state from being written
by multiple users at the same time. Please resolve the issue above and try
again. For most commands, you can disable locking with the "-lock=false"
flag, but this is not recommended.
exit=1
--- wait for the lock instead of failing
No changes. Your infrastructure matches the configuration.
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Things to know:
-lock-timeout=5mmakes a run wait for the lock instead of failing immediately. Pipelines usually set it, and also serialise runs per state at the CI level (GitHub Actionsconcurrency:groups), so two applies never even start together.- The lock records who holds it and for what operation: the first thing to read when you hit a lock error. Ask that person, or check the pipeline, before doing anything else.
tofu force-unlock LOCK_IDremoves a lock left behind by a crashed run (a killed CI job, a laptop that went to sleep). Only use it when you are sure the owner is no longer running; otherwise you get exactly the lost update the lock was preventing.-lock=falseexists. Don't use it on shared state.
With S3, the lock is the <key>.tflock object (use_lockfile) or an item in the DynamoDB table; a lock error looks the same, with Path set to the bucket and key:
$ tofu plan
Acquiring state lock. This may take a few moments...
Error: Error acquiring the state lock
Error message: operation error S3: PutObject, https response error StatusCode: 412, … PreconditionFailed
Lock Info:
ID: 2d1b46a2-37d4-58e6-8a0e-d8a4f0f5f5e2
Path: acme-tfstate-123456789012-eu-west-1/linkly/app/prod.tfstate
Operation: OperationTypeApply
Who: runner@gha-runner-7
Version: 1.13.2
Created: 2026-10-27 09:14:03.512 +0000 UTC
Info:Test yourself
What goes wrong when two applies write the same state without a lock?
- Nothing, writes are merged
- The last write wins and the other run's resources go missing from state
- Both runs fail
- The state is encrypted twice
A pipeline sometimes fails with "Error acquiring the state lock" because a colleague is applying. What is the best fix?
-lock=false-lock-timeout=10mplus a CI concurrency group per stateforce-unlockbefore every run- Use local state
When is force-unlock appropriate?
- Whenever a lock error appears
- Only when the run holding the lock is known to be dead (crashed job)
- Before every apply
- Never, it doesn't exist