TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › State Locking & Concurrency

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:

python · try it yourself
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:

bash · try it yourself
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=5m makes 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 Actions concurrency: 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_ID removes 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=false exists. 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:

bash
$ 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?

  1. Nothing, writes are merged
  2. The last write wins and the other run's resources go missing from state
  3. Both runs fail
  4. 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?

  1. -lock=false
  2. -lock-timeout=10m plus a CI concurrency group per state
  3. force-unlock before every run
  4. Use local state

When is force-unlock appropriate?

  1. Whenever a lock error appears
  2. Only when the run holding the lock is known to be dead (crashed job)
  3. Before every apply
  4. Never, it doesn't exist