Terraform uses a state file to track resources. When running terraform apply, it first loads the state file and checks its size. If the state file is large, for example over 20 MB, Terraform optimizes it by splitting or pruning unused resources. This reduces the state file size and improves performance. After optimization, Terraform plans and applies changes, then saves the updated state. It checks the state size again to ensure it remains manageable. This process helps Terraform run faster and more reliably when managing infrastructure at scale.