0
0
Terraformcloud~5 mins

Module composition patterns in Terraform - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Module composition patterns
O(n)
Understanding Time Complexity

When using modules in Terraform, it's important to understand how the number of modules affects the work Terraform does.

We want to know how the time to apply changes grows as we add more modules.

Scenario Under Consideration

Analyze the time complexity of this Terraform module composition.


module "network" {
  source = "./modules/network"
  count  = var.network_count
}

module "compute" {
  source = "./modules/compute"
  count  = var.compute_count
}

module "storage" {
  source = "./modules/storage"
  count  = var.storage_count
}

This code creates multiple instances of three different modules based on input counts.

Identify Repeating Operations

Look at what repeats when Terraform runs this code.

  • Primary operation: Creating each module instance involves API calls to provision resources inside that module.
  • How many times: The total number of module instances is the sum of all counts (network_count + compute_count + storage_count).
How Execution Grows With Input

As you increase the number of modules, the work grows in a simple way.

Input Size (total modules)Approx. API Calls/Operations
10About 10 module creations
100About 100 module creations
1000About 1000 module creations

Pattern observation: The number of operations grows directly with the number of modules added.

Final Time Complexity

Time Complexity: O(n)

This means the time to apply grows in a straight line as you add more modules.

Common Mistake

[X] Wrong: "Adding more modules won't affect apply time much because modules are just code."

[OK] Correct: Each module creates real resources, so more modules mean more API calls and longer apply times.

Interview Connect

Understanding how module counts affect apply time helps you design scalable infrastructure and explain your choices clearly.

Self-Check

"What if modules were nested inside other modules? How would that change the time complexity?"