Two engineers run terraform apply on the network root about 4 seconds apart. State is in S3 with versioning on, but the backend has no dynamodb_table and no use_lockfile. Both applies print Apply complete!. What has actually happened to state, and what would a lock have changed?
- S3 versioning reconciles the two writes, so state is complete and nothing is lost. Versioning stores both documents as separate versions; the current version is simply the last write. It lets you retrieve the overwritten state afterwards, which is a recovery path, not a prevention.
- The second apply is rejected because Terraform notices the state serial changed underneath it. The S3 backend's consistency check (the state digest) lives in the DynamoDB lock table; without locking configured there is nothing to compare against and the write goes through.
- Both runs read the same state serial, both created the missing resources, and the second state write overwrote the first: some real resources now exist with no entry in state. The next plan proposes to create them again (
+) and the apply fails on name conflicts or creates duplicates; recovery isterraform import, and a lock would have made the second run fail fast withError acquiring the state lock. Without a lock there is no serialisation and no serial check, so the last writer wins and the loser's objects become invisible to Terraform. - Nothing goes wrong:
applyis idempotent, so two applies converge on the same result. Idempotence holds for sequential applies against a consistent state; two applies working from the same snapshot both create the missing objects and then race on the write.
Without a lock the second state write overwrote the first, so some real resources are now missing from state and the next plan wants to create them again.
State is a document with a serial; every apply reads it, acts, and writes it back. A lock is what turns "reads and writes" into "one writer at a time". Without it, two applies that start from serial N both believe the same resources are missing, both create them (the cloud may reject duplicates or may not, depending on whether names must be unique), and both write serial N+1; the second write replaces the first, and the first run's objects are orphaned from Terraform's point of view. The S3 backend stores a digest of the state in the DynamoDB table precisely so it can detect a replaced document, which is why the fix is dynamodb_table (or use_lockfile = true on Terraform 1.10+), not a bigger bucket. Versioning stays on so the overwritten state can be pulled back when you need to reconstruct what happened.
Saying S3 versioning makes concurrent applies safe. Versioning keeps the overwritten document so you can get it back; only a lock stops the overwrite.