Module composition patterns in Terraform - Time & Space 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.
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.
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).
As you increase the number of modules, the work grows in a simple way.
| Input Size (total modules) | Approx. API Calls/Operations |
|---|---|
| 10 | About 10 module creations |
| 100 | About 100 module creations |
| 1000 | About 1000 module creations |
Pattern observation: The number of operations grows directly with the number of modules added.
Time Complexity: O(n)
This means the time to apply grows in a straight line as you add more modules.
[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.
Understanding how module counts affect apply time helps you design scalable infrastructure and explain your choices clearly.
"What if modules were nested inside other modules? How would that change the time complexity?"