Course contentsShow
← Cloud and Infrastructure
Lesson 786 of 2,98915. Terraform in PracticeFree lesson

State Locking Fundamentals

Learn how state locking prevents concurrent modifications and protects infrastructure from race conditions.

State Locking Fundamentals

What you'll learn: How state locking prevents simultaneous Terraform operations from corrupting your infrastructure state.

The Problem: Race Conditions

Imagine two team members running terraform apply at the exact same time on the same infrastructure. Both read the current state, make their changes, and try to write back — but each overwrites the other's work. The result? A corrupted state file that doesn't match reality, leading to unpredictable infrastructure behavior or outright failures.

This is called a race condition, and it's exactly what state locking prevents.

How State Locking Works

State locking is like a "Do Not Disturb" sign on your state file. When someone runs an operation that modifies state (apply, destroy), Terraform attempts to acquire a lock on the state file. If successful, the operation proceeds. If the lock is already held by another process, Terraform waits or fails, preventing concurrent modifications.

The lock is automatically released when the operation completes (or crashes). This ensures only one operation can modify state at any given moment.

When Locking Happens

State locking activates during any write operation:

  • terraform apply
  • terraform destroy
  • Any operation that changes infrastructure

Read-only operations like terraform plan typically don't require locks, though some backends may still use them.

Backend Support Required

Not all state storage supports locking. Local state (files on your disk) has no locking mechanism — if two people share the same local file via network storage, corruption is possible. Remote backends like S3 with DynamoDB or Terraform Cloud provide built-in locking capabilities, making them essential for team environments.

Key Takeaway: State locking prevents multiple Terraform processes from simultaneously modifying infrastructure state, protecting against race conditions and state file corruption — but requires a backend that supports locking mechanisms.