In the previous subchapter, we added a DynamoDB table to our backend "for locking." Now let's really understand what state locking is and why it is essential when several people work on the same infrastructure. It is the piece that prevents one of the worst possible disasters with Terraform: state corruption.

The problem: two people at the same time

Remember that the state (Chapter 11) is the file that records which resources exist and how they relate. It is Terraform's "source of truth." Now imagine this situation in a team:

   Ana runs "terraform apply"    ┐
                                 ├─► AT THE SAME TIME! on the SAME state
   Carlos runs "terraform apply" ┘

If both modify the state at the same time, their changes mix and get corrupted. The state file can become inconsistent: half-written records, duplicated resources, or a state that no longer reflects reality. A corrupt state is a nightmare: Terraform loses track of what exists, and fixing it by hand is slow and dangerous.

Analogy: it's like two people editing the same document at the same time without coordination, each saving over the other's changes. The result is a ruined document where changes are lost and nothing makes sense. You need that, while one edits, the other waits their turn.

The solution: state locking

State locking solves this with a simple rule: while someone is modifying the state, no one else can do it at the same time. Terraform puts a "lock" before starting to work and removes it when finished.

   Ana runs apply  →  Terraform puts the LOCK 🔒
                      (Ana works calmly)
   Carlos runs apply →  "The state is locked, please wait..."
                      (Carlos waits)
   Ana finishes  →  Terraform removes the lock 🔓
   Carlos  →  now he can put his lock and work

This way, operations are serialized: they happen one after another, never at the same time. The state is never corrupted by simultaneous access.

How it works with DynamoDB

This is where the DynamoDB table we set up in subchapter 20.1 comes in. It acts as the "lock doorman":

  1. When someone runs apply (or plan), Terraform writes a lock record in the DynamoDB table (in the LockID key).
  2. If someone else tries to run Terraform, it checks the table, sees that there is already an active lock and waits (or notifies that it is locked).
  3. When the first person finishes, Terraform deletes the lock record, releasing the lock.
DynamoDB (locks table)
  LockID: "my-state"  →  occupied by Ana since 10:32  🔒
                         (Carlos sees this and waits)

DynamoDB is ideal for this because it guarantees atomic and consistent operations: two people cannot "grab the lock" at the same time; only one wins.

What you see when the state is locked

If you try to run Terraform while someone else has the lock, you'll see a message like this:

Error: Error acquiring the state lock

Lock Info:
  ID:        a1b2c3d4-...
  Who:       [email protected]
  Created:   2024-...

This tells you who has the lock and since when. It's not a "bad" error: it's Terraform protecting you. You simply wait for the other person to finish and try again.

Locking happens automatically

The good news: once the backend is configured with DynamoDB (subchapter 20.1), locking works automatically, without you having to do anything. Terraform puts on and removes the lock automatically in each operation. You simply work as usual, and the system protects you in the background.

When a lock gets "stuck"

Occasionally, a lock can get "stuck": for example, if someone's connection is cut off in the middle of an apply, the lock might not be released. In those rare cases, there is the terraform force-unlock command to manually remove the lock:

terraform force-unlock <lock-ID>

⚠️ Use it with great care. Before forcing the unlock, make sure that no one is actually working on the state. If you force the unlock while someone is really applying changes, you risk the same corruption that locking was meant to prevent. Always confirm with your team first.

Why this is so important

State locking, together with remote state (subchapter 20.1), is what makes Terraform safe for teams. Without it, collaboration would be a ticking time bomb: sooner or later two people would overlap and corrupt the state. With it, dozens of people can work on the same infrastructure without fear. It is the foundation, along with the PR flow (subchapter 12.5), of professional work with Terraform.

What you should remember

  • If two people modify the state at the same time, it gets corrupted (becomes inconsistent), which is a disaster that's hard to fix. Like two people editing the same document without coordination.
  • State locking (locking) prevents this: while someone is working, they put a lock that prevents others from modifying the state at the same time. Operations are serialized (one after another).
  • With the S3 backend + DynamoDB, locking works automatically: Terraform writes a lock record in DynamoDB when starting and deletes it when finished.
  • If the state is locked, you'll see a message indicating who has it; it's not a bad error, it's protection. You just wait.
  • In rare cases of a "stuck" lock, there is terraform force-unlock, but use it with extreme care and only after confirming that no one is working.

In the next subchapter, we'll see how to move the state between backends safely, something necessary when reorganizing or migrating your infrastructure.

Cloud, AWS & Terraform — From Zero to Expert

Chapter 1 · What is cloud computing

Chapter 2 · The cloud market and major providers

Chapter 3 · Regions, availability zones and edge

Chapter 4 · Compute: EC2

Chapter 5 · Storage: S3

Chapter 6 · Networking: VPC

Chapter 7 · Identity and access: IAM

Chapter 8 · Managed databases

Chapter 9 · Why Infrastructure as Code

Chapter 10 · HCL: the Terraform language

Chapter 11 · Providers and state

Chapter 12 · Your first real infrastructure in Terraform

Chapter 13 · Load balancing and auto scaling

Chapter 14 · Serverless with Lambda

Chapter 15 · Messaging and events

Chapter 16 · Content delivery and DNS

Chapter 17 · Containers on AWS

Chapter 18 · Modules: reuse and composition

Chapter 19 · Workspaces and environment management

Chapter 20 · Remote backends and locking

Chapter 21 · Infrastructure testing

Chapter 22 · Terraform in CI/CD

Chapter 23 · Defense in depth

Chapter 24 · Observability: logs, metrics and traces

Chapter 25 · Cost optimization

Chapter 26 · High availability and disaster recovery

Chapter 27 · AWS Well-Architected Framework

Chapter 28 · Serverless architectures at scale

Chapter 29 · Data platforms on AWS

Chapter 30 · Multi-account and landing zones

Chapter 31 · Platform Engineering and Internal Developer Platform

Chapter 32 · Relevant AWS certifications

Chapter 33 · Projects to consolidate what you've learned

Chapter 34 · Resources and community

© Copyright 2024. All rights reserved