Q: Your infrastructure team uses Terraform Cloud for remote state and applies. In CI, developers run `terraform plan` on every PR. You discover that two developers' PRs simultaneously modified the same resource โ when both were merged, the second apply overwrote the first silently. What mechanism prevents this Terraform race condition?
This race condition is prevented by state locking. Terraform backend implementations (S3+DynamoDB, Terraform Cloud, etc.) acquire an excl...
๐ ๏ธ Production Runbook & Step-by-Step Resolution
Production Solution & Architecture
This race condition is prevented by state locking. Terraform backend implementations (S3+DynamoDB, Terraform Cloud, etc.) acquire an exclusive lock on the state file before any apply operation. If a second apply tries to run while the first holds the lock, it fails immediately with a state lock error rather than proceeding. The underlying issue here is that both PRs passed plan independently (with accurate plans), but the second apply did not re-plan after the first apply changed the state. Terraform Cloud's native solution is Run Queuing โ applies are serialised per workspace. The second run queues and then re-plans against the updated state before applying, so it sees the changes already made by the first apply and only does the diff required. For critical workspaces, enable plan and apply mode with manual confirmation to add a human gate before each apply.
- Immediate Triage: This race condition is prevented by state locking. Terraform backend implementations (S3+Dynamo
- Run targeted verification commands before modifying configuration.
- Automate permanent guardrails (CI check, alerts, IaC policy) to prevent recurrence.