0
0
Terraformcloud~5 mins

Immutable infrastructure concept in Terraform - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Immutable infrastructure concept
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As you add more servers, the number of create and destroy actions grows directly with that number.

Input Size (n)Approx. API Calls/Operations
10About 10 create + 10 destroy operations
100About 100 create + 100 destroy operations
1000About 1000 create + 1000 destroy operations

Pattern observation: The work grows directly with the number of servers you manage.

Final Time Complexity

Time Complexity: O(n)

This means the time to update grows in a straight line with the number of servers you replace.

Common Mistake

[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.

Interview Connect

Understanding how immutable infrastructure scales helps you explain deployment strategies clearly and shows you grasp how cloud resources behave as they grow.

Self-Check

"What if we changed from replacing all servers to updating them in place? How would the time complexity change?"