The End of the State File: Why Platform Engineering is Migrating from Terraform to Crossplane
Terraform is a static execution engine that observes cloud infrastructure only when invoked by a human or CI/CD runner; managing high-velocity database fleets through centralized state-file locks guarantees pipeline contention, drift collisions, and unforced rollbacks.
TL;DR
- Problem: Shared
terraform.tfstatelocks serialize concurrent pull requests, and staticapplyruns silently revert out-of-band emergency console fixes.- Answer: Keep static foundational infrastructure (VPCs, EKS clusters) in OpenTofu/Terraform and move high-velocity runtime database vending to Crossplane XRDs and Pipeline Composition Functions.
- Watch out: Monolithic providers bloat Kubernetes API server memory (~3 MiB per active CRD),
managementPoliciesoverridedeletionPolicy: OrphanifDeleteis listed, and continuous reconciliation will revert incident fixes unless paused withObserve.
Situation
Platform engineering teams supporting hundreds of containerized microservices across AWS, Azure, and Google Cloud have standardized on Infrastructure as Code (IaC) anchored in Terraform or OpenTofu. Under the classic GitOps-with-CLI model, platform teams codify Amazon Aurora clusters, KMS keys, DB subnet groups, and IAM policies into HCL modules backed by a remote state file in Amazon S3 with DynamoDB locking.
When an application team needs a new database or an instance class change, a developer opens a Pull Request modifying .tf variables. A CI/CD runner runs terraform plan, posts the diff, waits for platform review, and acquires an exclusive state lock to run terraform apply. That linear workflow works well for small teams and slowly changing foundational networks. Once dozens of product squads submit concurrent database changes daily, however, the centralized state file and one-shot execution model become the primary operational bottleneck.
The Problem
Static, state-file-driven IaC engines fail at high-velocity database vending due to three structural constraints:
- Global State-File Lock Serialization: Terraform acquires an exclusive distributed lock on
terraform.tfstateduring every plan-and-apply cycle. Because cloud database operations such as creating an RDS instance, modifying parameter groups, or rotating KMS keys routinely take 8 to 15 minutes per run, even 8 concurrent pull requests against a shared state file serialize into a 60-to-120-minute queue (Error acquiring the state lock). Splitting a monolith into dozens of small workspaces reduces lock contention, but introduces fragileterraform_remote_statelookups and multi-stage Terragrunt dependency graphs that slow down plans and break when upstream outputs shift. - Static Drift Blindness (“2:00 AM Drift Collision”): Terraform has zero continuous awareness of live cloud state between CI/CD runs. Suppose an on-call SRE scales an Aurora primary from
db.r6g.xlargetodb.r6g.4xlargein the AWS Console at 02:00 AM to stop a CPU saturation incident. If a developer merges an unrelated billing-tag PR twelve hours later before the console change is backported to HCL,terraform applytreats the emergency scale-up as drift and scales the primary back down—re-triggering the outage. - Leaky Cloud Primitives and Control Plane Memory Tax: Application developers should not have to debug VPC subnet groups, KMS key policies, or HCL state errors just to provision a PostgreSQL instance. At the same time, moving to Kubernetes-native control planes introduces its own hard resource constraint: each active Custom Resource Definition (CRD) consumes roughly 3 MiB of Kubernetes API server RAM, so installing a monolithic cloud provider with 400+ CRDs consumes over 1.2 GiB of API server memory before controller informer caches even begin watching
SecretandConfigMapobjects.
How can platform teams eliminate state-file lock contention and continuous drift blindness without trading one operational bottleneck for an overloaded Kubernetes control plane?
Options Considered
Platform teams scaling self-service database provisioning have three main architectural paths.
| Architecture Option | What It Gets Right | Where It Breaks | Decision |
|---|---|---|---|
| Monolithic Terraform / OpenTofu | Single dependency graph; no Kubernetes control plane required | Global tfstate lock queues concurrent PRs; blind to drift between runs | Rejected for runtime database vending |
| Fragmented Workspaces / Terragrunt | Shrinks blast radius and lock scope per service or team | Fragile terraform_remote_state coupling; developers still debug HCL | Rejected as primary developer API |
| OpenTofu (Base) + Crossplane (Runtime) | OpenTofu boots static VPC/EKS once; Crossplane vends DBs via XRD API with continuous reconciliation | Requires operating a Tier-0 multi-AZ Kubernetes cluster for Crossplane | Selected for high-velocity runtime vending |
Monolithic Terraform is rejected for application-facing database vending because lock serialization and manual-fix reversion scale poorly with team count. Fragmenting into hundreds of micro-workspaces reduces lock contention, but forces platform engineers to maintain brittle cross-state plumbing while still exposing HCL to developers. Combining OpenTofu for static foundational layers (VPCs, subnets, base EKS clusters) with Crossplane for runtime database Claims captures continuous reconciliation without putting the control plane’s own bootstrap in a circular dependency.
The Kubernetes-Native Control Plane (Crossplane)
Crossplane extends Kubernetes Custom Resource Definitions and controller reconciliation loops into a continuous cloud control plane. Instead of running a CLI binary in CI/CD and exiting, Crossplane stores desired state per resource in Kubernetes etcd and reconciles against cloud APIs on a continuous loop.
1. XRDs, Pipeline Composition Functions, and Claims
Crossplane separates the developer contract from cloud implementation across three layers:
- Composite Resource Definition (XRD): Defines a custom Kubernetes API schema (for example,
CompositePostgresInstancewith claimPostgresInstanceClaim) exposing only approved parameters such asstorageGBandenvironment. - Composition (
mode: Pipeline): Modern Crossplane replaces repetitive YAML Patch-and-Transform rules with Composition Functions. Each function is packaged as an OCI container image and runs as an isolated gRPC server inside the cluster. When Crossplane reconciles a Composite Resource, it acts as a gRPC client sending aRunFunctionRequestcontaining the observed state, pipeline context, and inline inputs. The function (authored in Go, Python, or KCL) executes validation, resource templating, or policy checks and returns aRunFunctionResponsecontaining the desired composed resources (Instance,SubnetGroup,KMSKey). Multiple functions chain sequentially in thepipelinearray so one step can validate inputs, a second can render cloud resources, and a third can inject compliance tags—without risking core Crossplane controller stability if a custom function crashes. - The Claim: Application teams commit a concise Kubernetes manifest alongside their Helm or Kustomize deployment via ArgoCD or Flux, never touching HCL or cloud IAM credentials:
apiVersion: platform.enterprise.com/v1alpha1
kind: PostgresInstanceClaim
metadata:
name: checkout-database
namespace: checkout-service
spec:
storageGB: 200
environment: production
2. Continuous Level-Triggered Reconciliation
Unlike Terraform’s edge-triggered CLI runs, Crossplane controllers execute level-triggered reconciliation loops. By default, Crossplane managed resource controllers poll external cloud APIs every 1 minute (1m) to detect drift. Because each managed resource is an independent object in etcd, hundreds of teams can submit database updates concurrently without a global state lock; the Kubernetes API server serializes individual resource writes via optimistic concurrency (resourceVersion) rather than locking an entire environment. For resources that rarely change, operators override the default frequency per resource using crossplane.io/poll-interval: 30m to conserve cloud API quotas. Crossplane also attaches finalizers (finalizer.managedresource.crossplane.io) to managed resources so etcd does not purge a Kubernetes object until external teardown—or orphan detachment—completes cleanly.
3. Modular Providers and Managed Resource Definitions (MRDs)
Installing monolithic provider packages (provider-aws) loads hundreds of CRDs into the Kubernetes API server and expands controller informer caches. Production Crossplane deployments install scoped modular Upbound providers—such as provider-aws-rds and provider-aws-kms—and use Managed Resource Definitions (MRDs) plus crossplane-runtime v2.4+ caching optimizations so unused resource schemas remain inactive rather than consuming API server memory.
4. Deletion Governance: managementPolicies and deletionPolicy
Stateful databases require strict protection against accidental kubectl delete namespace commands. Historically, teams relied solely on deletionPolicy: Orphan so deleting the Kubernetes object left the cloud RDS instance intact. In modern Crossplane, managementPolicies take precedence over deletionPolicy when custom policies are specified: if Delete is included in managementPolicies, Crossplane will destroy the cloud database even when deletionPolicy: Orphan is set. Production compositions must omit Delete from managementPolicies alongside deletionPolicy: Orphan:
apiVersion: rds.aws.upbound.io/v1beta1
kind: Instance
metadata:
name: production-customer-db
spec:
managementPolicies: ["Create", "Update", "Observe", "LateInitialize"]
deletionPolicy: Orphan
forProvider:
region: us-east-1
instanceClass: db.r6g.2xlarge
allocatedStorage: 500
During an active incident where an on-call engineer needs to scale a database in the AWS Console without Crossplane reverting the change 60 seconds later, operators temporarily patch the resource to managementPolicies: ["Observe"] so Crossplane tracks status without issuing mutating Update calls.
5. Zero-Trust Credential Delivery and Upjet Schema Lag
By default, Crossplane writes generated database endpoints, usernames, and passwords into standard Kubernetes Secret objects inside the Claim’s namespace via writeConnectionSecretToRef. Because Kubernetes Secret values are only base64-encoded rather than encrypted at the application RBAC layer, any principal or CI job with kubectl get secrets access in that namespace can read production credentials. Production architectures avoid this by pairing Crossplane with HashiCorp Vault or AWS Secrets Manager and syncing short-lived credentials into pods through the External Secrets Operator (ESO). Additionally, when a cloud provider launches a new RDS parameter or engine version before Upjet regenerates the modular provider schema, teams temporarily bridge the gap using provider-terraform for that single attribute rather than abandoning the control plane.
How It Rolls Out
Migrating an existing Terraform-managed database fleet to Crossplane without downtime requires adopting resources in read-only Observe mode before transferring write ownership.
- Phase 1 — Tier-0 Bootstrap in OpenTofu: Retain foundational VPCs, subnets, and the dedicated multi-AZ Kubernetes control plane cluster in OpenTofu/Terraform. Verify
etcdsnapshot backups and control-plane HA before onboarding workloads. - Phase 2 — Modular Providers and Pipeline XRDs: Install scoped modular providers (
provider-aws-rds) and OCI-packaged Composition Functions (mode: Pipeline). Validate rendered resource DAGs in CI before applying to the cluster. - Phase 3 — Non-Destructive Import via
Observe: Create Crossplane Managed Resources referencing existing RDS identifiers viacrossplane.io/external-name, withmanagementPolicies: ["Observe"]anddeletionPolicy: Orphan. Confirm Crossplane reportsSynced: TrueandReady: Truewith zero schema mismatches. Rollback: Delete the Crossplane CR cleanly without touching the live database. - Phase 4 — State Transfer and Enforcement: Remove the resource from Terraform state (
terraform state rm) so two control planes never mutate the same RDS instance, then updatemanagementPoliciesto["Create", "Update", "Observe", "LateInitialize"](omittingDelete). Route database credentials through External Secrets Operator or HashiCorp Vault rather than raw plaintext KubernetesSecretobjects.
In Practice
Documented system behaviors across Terraform, Kubernetes, and Crossplane explain both the gains and the operational guardrails required in production:
- Terraform Lock Serialization Behavior: Terraform’s S3 backend with DynamoDB locking acquires a single-writer lock per state key for the duration of
planandapply. On long-running RDS or Aurora operations, that lock blocks all unrelated changes sharing the same state file, forcing teams either to wait in CI queues or to split state into fragmented workspaces linked byterraform_remote_state. - Crossplane
managementPoliciesPrecedence: Crossplane’s official Managed Resources specification documents that custommanagementPoliciesoverridedeletionPolicy. Teams migrating from older manifests that only setdeletionPolicy: Orphanmust verify thatDeleteis explicitly absent frommanagementPoliciesand enforce that invariant with OPA Gatekeeper or Kyverno admission policies. - Controller-Runtime and CRD Memory Behavior: Crossplane’s provider architecture documentation notes that each active CRD consumes roughly 3 MiB of Kubernetes API server memory and increases informer cache footprints. Moving from monolithic providers to modular family packages (
provider-aws-rds) andcrossplane-runtimev2.4+ cache scoping eliminates unnecessary OpenAPI andSecretcaching overhead. - Pattern Acknowledgment: I have not personally migrated a 280-microservice fleet in a single cutover, but the documented architectural pattern across Crossplane and CNCF platform engineering references is consistent: use OpenTofu/Terraform for static cluster foundations, adopt existing databases in
Observemode, and enforceOrphanplus non-Deletemanagement policies on every stateful resource.
Where It Breaks
Continuous control loops introduce distinct failure modes that static CLI tools never encounter.
| Failure Mode | Breaks How | Detect | Mitigate |
|---|---|---|---|
| Provider reconciliation throttling storm | Hundreds of CRs polling cloud APIs every 1m hit ThrottlingException | Provider pod logs showing 429/throttling errors; rising Ready: False latency | Set crossplane.io/poll-interval (e.g., 15m–30m) on stable resources |
managementPolicies precedence trap | Custom managementPolicies includes Delete, destroying DB despite deletionPolicy: Orphan | Admission audit or catastrophic deletion on namespace/CR removal | Omit Delete from managementPolicies and block via Kyverno/OPA |
| Incident drift reversion | Crossplane reverts an emergency AWS Console scale-up within 60 seconds | Console change disappears; provider events show Update reconciliation | Patch CR to managementPolicies: ["Observe"] during active incidents |
| Monolithic CRD memory exhaustion | Installing full provider-aws loads hundreds of CRDs (~3 MiB each) into API server RAM | API server OOMKills or slow kubectl discovery responses | Install scoped modular providers (provider-aws-rds) and use MRDs |
| Circular Composition dependencies | Composition DAG creates mutual dependency between KMS key, IAM role, and RDS subnet group | Resources remain stuck in Ready: False / Synced: False | Enforce unidirectional DAGs and validate Composition Function outputs in CI |
| Plaintext Kubernetes Secret exposure | Crossplane writes DB passwords to standard Secret objects readable via kubectl get secrets | RBAC audit shows broad namespace secret read permissions | Sync credentials via Vault or AWS Secrets Manager + External Secrets Operator |
Before cutting over production namespaces, validate your admission webhook by attempting to apply a CompositePostgresInstance claim with managementPolicies containing "Delete" or missing deletionPolicy: Orphan. Confirm that the Kubernetes API server rejects the manifest at admission time rather than allowing a controller to schedule destructive cloud API calls later.
Key Takeaways
- Use OpenTofu for foundations and Crossplane for runtime vending: Static VPCs and base EKS clusters belong in one-shot IaC; high-velocity developer database requests belong in continuous Kubernetes control loops.
- Pipeline Composition Functions are OCI gRPC services, not Wasm: Author composition logic in Go, Python, or KCL inside containerized gRPC servers (
mode: Pipeline) instead of brittle YAML Patch-and-Transform blocks. - Omit
DeletefrommanagementPolicieson every production database: CustommanagementPoliciesoverridedeletionPolicy: Orphan; enforce non-destructive policies with admission webhooks. - Use
Observemode for both safe imports and incident freezes: Import existing Terraform databases withmanagementPolicies: ["Observe"]before runningterraform state rm, and switch back toObserveduring Sev-1 console mitigations. - Scope providers to protect
etcdand API server RAM: Replace monolithic cloud provider packages with modular family providers (provider-aws-rds) and tunecrossplane.io/poll-intervalto avoid cloud API throttling.
What to Do Next
- Problem: Determine whether shared
tfstatelock queues and out-of-band drift reversions are throttling database delivery. - Solution: Split static infrastructure (OpenTofu) from self-service database vending (Crossplane XRDs + Pipeline Composition Functions).
- Proof: Measure CI/CD state-lock wait times and drift-reversion incidents over two sprints; if teams wait on shared locks or hesitate to use the AWS Console during incidents, a continuous control plane is justified.
- Action: Stand up Crossplane on a non-production EKS cluster with
provider-aws-rds, define aCompositePostgresInstanceXRD withdeletionPolicy: OrphanandDeleteomitted frommanagementPolicies, and test adopting an existing staging RDS instance inObservemode before enablingUpdate.