Why should you use remote state, and what problem does state locking solve?

5 minintermediateterraformstatebackendlocking

Quick Answer

Local state (a `.tfstate` file on one laptop) doesn't scale beyond a single operator: it can't be shared, isn't backed up, and risks being committed to git with secrets in plaintext. A **remote backend** (S3+DynamoDB, Terraform Cloud, Azure Storage, GCS) stores state centrally so a team shares one source of truth. **State locking** prevents two concurrent `apply` runs from writing to state at the same time — without it, simultaneous applies can corrupt state or cause one run's changes to silently overwrite another's.

Detailed Answer

By default, terraform init uses a local backend — state lives as a plain file (terraform.tfstate) on whatever machine ran apply. That's fine for solo experimentation, but it breaks down almost immediately for a team.

Why remote state

  • Sharing. If state only exists on one engineer's laptop, nobody else can run plan/apply against the same infrastructure without copying that file around manually (and immediately risking two divergent copies).
  • Durability. A laptop disk failure shouldn't mean losing the only record of what infrastructure exists.
  • Security. Local state files are easy to accidentally commit to git in plaintext (including any sensitive attribute values); a remote backend with proper access controls avoids that.

A remote backend configuration looks like:

terraform {
  backend "s3" {
    bucket         = "my-org-terraform-state"
    key            = "prod/network/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

Why state locking

Without locking, imagine two engineers (or a human and a CI job) run terraform apply at the same moment. Both read the same starting state, both compute a plan, and both write back their own updated version — the second write silently clobbers the first's changes, and the real infrastructure now disagrees with what state records. Worse, concurrent writes to the same state file can corrupt it outright.

State locking prevents this: before any operation that could modify state, Terraform acquires a lock (in the example above, via a DynamoDB table using conditional writes) — a second concurrent apply blocks or fails immediately with a clear "state is locked" error instead of silently racing.

Modern approach

Newer AWS provider versions support S3-native locking (using S3 conditional writes) without a separate DynamoDB table, and platforms like Terraform Cloud/HCP Terraform provide remote state + locking + a full run history out of the box. The specific mechanism varies by backend, but the guarantee is the same: one write to state at a time.