Abstracting the Cloud: Building an Enterprise Database Vending Machine API
If application developers are writing raw Terraform modules or clicking through cloud consoles to provision databases, your organization does not operate a platform; it operates an unmanaged scripting surface where public-exposure drift, speculative over-sizing, and abandoned Day-2 lifecycles are inevitable.
TL;DR
- Problem: Exposing raw Terraform modules leaks 80+ cloud parameters, lets security-group drift (
0.0.0.0/0,publicly_accessible = true) slip past PR reviews, and encourages speculative hardware over-sizing.- Answer: Replace developer-authored HCL with an intent-driven Database Vending Machine API (Go + OPA + IPAM + Temporal/Crossplane + Vault Database Secrets Engine).
- Watch out: A
/28AWS subnet leaves only 11 usable IPs (risking Multi-AZ ENI exhaustion), RDS automated backups cap at 35 days, and Day-1 vending fails if you omit Day-2 storage, extension, and TTL endpoints.
Situation
Organizations running multi-cloud workloads across Amazon Web Services (AWS), Microsoft Azure, and Oracle Cloud Infrastructure (OCI) rely on managed data stores—Amazon Aurora PostgreSQL, Amazon RDS, Azure Database for PostgreSQL Flexible Server, and OCI Exadata Database Service—to back application microservices. To standardize provisioning, platform engineering teams typically publish reusable Terraform or OpenTofu modules in an internal registry. Application developers clone a module, fill in instance classes, storage sizes, VPC subnet IDs, and backup windows, and open a Pull Request for CI/CD execution.
That module-sharing model works when a single platform team supports a handful of services. As an organization scales to dozens of autonomous product squads, however, raw IaC modules expose too many low-level cloud flags. Application engineers spend sprints debugging subnet group errors and KMS key policies, while platform engineers become a manual PR-review bottleneck.
The Problem
Exposing raw cloud primitives—even wrapped inside Terraform modules—breaks governance and velocity across four concrete constraints:
- Attribute Explosion and Security Drift: A single
aws_db_instanceoraws_rds_clusterresource exposes over 80 configuration attributes and depends on half a dozen adjacent resources: KMS customer-managed keys, DB parameter groups, DB subnet groups, VPC security groups, IAM authentication roles, and log exports. When a developer hits a connectivity timeout during testing and temporarily setscidr_blocks = ["0.0.0.0/0"]andpublicly_accessible = true, a platform reviewer scanning a 1,000-line PR can easily miss the change. - Subnet CIDR Exhaustion: AWS enforces a minimum IPv4 subnet size of
/28(16 IP addresses) and reserves 5 addresses per subnet (network, VPC router, Amazon DNS, future use, and broadcast), leaving only 11 usable IP addresses per subnet. Because Multi-AZ RDS DB subnet groups must span at least two Availability Zones and consume extra Elastic Network Interfaces (ENIs) during failover, minor-version patching, blue/green deployments, and read-replica scaling, a single Multi-AZ cluster with replicas can consume 6 to 10 IPs in one AZ—pushing/28blocks straight intoInsufficientFreeAddressesInSubnetfailures. Production database tiers require/26(59 usable IPs) or/24(251 usable IPs) subnets managed centrally via IPAM. - Backup Retention Ceiling Misalignment: Compliance regimes such as PCI-DSS frequently mandate 7-year (
2,555-day) audit retention. However, Amazon RDS and Aurora automated backups cap at 35 days maximum retention. Developers who assume settingbackup_retention_periodcovers multi-year compliance either hit API validation errors or miss the requirement to pair 35-day PITR with AWS Backup vaults or immutable S3 snapshot exports. - Speculative Over-Sizing and Day-2 Abandonment: When asked to pick between
db.r6g.large(2 vCPU, 16 GiB RAM) anddb.r6g.8xlarge(32 vCPU, 256 GiB RAM), developers defensively over-provision to avoid latency incidents—a 16x compute and memory jump for a low-throughput microservice. Worse, static Day-1 Terraform modules do not govern Day-2 operations—such as minor engine patching, extension whitelisting, or credential rotation—leaving databases as unmanaged pets.
How can platform teams replace leaky Terraform modules with an intent-driven Database Vending Machine API that translates business requirements into governed, multi-cloud infrastructure and zero-trust credentials?
Options Considered
Platform engineering teams replacing raw Terraform PRs generally evaluate three architectures.
| Architecture Option | What It Gets Right | Where It Breaks | Decision |
|---|---|---|---|
| Shared Terraform / OpenTofu Modules | Fastest to bootstrap; zero custom control-plane services to operate | Leaks HCL/cloud attributes; manual PR bottlenecks; speculative sizing | Rejected as developer interface |
| Go Vending Machine API + Temporal | Clean JSON intent contract; tight integration with OPA, external IPAM, and Vault dynamic creds | Platform team must maintain the Go service and hot-reloaded sizing matrices | Selected for multi-cloud + IPAM orchestration |
| Crossplane XRDs + Pipeline Functions | Declarative Kubernetes API with built-in continuous drift reconciliation | Requires Kubernetes everywhere; awkward for non-K8s REST/IPAM workflows | Viable alternative when K8s is the universal control plane |
Shared Terraform modules are rejected as the developer-facing boundary because they cannot prevent developers from editing security groups or guessing instance sizes inside HCL variables. Crossplane XRDs are a strong alternative for Kubernetes-first platforms, whereas a dedicated Go Vending Machine API backed by Temporal wins when the platform must integrate external enterprise IPAM (such as Infoblox), non-Kubernetes consumers, and multi-step compensation sagas across AWS, Azure, and OCI.
The API-Driven Vending Architecture: Intent-Based Infrastructure
The Database Vending Machine API inserts a strict four-layer control plane between application developers and cloud provider APIs.
1. The Declarative Intent Contract
Developers submit a business-centric JSON payload via an Internal Developer Portal (such as Backstage) or CLI. Infrastructure primitives—instance families, IOPS, subnet IDs, and KMS ARNs—are omitted from the schema:
{
"service_id": "checkout-payment-service",
"owner_team": "checkout-platform",
"environment": "production",
"database_engine": "postgresql",
"engine_version": "15",
"workload_profile": {
"expected_qps": 3500,
"storage_growth_gb_per_month": 50,
"read_heavy_ratio": 0.80
},
"compliance": {
"data_classification": "pci-dss",
"archive_retention_days": 2555,
"multi_az_required": true
},
"cloud_target": "aws"
}
Because publicly_accessible and kms_key_id do not exist in the contract, a developer cannot disable encryption or expose a database to the internet. When data_classification is pci-dss, the API enforces customer-managed KMS encryption, TLS 1.3 in transit, 35-day automated RDS/Aurora PITR, and an AWS Backup archive policy for the 2,555-day compliance window.
2. Policy Validation and Topology Calculation
Upon receiving an intent payload, the Go API runs a three-step translation pipeline:
- Phase 1 — OPA Rego Validation: Evaluates budget quotas, approved cloud regions, curated
extensions: []whitelists (such aspgvectorortimescaledb), and compliance constraints before touching any cloud API, returning actionable validation errors immediately if a rule fails. Because OPA rules live in versioned Rego bundles, security teams can tighten encryption or region rules across the entire vending surface without modifying Go application code or reviewing individual Terraform PRs. - Phase 2 — Topology and Hardware Sizing: Maps
expected_qpsandread_heavy_ratioto benchmarked instance classes (db.r6g.large2 vCPU / 16 GiB,db.r6g.xlarge4 vCPU / 32 GiB,db.r6g.2xlarge8 vCPU / 64 GiB,db.r6g.4xlarge16 vCPU / 128 GiB). Crucially, sizing rules belong in hot-reloaded YAML config maps rather than hardcoded Go switches so newer Graviton3 (db.r7g) shapes adopt without recompiling the API. Also note the storage distinction: standard RDS PostgreSQL usesMaxAllocatedStoragefor EBS Storage Autoscaling, whereas Amazon Aurora cluster volumes grow automatically up to 128 TiB (or 256 TiB depending on engine configuration) without aMaxAllocatedStorageparameter:
// Standard RDS PostgreSQL sizing with hot-reloaded tier matrix
func CalculateRDSTopology(p WorkloadProfile, c ComplianceSpec, m TierMatrix) InstanceSpec {
spec := InstanceSpec{
Engine: "postgres",
EngineVersion: "15",
MultiAZ: c.MultiAZRequired,
StorageEncrypted: true,
BackupRetention: 35, // AWS RDS/Aurora automated backup max
AllocatedGB: 100,
MaxAllocatedGB: 100 + (p.StorageGrowthGBPerMonth * 24),
}
spec.InstanceClass = m.MatchClass(p.ExpectedQPS) // e.g., db.r6g.2xlarge
if p.ReadHeavyRatio >= 0.70 && p.ExpectedQPS > 1000 {
spec.ReadReplicas = 2
}
return spec
}
- Phase 3 — IPAM and Security Isolation: Leases
/26(59 usable IPs) or/24(251 usable IPs) private subnets across at least two Availability Zones from enterprise IPAM, attaches security groups restricted to application worker nodes, and binds a dedicated KMS Customer Managed Key with annual rotation.
3. Zero-Trust Credential Delivery via Vault
Rather than letting developers pick passwords or storing static credentials in Git, the Vending API separates static configuration from dynamic database access in HashiCorp Vault:
- Database Bootstrap: Durable execution workers (Temporal or Crossplane) provision the database with a randomized 32-character root credential stored strictly in a restricted platform Vault KV v2 path (
secret/data/platform/db-roots/<service_id>). - Dynamic Credential Engine: The worker registers the new database with Vault’s Database Secrets Engine (
database/config/<service_id>anddatabase/roles/<app_role>). When an application requests credentials atdatabase/creds/<app_role>, Vault dynamically issues a short-lived PostgreSQL user with a bounded TTL and revokes it automatically on lease expiry. - Readiness-Gated Delivery and Durable Compensation: In Kubernetes, the External Secrets Operator (ESO) or Vault Agent Injector delivers credentials into pods and handles lease renewal before TTL expiration. The Vending API gates its final
PROVISIONEDstatus on secret-sync verification so pods do not boot intoCrashLoopBackOffbefore credentials land. Crucially, Temporal workflow workers wrap each provisioning step—IPAM lease, RDS creation, KMS binding, and Vault role registration—in a durable saga: if Vault registration fails after the cloud database is created, Temporal retries with exponential backoff or executes a compensation activity to quarantine the resource and release the IPAM CIDR block, preventing silent orphaned databases.
4. Day-2 Lifecycle Endpoints and Ephemeral TTLs
Provisioning is only half the contract; without governed Day-2 mutations, teams fall back to manual console edits. The Vending API exposes scoped PATCH /v1/databases/{service_id} endpoints for approved operational changes: raising MaxAllocatedStorage ceilings on standard RDS instances, enabling whitelisted extensions (pgvector, timescaledb) via parameter-group updates, and triggering point-in-time recovery clones into staging. For pull-request preview environments, the API enforces a mandatory ttl_hours field (such as 72 hours) and runs a scheduled reaper workflow that deletes expired test clusters, revokes their Vault roles, and returns their /26 subnet allocations to IPAM automatically.
How It Rolls Out
Shipping a Vending Machine API requires a staged rollout with Day-2 endpoints built alongside Day-1 provisioning.
- Phase 1 — Intent Contract and YAML Sizing Matrix: Define a minimal JSON schema covering 80% of standard PostgreSQL workloads and externalize instance mappings into versioned YAML config maps.
- Phase 2 — OPA Policies and IPAM Integration: Wire Rego compliance checks (
publicly_accessible == false, mandatory KMS, 35-day PITR + AWS Backup archive for regulated data) and automated/26subnet leasing across at least two AZs. - Phase 3 — Temporal Sagas and Vault Readiness Gates: Implement durable workflows with compensation rollbacks (so a failed Vault registration cleans up or quarantines the half-provisioned database) and token-bucket rate limiters against cloud
ThrottlingExceptionerrors. - Phase 4 — Portal Cutover and Day-2 Endpoints: Expose the template in Backstage, ship Day-2
PATCHendpoints (for storage ceiling bumps, curatedextensions: []whitelists such aspgvector, and 72-hour ephemeral preview TTLs), and retire raw developer Terraform PRs.
In Practice
Documented cloud provider constraints and platform engineering patterns explain why intent-driven APIs outperform raw module sharing:
- AWS Subnet and Backup Boundaries: AWS VPC documentation establishes that
/28subnets yield only 11 usable IP addresses after the 5 AWS-reserved addresses, creating ENI exhaustion risk during Multi-AZ RDS failover and maintenance. Likewise, Amazon RDS and Aurora documentation caps automated backup retention at 35 days—requiring an explicit archival tier (AWS Backup or S3 exports) whenever compliance mandates multi-year retention. - Vault KV v2 vs. Database Secrets Engine: HashiCorp Vault’s documented separation between KV v2 (
secret/data/...for static secrets) and the Database Secrets Engine (database/creds/<role>for dynamic, TTL-bound database users) eliminates static password sprawl and removes humans from routine credential rotation. - Crossplane and Copy-on-Write Convergence (2024–2026): Platform teams increasingly pair intent-driven portals with Crossplane XRDs for Kubernetes-native reconciliation and copy-on-write branching (such as Aurora Serverless v2 or Neon) for ephemeral pull-request databases with automated 72-hour teardown TTLs.
- Multi-Cloud Semantic Boundaries: Keeping
cloud_targetexplicit in the intent contract rather than forcing lowest-common-denominator cloud agnosticism prevents runtime surprises when workloads depend on cloud-specific features such as AWS IAM database authentication tokens versus Microsoft Entra ID authentication on Azure Flexible Server. - Pattern Acknowledgment: I have not personally operated a single Go vending service across 1,400 engineers, but the documented CNCF Internal Developer Platform pattern is consistent: hide cloud flags behind an intent contract, enforce compliance via OPA before provisioning, and pair durable execution with dynamic Vault leases.
Where It Breaks
Centralizing provisioning into a Vending Machine API shifts operational failure modes onto the platform team.
| Failure Mode | Breaks How | Detect | Mitigate |
|---|---|---|---|
| Hardcoded hardware mappings | Go switch locks fleet to db.r6g, missing newer db.r7g price-performance | FinOps audit shows stale instance families in new provisions | Externalize sizing matrices into hot-reloaded YAML config maps |
| IPAM CIDR exhaustion | Ephemeral preview DBs consume VPC /26 blocks without reclamation | Provisioning fails with SubnetAllocationException | Enforce 72-hour TTLs on preview DBs and automated IPAM reclamation |
| Multi-cloud semantic mismatch | Treating AWS RDS and Azure Flexible Server as identical breaks cloud-native IAM auth | App deployment fails when target_cloud changes | Keep target_cloud explicit in intent; bind cloud-specific auth per target |
| Vault secret sync race | Pod starts before ESO syncs credentials from Vault | Pod enters CrashLoopBackOff on missing DB env vars | Gate Vending API PROVISIONED readiness on confirmed K8s Secret sync |
| Locked-down parameter groups | Apps needing pgvector or timescaledb fail against rigid defaults | Extension CREATE EXTENSION rejected in staging | Expose a curated, OPA-validated extensions: [] whitelist in intent |
| Orchestrator crash mid-provision | Worker crashes after RDS creation but before Vault registration | Orphaned cloud DB running with no Vault record | Use Temporal or Crossplane durable sagas with compensation rollbacks |
| Burst CI/CD cloud throttling | Parallel test suites send 50+ create calls simultaneously | Cloud API returns ThrottlingException / RateExceeded | Add token-bucket rate limiters and durable task queues on outbound SDKs |
Key Takeaways
- Hide cloud flags behind business intent: Developers should specify QPS, growth rate, and compliance classification—never
cidr_blocks, KMS ARNs, or raw instance classes. - Encode cloud limits inside the API: Enforce
/26or/24subnets across two AZs, distinguish Aurora auto-growing storage from RDSMaxAllocatedStorage, and pair 35-day RDS PITR with AWS Backup for multi-year retention. - Use Vault’s Database Secrets Engine for runtime access: Reserve KV v2 (
secret/data/...) for static bootstrap roots and issue dynamic, TTL-bound credentials viadatabase/creds/<role>. - Build Day-2
PATCHand TTL teardown on day one: A vending API without storage expansion, curated extension whitelists, and ephemeral preview TTLs simply automates the creation of tomorrow’s unmanaged pets.
What to Do Next
- Problem: Identify whether developers are copy-pasting Terraform database modules, guessing instance sizes, or opening manual tickets for routine provisioning.
- Solution: Replace developer-authored HCL with an intent-driven Database Vending Machine API backed by OPA policies, IPAM subnet leasing, durable workflows, and Vault dynamic credentials.
- Proof: Audit your existing Terraform PRs and deployed RDS instances for public-access drift, undersized
/28subnets, and oversized instances running below 10% CPU. - Action: Draft a minimal JSON intent contract covering your primary PostgreSQL workload, write an OPA Rego rule blocking
publicly_accessible = trueand enforcing encryption, and wire a staging pipeline to Vault’s Database Secrets Engine before retiring raw module PRs.