Immutable infrastructure concept in Terraform - Time & Space Complexity
We want to understand how the time to update infrastructure changes when using immutable infrastructure.
Specifically, how does creating new resources instead of changing existing ones affect the work done?
Analyze the time complexity of replacing servers by creating new ones instead of updating in place.
resource "aws_instance" "web" {
count = var.server_count
ami = var.ami_id
instance_type = var.instance_type
lifecycle {
create_before_destroy = true
}
}
This code creates a number of servers and replaces them by creating new ones before destroying old ones.
Look at what happens repeatedly when the number of servers changes.
- Primary operation: Creating and destroying each server instance.
- How many times: Once per server, so as many times as the server count.
As you add more servers, the number of create and destroy actions grows directly with that number.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | About 10 create + 10 destroy operations |
| 100 | About 100 create + 100 destroy operations |
| 1000 | About 1000 create + 1000 destroy operations |
Pattern observation: The work grows directly with the number of servers you manage.
Time Complexity: O(n)
This means the time to update grows in a straight line with the number of servers you replace.
[X] Wrong: "Replacing servers one by one is faster because only one server changes at a time."
[OK] Correct: Even if done one by one, each server still requires a full create and destroy operation, so total work grows with the number of servers.
Understanding how immutable infrastructure scales helps you explain deployment strategies clearly and shows you grasp how cloud resources behave as they grow.
"What if we changed from replacing all servers to updating them in place? How would the time complexity change?"