State locking and concurrent applies

Intermediate · 9 min

Why two simultaneous applies corrupt state, how S3 use_lockfile and other backends lock it, and what to do when a crashed run leaves a stale lock.

Before thisRemote backends: S3, GCS and azurerm

Rahul Saxena · 9 min

State locking and concurrent applies

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Rahul SaxenaReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Two runs that read the same state, change it and write it back will lose one of the changes. A lock makes the second run wait or fail before it reads.
  • On the S3 backend, `use_lockfile = true` locks with a `.tflock` object next to the state, with no DynamoDB table. It was added in Terraform 1.10, became generally available in 1.11, and OpenTofu 1.10 added it too.
  • The `dynamodb_table` argument is deprecated since Terraform 1.11, and the docs say it will be removed in a future minor version. Both can be set at once while you migrate.
  • A lock left by a crashed run is stale. Check that the holder is really dead, then `terraform force-unlock LOCK_ID`. Never use `-lock=false` as a habit.
  • Locking protects state, not your design. If a CI job and a human apply the same configuration, the lock only stops them from overlapping. It does not decide who should apply.

A lost update, run for real

Terraform’s state update is the oldest bug in shared storage: read the file, change it, write it back. If two runs interleave, one change disappears. I wanted to see that happen, so I wrote a stand-in. It is not Terraform. It is a Python script that plays two appliers, alice and ci-job, against a JSON file with a serial number, and each takes half a second between reading and writing.

--- no lock
alice: wrote serial 2
ci-job: wrote serial 2
final: {'serial': 2, 'resources': ['ci-job-change']}

Both wrote serial 2. The final file holds only ci-job’s change. Alice’s resource exists in the cloud and nowhere in state, so the next plan wants to create it again and either fails on a name clash or makes a duplicate. That is an unlocked apply, in one line of output.

Adding the lock

A lock turns the read-modify-write sequence into a critical section. The run must hold the lock before it reads, and release it after it writes. The one hard requirement is that taking the lock is atomic: check-then-create is not enough, because two runs can both see “no lock” and both create one. The create has to fail for the second caller.

My stand-in uses a create-only open of a lock file, which is an exclusive create on a local disk:

--- with create-if-absent lock file
ci-job: Error acquiring the state lock. Held by alice (ID 77a7c726), op OperationTypeApply
alice: wrote serial 2
final: {'serial': 2, 'resources': ['alice-change']}

The second run was refused before it read anything. Real Terraform adds options on top of this. -lock-timeout=5m makes a run wait for the lock instead of failing at once, which is useful in CI queues. The message it prints when it fails lists ID, Path, Operation, Who, Version and Created, written from the docs and not run by me.

How each backend takes the lock

Every backend has its own atomic primitive. The S3 backend, since Terraform 1.10, can write a lock object named after the state key with .tflock added, using S3’s conditional write so that the write fails if the object already exists. You turn it on with one argument:

terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "notes/prod/terraform.tfstate"
    region       = "eu-west-1"
    use_lockfile = true
  }
}

That block comes from the backend docs, and I did not run it. It was experimental in 1.10, and the 1.11 changelog says S3 native locking became generally available and deprecated the DynamoDB arguments. The S3 backend docs say DynamoDB-based locking will be removed in a future minor version, and that both mechanisms can be configured together so you can migrate. When both are set, locks are taken from both. OpenTofu 1.10’s changelog lists the same feature, so use_lockfile works on both tools.

Before 1.10, the standard setup was a DynamoDB table with a LockID string key, and a lot of tutorials still show it. Keep that in mind when you watch older videos. Everything they say about why locks matter is right, and the table is now the legacy way to get one. The GCS and azurerm backends lock with their own storage features, with nothing extra to create.

The permissions change slightly too: with use_lockfile, the role needs s3:GetObject, s3:PutObject and s3:DeleteObject on the .tflock key, as well as read and write on the state key.

Stale locks

A lock exists to be released. If the process dies between acquiring and releasing it, a CI runner reclaimed mid-apply or a laptop closed during a long plan, the lock object stays. I simulated that case too:

--- stale lock after a crash
alice: Error acquiring the state lock. Held by ci-job (ID b1c2d3e4), op OperationTypeApply

Terraform gives you terraform force-unlock LOCK_ID, using the ID printed in the error. It removes the lock without checking anything, so the checking is your job. Look at Who and Created, then at the CI system. If that pipeline job is gone, unlock. If it is still running, wait. Force-unlocking a live apply puts you back in the first block of this lesson’s output.

There is also -lock=false, a flag on most commands that skips locking. It exists for a recovery situation where the lock mechanism itself is broken. Using it routinely is the same as having no lock, with the extra risk that you now think you have one.

What a lock does not do

Locking prevents two writes from interleaving. It does not stop a plan that was made at 10:00 from being applied after someone else’s apply at 10:05, which is why CI applies the saved plan file and why Terraform refuses a plan file made against a state that has since changed. It also does not make “who applies” a good question. Sort that out with a pipeline that is the only thing allowed to apply, covered in Terraform in CI.

About the video

The embed is Rahul Saxena’s “Terraform S3 State Locking Explained”, published October 2026, 9 minutes. Its description says it covers the concurrent-apply problem, use_lockfile, the .tflock file, stale locks and force-unlock, which is this lesson’s scope and on the current mechanism. It is a very small channel, around 160 views when I looked. I read the metadata only. Automation Avenue’s January 2025 video in deeper is a short demo of replacing dynamodb_table with use_lockfile. English was judged from the title, description and the English auto-caption track.

Where this fits

State is now shared and protected from overlapping writes. Next, the commands that change state on purpose: the terraform state subcommands.

Check yourself

  1. 01What exactly goes wrong if two applies run at once with no lock?

    Each reads the same starting state, makes its own changes, and writes the whole file back. The later write replaces the earlier one, so state forgets resources the first run created, and the next plan wants to create them again.

  2. 02Why does an S3 lock need a way to create an object only if it does not already exist?

    Two runs checking for the lock and then writing it can both see it missing and both succeed. The create must be one atomic step that fails for the second caller. S3's conditional write gives that.

  3. 03A pipeline was killed in the middle of an apply and every later run reports the state is locked. What do you check before `force-unlock`?

    That the process holding the lock is really gone, from the lock's `Who` and `Created` fields and the CI system. If it is still running, unlocking lets two writers in.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark