Skip to content
Tech Interview Prep
Technical interview guide

Self-Service Infrastructure

Letting teams provision what they need through an API or portal, with policy enforced automatically instead of manually.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed
Relevant for
Platform Engineer

Scope: AWS and Microsoft platform engineering guidance and HashiCorp Terraform/HCP Terraform documentation current 2026-08-31; confirm product-tier and version-specific policy features for the target deployment.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-3

Design the plan-and-apply workflow.

Answer

Assume a Terraform-like tool, remote state with locking, CI/CD, and a shared production environment. The plan is a pure function of four things: config, variables, provider/module versions, and the exact state snapshot. Apply mutates state. So a plan is only valid against the state serial it read. That single fact drives the workflow.

Core answer: freeze config, module and provider versions plus validated inputs. Read state under a lock or consistent read. Compute the plan: creates, updates, replacements, deletes, unknowns, cost, policy results. Persist the plan file with a hash, the state serial, actor, scope, and expiry. Approve. Before apply, re-read the state serial and compare. If it changed, re-plan. If not, acquire the lock, apply with short-lived credentials, stream status, verify outputs and effective policy, reconcile partial failure, retain audit.

Why the signed plan goes stale: Terraform state carries lineage and serial. The plan file stores the prior state serial. If another apply bumps the serial, Terraform refuses with "Saved plan is stale". That is the mechanism. It is not bureaucracy; it prevents your apply from deleting a resource someone else just created. Example: plan reads serial 41. A teammate applies and state becomes 42. Your apply errors. If you force it, you risk a destructive diff against state you never saw.

Trade-offs: plan expiry vs re-plan-on-apply. Expiry is cheap and bounds approval age, but it does not catch state changes. Re-plan-on-apply is safest but discards the exact diff a human approved. Manual approval gates catch intent; policy-as-code catches invariants like "no public buckets". Use both when blast radius is high. A lighter workflow is fine for a dev sandbox with a single writer and no shared state: skip approval, keep the lock.

Failure modes:

FailureDetectionCost
Lock contentionlock errorpipeline stalls; set -lock-timeout=5m instead of default 0s
State corruption mid-applystate serial mismatch, refresh shows half-createdmanual import/reconcile
Drift between plan and applystale plan errorre-plan
Partial applyapply exit code + refreshorphaned resources

Concrete numbers: Terraform's -lock-timeout defaults to 0s, so a contended lock fails immediately. Set 5m for CI. Plan TTL: 30 minutes is a common bound. Credential TTL: AWS STS AssumeRole defaults to 3600s; use 15-60 minutes for apply. These are examples, not universal defaults.

What changes the decision: if your backend has no locking or you are single-writer, drop the lock and approval gate. If you have compliance or shared prod, keep signed plan, TTL, and re-check serial before apply.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Secure infrastructure state and plans.

Answer

The 90-second answer

Two assumptions: Terraform (or OpenTofu) with a remote backend, and more than one engineer or pipeline writing to the same environment. With one person on one laptop the answer is different, but as soon as a second writer exists, state is shared mutable data with credentials inside it, and I treat it like a production database.

State is a JSON document recording every attribute of every managed resource, including values you marked sensitive. sensitive = true redacts CLI output only; the plaintext is still in state and in the binary plan file from terraform plan -out=tfplan. So the controls are: keep state and plan files off laptops and out of git, put state in a backend with encryption, versioning and locking, and shrink what lands in it using ephemeral values and write-only arguments.

Why write-only actually avoids persistence

A write-only argument is passed to the provider at apply time and never serialised into state. The provider stores the value server-side (RDS keeps the master password), and Terraform tracks only a version counter so it knows when to re-send. Ephemeral values (Terraform 1.10+) work the same way for data sources and variables: available during the run, absent from the state file. Write-only arguments need Terraform 1.11+ and a provider that supports them: AWS provider 5.79+ for things like password_wo.

Choosing a backend

BackendLockingEncryptionAccess controlPick it when
S3 (+ DynamoDB, or use_lockfile since TF 1.10)DynamoDB conditional write, or native lockfileencrypt = true gives SSE-S3; kms_key_id switches to SSE-KMSIAM, bucket policy, CloudTrail data eventsYou are on AWS and want to own the key
GCSbuilt-in object lockGoogle-managed or CMEKIAM + Cloud Audit LogsGCP shop
Azure Blob (azurerm)blob leaseplatform key or Key Vault keyEntra ID + diagnostic logsAzure shop
Terraform Cloud / Enterprisebuilt-invendor-managed at restworkspace RBAC, audit log, state versioningSmall platform team that would rather not run a lock table
Local disk or gitnonenonenoneThrowaway sandbox only

The deciding questions are who holds the encryption key, whether you need per-workspace RBAC and an audit trail, and whether you can operate the locking table.

Failure modes, detection, recovery cost

  • State committed to git. Detection: secret scanning on push (gitleaks, GitHub secret scanning) and a CloudTrail GetObject on the state bucket from an unexpected principal. Cost: every credential in that state is burned. Rotate all of them, then rewrite history.
  • Stale lock. Symptom is Error acquiring the state lock with a LockID. Confirm the holder is dead before terraform force-unlock <LOCK_ID>; forcing while a run is live gives two writers and a corrupted state.
  • Lost backend. Bucket deleted or region unavailable. Recovery is the last object version, so RPO equals the time since the last successful apply: versioning plus a cross-region replica is what makes that recoverable at all.
  • Unauthorized modification. Diff terraform state pull against the previous state version and correlate with CloudTrail PutObject events. A changed attribute with no matching apply in CI is the signal.

Plan files get the same treatment as state: if CI persists tfplan as an artifact, it is a secret-bearing file with a retention clock. Applying in the same job avoids writing it to disk at all.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Recover from lost or corrupted infrastructure state.

Answer

I'll assume we're using Terraform with a remote backend like S3 and DynamoDB locking, as that's the most common setup for infrastructure state. The state file is the source of truth mapping your configuration to real infrastructure. If it's lost or corrupted, you risk duplicating or destroying resources. My first move is to freeze all writers: stop CI/CD pipelines, revoke write access to the state bucket, and prevent any terraform apply. Then preserve evidence: copy the current state, logs, and recent plans. Next, determine the scope: which workspace, which version, and when the corruption occurred. Then restore the latest verified backup into isolation, not directly into production. For example, if S3 versioning is enabled, list versions with aws s3api list-object-versions --bucket mybucket --prefix terraform.tfstate and download the last known good version. Push that to a temporary backend or local file. Then run terraform plan to compare against real infrastructure. Use terraform state mv, terraform state rm, and terraform import to fix bindings. Never recreate stateful resources like databases to make a plan clean. Once the plan is no-change or explicitly understood, canary a safe read, then resume one writer and monitor.

Why does state drift? Manual changes in the cloud console, provider API changes, or concurrent writes without locking. terraform refresh (or apply -refresh-only in Terraform 0.15+) updates state with real-world attributes, but if state is corrupted, it can make things worse. To prove ownership, check the resource ID in state against the provider's console or API. For example, an AWS instance ID i-123 in state should match a running instance. If it doesn't, you have a stale binding. Failure modes: recreating a database because state lost its binding causes data loss; stale bindings cause Terraform to try to create duplicates; missing bindings cause Terraform to think resources don't exist. Detection: terraform plan shows unexpected creates/destroys; CloudTrail logs show manual changes; state file checksum mismatch. Tradeoffs: restore is fast but may lose recent changes; import is precise but manual and error-prone. Restore is wrong if the backup is older than a critical change, or if the corruption is in the backup too. Costs: restoring from S3 takes seconds, but reconciling 1000 resources can take hours.

Here's a worked example. State file deleted, S3 versioning enabled. We list versions, find one from 2 hours ago, download it, push to a temporary backend, run terraform plan and see 5 resources missing and 2 stale. We use terraform import for the 5 and terraform state rm for the 2, then push to production. The plan is clean. We resume writers.

ApproachWhen to useCostRisk
Restore from backupBackup is recent and accurateSeconds to restore, hours to reconcileLosing changes since backup
Import missing resourcesBackup is stale or missing resourcesManual, error-proneIncorrect IDs, duplicate resources
Shell
# 1. Freeze writers
aws s3api put-bucket-policy --bucket mybucket --policy file://deny-write.json

# 2. List state versions
aws s3api list-object-versions --bucket mybucket --prefix terraform.tfstate

# 3. Download last good version
aws s3api get-object --bucket mybucket --key terraform.tfstate --version-id <version-id> backup.tfstate

# 4. Inspect backup
terraform show -json backup.tfstate | jq '.resources[] | .type + "." + .name'

# 5. Push to temporary backend
terraform state push backup.tfstate  # with temporary backend config

# 6. Compare with reality
terraform plan -refresh-only

# 7. Fix bindings
terraform import aws_instance.web i-1234567890abcdef0
terraform state rm aws_instance.old

# 8. Push to production
terraform state push backup.tfstate  # with production backend config, use -force if lineage differs

Prevention: enable S3 versioning, DynamoDB locking, restrict access, test restores regularly, use state file checksums, and monitor for corruption.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Recover from a stuck infrastructure state lock.

Answer

Assume Terraform 1.10+ with an S3 backend. If you're on DynamoDB locking, the lock is an item in the DynamoDB table; if you're on native S3 locking (use_lockfile = true), it's a .tflock object next to the state. DynamoDB locking still works but is deprecated. The lock is advisory: Terraform writes it before reading state and deletes it after. A dead process leaves it behind. terraform force-unlock deletes the record; it does not kill the writer. Terraform has no fencing token, so the only safe question is whether the old writer can still write.

In the first minute, read the error and get the lock ID, owner, operation, and created time. Don't force-unlock yet.

terraform plan
# Error: Error acquiring the state lock
# ID: 8f3c...

S3 native locking:

aws s3api head-object --bucket my-tf-state --key prod/terraform.tfstate.tflock

DynamoDB locking:

aws dynamodb get-item --table-name terraform-locks \
  --key '{"LockID":{"S":"my-tf-state/prod/terraform.tfstate"}}'

The Info attribute looks like {"ID":"8f3c...","Operation":"Apply","Who":"ci@runner-7","Version":"1.10.5","Created":"2025-01-15T10:00:00Z","Path":"my-tf-state/prod/terraform.tfstate"}. Terraform does not heartbeat the lock. Created is acquisition time, not last activity, so age alone is not proof.

SignalWriter aliveWriter stale
CI jobrunningcancelled or failed
Hostrunner existsterminated
Provider activityCloudTrail events in last 5mnone since Created
Lock ageunder 30mover 30m and no other signal

If the writer is alive, restore network or let it finish. If it is stale, back up state, then force-unlock with the exact ID.

terraform state pull > backup-$(date +%s).tfstate
aws s3 cp s3://my-tf-state/prod/terraform.tfstate \
  s3://my-tf-state-backup/prod/terraform.tfstate.$(date +%s)
terraform force-unlock 8f3c...
terraform plan -lock-timeout=5m

The default -lock-timeout is 0s, so Terraform fails immediately. 5m makes it wait for a live writer instead of forcing.

Plan detects partial effects. Example: apply created aws_instance.web but died before the state write; plan says create. terraform import aws_instance.web i-123 then plan again. If state has a resource the provider deleted, terraform state rm or apply.

Force-unlocking while the old writer is alive gives two applies: lost update, duplicate resources, orphaned cloud resources. Detection is two RunInstances calls with the same tag in CloudTrail, or a state serial conflict. S3 versioning lets you restore the previous state. Enable S3 versioning and DynamoDB point-in-time recovery. In CI, set -lock-timeout=5m, cancel jobs on timeout, and alert when a lock is older than 30m.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Handle infrastructure drift.

Answer

What I'd say first

Drift is a difference between three things: what the config declares, what the state file records, and what the provider's API returns right now. Before touching anything I ask which system owns each field: Terraform, a platform controller, or an external process like an autoscaler or a security scanner. That answer decides whether drift is a bug to revert or a fact to record. Assume Terraform 1.x with a remote backend and the AWS provider.

How detection actually works

terraform plan refreshes by default: it calls the provider's read API for every resource in state, then diffs the result against config. Drift therefore shows up as an ordinary plan diff. To see only what changed in the real world, terraform plan -refresh-only (Terraform 0.15.4+) suppresses the config diff; terraform apply -refresh-only writes the observed values into state without changing infrastructure.

CloudFormation is separate: aws cloudformation detect-stack-drift returns DRIFTED, IN_SYNC, NOT_CHECKED or UNKNOWN, and describe-stack-resource-drifts gives per-resource MODIFIED/DELETED. It only covers properties CloudFormation supports for drift detection, so a clean result isn't proof of no drift. AWS Config's managed rule cloudformation-stack-drift-detection-check runs it on a schedule.

Kubernetes: kubectl diff -f manifest.yaml shows what apply would change. With server-side apply, kubectl get ... -o yaml --show-managed-fields shows which field manager owns each field, and a second writer fails with Apply failed with 1 conflict: conflict with "...".

Worked trace

A Terraform-managed security group; someone added an ingress rule from the console during an incident.

  1. terraform plan -refresh-only → ~ aws_security_group.app, ingress gains one rule.
  2. Classify and act:
classexampleaction
unauthorized divergenceconsole-added ingress rulerevert: terraform apply with unchanged config removes it
legitimate emergency changesame rule, needed for the incidentcodify: add it to config, terraform apply -refresh-only, then terraform plan must be empty
externally owned fieldautoscaler-set desired_capacitylifecycle { ignore_changes = [desired_capacity] }, or Argo CD ignoreDifferences; record, don't fight
  1. Verify: terraform plan prints "No changes." Then alert if the same resource drifts again inside 24 h. Recurrence means something is still writing.

Failure modes

  • Two reconcilers on one object. Argo CD selfHeal plus a Terraform apply on the same Kubernetes object flips a field back and forth: OutOfSync → Synced → OutOfSync with no config change, and audit logs alternating between two writers. One owner per field.
  • Destructive auto-correction. A plan that replaces instead of updates, changing identifier or availability_zone on an RDS instance is ForceNew, turns a drift fix into an outage. lifecycle { prevent_destroy = true } makes the plan fail instead.
  • Provider normalization. AWS reorders tags and normalizes IAM policy JSON, producing a diff you didn't cause. Fix it in config; don't paper over it with ignore_changes.
  • Renamed ownership. A resource deleted and recreated out of band leaves state pointing at a dead ID. terraform state rm then terraform import (or an import block, Terraform 1.5+) reattaches it.

Decision rule

If the live value is what you want, codify it. If it isn't, revert it. If you don't own the field, stop managing it. Never let a reconciler auto-revert a field it doesn't own.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Import existing infrastructure into self-service management.

Answer

Core answer (first 90 seconds)

Assume Terraform 1.5+ with a remote backend, and that the resources are stateful enough that recreation is not acceptable. The answer is: adopt by import into an isolated state, drive the plan to a no-op, then hand over ownership. The first apply must never be the first time anyone sees the diff.

Say it this way: "Import writes an address-to-real-ID mapping into state. It does not read your config and it does not call the create API. So the plan immediately after import is the diff between what you wrote and what already exists: that diff is the entire job."

Mechanism

terraform import aws_s3_bucket.logs my-bucket writes state only; the import ID for aws_s3_bucket is the bucket name. Terraform 1.5 replaced the CLI form with an import block, which is reviewable in a pull request and can generate config:

HCL
import {
  to = aws_s3_bucket.logs
  id = "my-bucket"
}

terraform plan -generate-config-out=generated.tf writes a config skeleton. Treat it as a starting point, not a review: it emits every attribute the provider reads, including ones you do not want to manage. Then terraform plan -refresh-only shows drift without proposing changes, and plain terraform plan shows the real diff. Enable apply only when that plan is empty.

Alternatives

approachwhen it winscost
import into the existing statea handful of resources, one owning teamblast radius is the whole state
import into a new isolated state, then terraform state mvbrownfield at scaletwo states to reconcile
rewrite and recreatestateless and cheap, e.g. a dev namespacedata loss if you guessed wrong
per-team staging statemany teams, unclear ownershipslower, needs a merge step

Failure modes

  • Wrong workspace. Importing prod into the dev state means the next dev apply destroys prod. Lock the workspace and set lifecycle { prevent_destroy = true } on stateful resources before the first plan.
  • Config drift. Import does not tell you which attributes are unmanaged. A bucket imported without acl in config shows a diff on the next plan; ignore_changes hides that, which is a decision, not a fix.
  • Forced replacement. Provider version differences change defaults, and a changed default shows as a replace. Read the plan for # forces replacement.
  • Secrets in state. State is plaintext JSON. Use SSE-KMS on the backend; Terraform 1.10 added native S3 locking via use_lockfile = true, so a DynamoDB lock table is no longer required on new backends. Never use a local backend for this.
  • Partial import. A resource with children, such as aws_route53_record under a zone, needs every address imported; a missing child shows as a create.

When not to import

If the resource is stateless and cheap to recreate, rewriting is faster and leaves no legacy config behind. If ownership is unclear across teams, per-team staging states beat one large import. If the resource is a legacy monolith with no clean address mapping, adopt the boundary (the VPC, the account) and leave the interior unmanaged. Partial adoption is a valid end state.

Handover

Ownership transfer is explicit: the importing team writes the runbook, the state moves to the owning team's backend, and the import pull request is the audit record. Crossplane does the same thing with the crossplane.io/external-name annotation: set it and the managed resource adopts the existing object.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design asynchronous request status and retry.

Answer

Assumptions I'd state first: the operation is a long-running mutation with side effects outside my process (provisioning, a config apply, a batch job); the caller is a UI or another service; I own the server; the client can crash or lose the network at any point. If the operation is a pure read, none of this is needed: just retry the GET.

The core answer. Status is a server-owned resource, not a promise the client holds. Every submission carries a client-generated idempotency key; the server returns an immutable request ID and a status URL. The client never infers "did it work" from a timeout: it re-reads status by ID. Retry is a property the server classifies and publishes, not a timer the client invents.

Why server-owned. A 504 from a proxy can arrive after the write already committed. The client's timeout carries zero information about whether the change landed. The only safe recovery is to re-read the request by its immutable ID, which is the entire reason the ID exists and the status is a GET-able resource.

State machine. Retryability is a field on failed, not a separate state: that keeps the state count from exploding.

stateentered whenterminalclient action
queuedaccepted, not startednopoll with backoff
runninga worker picked it upnopoll; show step progress
awaiting_approvalpolicy requires a humannosurface to approver; keep polling
succeededall steps verifiedyesread result
faileda step failedyesread retryable + reason
cancelledclient or operator cancelledyesstop polling

Idempotency. The submission key is stored with the request, keyed on (tenant, idempotency_key). A duplicate POST with the same key returns the same request ID instead of creating a second request. Give the key a TTL, 24h is a reasonable example, long enough to cover client retries, short enough to bound storage.

Two retry layers, decided separately.

  • Transport retry (client → server): safe because the POST is idempotent. Retry on connection error, 429, 502/503/504, and honor Retry-After.
  • Work retry (server → provider): only if the step is idempotent or has a compensating action. Classify each step at design time; a step that charges a card is not the same as one that writes a tag.

Backoff, with the trace:

Python
def next_delay(attempt, retry_after, base=0.5, cap=30.0):
    if retry_after is not None:
        return min(retry_after, cap)
    return min(base * 2 ** attempt, cap)
attemptretry_afterreturn
0None0.5
1None1.0
2None2.0
31212.0
6None30.0

So a 503 with Retry-After: 12 waits 12s, not the 4s the exponential curve would give. The 30s cap stops a stuck client from sleeping through a recovery. Add ±20% jitter in production; the trace above has none.

Failure modes, with detection.

  • Duplicate execution: two workers pick up the same request. Detect: a step counter or provider effect count higher than expected; alert on it. Cost: a double-charged provider and manual cleanup.
  • Orphaned request: a worker dies mid-run and the request sits in running. Detect: age in running exceeds the p99 for that step type (say 10 min). Cost: a spinner forever. Fix: a reaper that moves it to failed with retryable=true.
  • Retry storm: many clients retry a 503 in lockstep. Detect: request-rate spike correlated with error rate. Cost: provider rate limit, then cascading failure.
  • Stale retry: a client retries a request that already succeeded. Detect: idempotency-key hit on a terminal request. Cost: none if handled, a duplicate side effect if not.

Trade-offs. Polling is the baseline: simplest, survives client restarts, no public endpoint. Webhooks push but need their own retry and a reachable URL; SSE/WebSocket drops on reconnect and still needs a fallback poll. Server-side state costs storage and a reaper, but it is the only way to answer "did it happen" after a crash: client-side state is cheaper and loses the answer. Finally, resume vs compensate is a per-step decision: re-run the step if it is idempotent, undo it if it is not.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Handle cancellation during apply.

Answer

First 90 seconds

"Cancel" during apply means two things, and I'd separate them out loud: stop starting new work, and reconcile what already exists. It never means roll back. Terraform has no record of the pre-apply state of a resource it just created, and a provider call that returned 200 may have created something it never reported. So the honest answer is: quiesce, then reconcile from state.

Assumptions: Terraform 1.x, remote state in S3 with a DynamoDB lock, apply driven from CI, AWS provider. Different orchestrator, same shape.

Why the state file is the reconciliation input

Terraform writes state after each resource operation completes. At any instant the state file is a truthful record of completed operations and nothing else: no partial resource, no optimistic entry. That's why you don't need rollback: the file already tells you exactly what exists.

Terraform's first Ctrl-C (SIGINT) stops scheduling new operations and waits for in-flight provider calls; a second Ctrl-C exits immediately.

SignalTerraform's responseLeft behind
1st SIGINTstops new ops, waits for in-flight callsstate for completed ops; lock released on clean exit
2nd SIGINTexits nowin-flight creates unrecorded; lock may stay held
SIGKILLno handler runssame, and no final state write

If your runner sends SIGTERM rather than SIGINT, check what your Terraform version does with it before relying on the graceful path: I wouldn't assume it matches SIGINT. Kubernetes sends SIGTERM then SIGKILL after terminationGracePeriodSeconds (default 30s), which is the trap below.

Worked trace (numbers illustrative)

Plan: 40 resources, -parallelism=10 (the default).

  • t=0: lock acquired in DynamoDB, lock ID a1b2…; state serial 41.
  • t=0–90s: 12 resources created, 12 state writes, serial 53.
  • t=91s: CI job cancelled, SIGTERM to the pod. Three calls in flight: aws_iam_role (~2s), aws_instance (~40s), aws_db_instance (~4 min).
  • t=93s: IAM role returns, serial 54.
  • t=121s: 30s grace expires, SIGKILL. The instance and the DB were never written.
  • Reality: both exist in AWS, neither is in state, and the DynamoDB lock is still held.
  • Next run: terraform plan fails with "Error acquiring the state lock" because -lock-timeout defaults to 0s. Operator confirms no writer is alive, terraform force-unlock <ID>, then terraform plan shows the drift and terraform import picks up the two orphans.

Classifying what completed

ClassTestExampleAction
retainholds data not reproducible from configRDS with rows, bucket with objectsleave it, import, never destroy
safe destroystateless, no dependents, no datasecurity group with no ENIs, empty bucketdestroy; the call is idempotent
needs a decisioncosts money idle, or something references itNAT gateway, EIP, record in a shared zonepage the owner, don't guess

Failure modes

  • Stuck cancel. A provider call with no client timeout never returns, so the graceful path never ends. Detect it as no state write for longer than the resource's timeouts { create = … } while the process is alive and idle. Cost: the lock is held, every other apply is blocked. Set timeouts on anything that can hang; force-unlock only after the PID is confirmed gone.
  • Two writers. Someone force-unlocks on a timer while the old process is still alive. Terraform checks the lock ID before writing state and aborts if it no longer holds it: that check is the fence. Detect a breach by a state serial that jumps by more than your own writes, or a lock owner ID that doesn't match. Cost: last-writer-wins, silent orphans.
  • Half-destroyed graph. Cancel mid-destroy leaves a dependent whose dependency is gone. Detect it in terraform plan (ENI present, security group absent) or an AWS DependencyViolation. Cost: a VPC you can't delete without hand work.
  • Orphans outside state. Diff a tag-based inventory (resourcegroupstaggingapi get-resources) against terraform state list. Cost: silent spend.

When not to drain

Credential leak or a bad artifact: revoke first, kill second. Draining keeps the compromised principal alive for the length of the slowest call. Ephemeral environment: destroy-first beats retain. A non-idempotent long job like a data migration: the orchestrator waiting doesn't help. The job needs its own checkpoints. And don't revoke the CI role's credentials until the writer is confirmed dead, or in-flight calls fail auth and you get a half-created resource with no state record.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Handle provider outage during provisioning.

Answer

Core answer (first ~90 seconds)

Assume a multi-tenant provisioning service calling a cloud provider API (EC2, say) through a workflow with per-step state in Postgres, each create carrying an idempotency token. The provider starts returning 503s and one RunInstances call hits our 30 s client timeout. The timeout is the hard part: it is ambiguous. The instance may exist and only the response was lost.

I'd do three things in order. Stop the amplification: cap retries at 3 attempts (the AWS SDK standard retry mode default) with full jitter, and put a circuit breaker on the provider endpoint. Say 20 consecutive failures in 30 s opens it, fail fast for 30 s, then one half-open probe. With 200 in-flight provisions, uncapped retries turn one outage into 600+ calls against a provider already shedding load.

Then resolve the ambiguity before retrying: query the provider by the idempotency token or a deterministic name tag. If the resource exists, adopt it into state; if not, retry. Never retry a create whose outcome you haven't checked.

Then contain: mark only the affected step degraded with a real retry-after, keep unrelated tenants and unrelated providers (DNS, billing) running, and preserve request ID, correlation ID, plan hash and state version for the postmortem.

Detail an interviewer will push on

Why timeouts are ambiguous. The write can commit server-side and the response be lost to a reset connection. There is no protocol-level way to tell "never happened" from "happened, reply lost": only a read-back or an idempotency token resolves it. AWS's ClientToken is valid only for a bounded window, so a retry a day later is a fresh create, not a dedupe.

Locks. Hold the provisioning lock only while a live writer exists: a lease with a heartbeat, not an indefinite row lock. On takeover, issue a monotonically increasing fencing token and have the state store reject any write carrying a token lower than the highest it has seen. Without fencing, a paused writer resumes and overwrites the new writer's state.

Replay after recovery. Rate-limit replay to the provider's documented quota, client-go's default 5 QPS / burst 10 is a reasonable starting shape, and order by lifecycle safety: finish or roll back half-created tenants before starting new ones.

failuredetection signalcost
retry stormprovider 503/429 ratio climbs while your request rate is flatprovider throttles the whole account, not just the failing step
duplicate resourcestag query returns >1 resource for one plan hashdouble billing, orphan cleanup
orphaned resourcesnightly reconcile: provider list minus state entries > 0silent spend, quota exhaustion
stale locklease expiry timestamp older than last heartbeattwo writers, lost state
expired approvalapproval TTL passes mid-outageprovision proceeds on stale context

Reconciliation is a three-way diff: desired (plan), recorded (state), actual (provider describe/list). Orphans are actual-minus-recorded; drift is recorded-vs-actual mismatch.

Trade-offs. Retry vs fail-fast: retry only idempotent, retryable errors (5xx, 429, timeouts); fail fast on 4xx validation. Retrying those just burns budget. Cancel vs defer an approval: cancel if the context it approved changed (cost, region, policy); defer if only time passed. "Prioritize lifecycle safety" means a half-created tenant that can't be rolled back beats a new tenant that can, because the former is unbounded spend.

What changes the decision: if the provider is a shared control plane (IAM, VPC) rather than per-tenant resources, blast radius is account-wide and you stop all provisioning, not just the failing step.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Protect self-service runners and plugins.

Answer

What I'd say first. "Self-service" hides the trust boundary, so I'd pin it down before naming controls. Assumption: a multi-tenant platform where tenants register their own runner images and install plugins/providers from a marketplace, and the platform holds cloud credentials those jobs can reach. If instead every committer is trusted and the runner is single-tenant, most of what follows is over-engineering.

Given that, the answer is: treat the runner as untrusted-by-default and every plugin as code you didn't write. One job per ephemeral runner, no long-lived credentials on it, default-deny egress, and plugins pinned by digest behind an allowlist. GitHub's own docs make the first point bluntly: a self-hosted runner should only be used with private repositories, because anyone who can trigger a job on it can reach the runner's secrets and environment.

Why each mechanism works.

AttackControlWhy it defeats the attackDetection signal
Fork PR runs attacker codeEphemeral runner, one job per VMA persistent runner is a shared mutable cache: a poisoned toolchain or a leftover credential file is the next job's starting state. Destroying the VM removes the persistence window.Job outlives its TTL; runner re-registers with the same ID
Secret exfiltrationOIDC federation, no static keysThere is no long-lived secret to steal. The token is minted per job, scoped to one role, and expires in ≤1h.AssumeRoleWithWebIdentity from an unexpected repo or branch
Malicious plugin/providerPin by digest, allowlistA re-tagged release can't be pulled. Terraform's .terraform.lock.hcl records provider hashes and terraform init verifies them.Lockfile diff in the PR; plugin reaching an unlisted host
Artifact rollbackProvenance attestation carrying the source commitRe-uploading an old signed artifact fails, because its provenance commit isn't an ancestor of main.Provenance commit absent from main's history

The OIDC trust policy is where the isolation actually bites: the sub condition is what stops a fork PR from assuming the deploy role:

JSON
{
  "Effect": "Allow",
  "Principal": { "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com" },
  "Action": "sts:AssumeRoleWithWebIdentity",
  "Condition": {
    "StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" },
    "StringLike": { "token.actions.githubusercontent.com:sub": "repo:acme/*:ref:refs/heads/main" }
  }
}

PR jobs get a role with no cloud permissions; only main can assume the deploy role.

Trade-offs and when not to. Ephemeral runners cost cold start: a fresh VM plus runner registration is 30–60s. If the median job is 3 minutes, a 45s boot is 25% wall-clock overhead: worth it for untrusted PRs, not for a trusted nightly release, where a warm dedicated runner starting in ~2s is the right call. A hard egress allowlist breaks any build fetching from an arbitrary host; a logging proxy keeps visibility but loses the fail-closed guarantee. OIDC needs the CI provider to be an OIDC issuer and the cloud to trust it: on Jenkins without an OIDC plugin you fall back to Vault-issued short-lived credentials, which is more moving parts for the same result.

Failure modes and blast radius. A compromised runner persists only for one job; blast radius is that job's OIDC token, ≤1h, one role. A dependency takeover is caught by the lockfile diff and confined to the job. A malicious plugin runs in-process with the runner's token, so egress deny is what fails it closed. Alert on jobs exceeding their TTL and on egress to unlisted destinations: those two signals cover most of the above.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design authorization for self-service infrastructure.

Answer

Core answer

Assume a multi-tenant platform where teams self-serve through a CI pipeline (Terraform, Crossplane, Pulumi), humans and CI both act, and the platform owns the cloud accounts. The design is two authorization decisions, not one: a plan-time decision on the requested change, and an apply-time decision on the exact artifact a human approved. Everything else (role separation, short-lived credentials, audit) exists to make those two decisions trustworthy.

Identity first. Don't hand teams cloud keys. Federate: GitHub Actions OIDC into sts:AssumeRoleWithWebIdentity, GCP Workload Identity Federation, or a SPIFFE SVID from SPIRE. The token is scoped to one job and dies with it; AWS STS AssumeRole defaults to a 1-hour session (12 h max, and role chaining caps at 1 h). Kubernetes projected service-account tokens default to about an hour. The runner identity is then a claim about which repo, branch and workflow, not a shared secret.

Plan-time. The pipeline runs terraform plan -out=tfplan, then terraform show -json tfplan for plan JSON. A policy engine (OPA/Rego, or Cedar) evaluates that JSON against the requester's team, project, environment and resource class: instance size, region, whether the target VPC is prod, whether the change touches a secret, whether it references another project's state.

Apply-time, and why plan binding matters. The classic bug is TOCTOU: a human approves plan A, the branch moves, apply runs plan B. Fix: approval binds to the plan artifact's hash, and apply consumes that file, terraform apply tfplan, never a fresh plan. The apply-time check re-evaluates policy against the same JSON plus the approval record (approver, timestamp, plan hash). Hash mismatch, apply refuses. The runner's OIDC claim must likewise match the repo and branch the approval was issued for.

Separation of duties. Split view, plan, apply, prod-approve, policy-override, state-access, admin. Prod apply needs an approver who is not the requester. state-access is separate because state holds secrets and is a lateral-movement path.

decisionevaluated atinputwho approves
resource class / sizeplanplan JSONrequester's team
prod targetplan + applyplan JSON + env tagnon-requester, prod-approve role
cross-project refplanplan JSON + state refsboth project owners
policy overrideapplyoverride record + expiryplatform admin, time-boxed

Trade-offs. Centralized policy (one Rego repo, one decision point) gives uniform audit and one place to fix a bug; it costs a bottleneck and a shared failure domain: policy service down, nobody ships. Fully delegated (each team owns its IAM roles) scales and fails independently, but you can't answer "who can touch prod?" without reading N repos, and drift is invisible. The deciding criterion is blast radius: centralize the decision, delegate the request. Don't centralize when teams are genuinely separate trust domains with their own accounts and compliance regimes, then you want a thin auditable contract (an org-level SCP plus per-account policy) rather than a shared engine.

Failure modes.

  • Confused deputy: a runner in account A assumes a role in account B. Detect with CloudTrail AssumeRole events where sourceAccount != targetAccount and no ExternalId. Mitigate with aws:SourceAccount / aws:PrincipalOrgID conditions.
  • Forged owner tag: requester sets owner=platform to pass a tag-based policy. Never authorize on requester-supplied tags; use aws:PrincipalTag from the federated identity, or resolve ownership server-side from the repo.
  • Stale approval: approval older than the plan, or hash mismatch. Log both hashes; alert on any apply whose plan hash has no matching approval.
  • Tenant enumeration: errors that distinguish "not found" from "not authorized". Return one 403 shape.
  • Compromised runner: short TTL bounds the window; the audit trail (actor, delegation chain, plan hash, result) is what lets you reconstruct it.

What would change the decision. Single-tenant platform, one real org: plan binding and four-eyes are overhead. A plain IAM role per environment suffices. If regulators require per-change evidence, the plan hash and approval record become the artifact of record.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design tenant isolation for infrastructure workspaces.

Answer

I'll assume Terraform 1.5+ with remote state in S3, and AWS as the cloud. The core decision is where to draw the tenant boundary: workspace, account, or cluster. My default for production tenants is account-per-tenant, because IAM and SCPs enforce isolation at the API level. Workspaces alone share the same credentials and state backend, so a single IAM misconfiguration leaks across tenants.

Here's the design. For each tenant, create a separate AWS account under AWS Organizations. The Terraform runner assumes a cross-account role in that account with a trust policy scoped to the tenant's CI/CD pipeline. State lives in an S3 bucket in the tenant account, with a bucket policy that denies s3:GetObject unless the principal's aws:PrincipalTag/tenant matches the object prefix. Enable versioning and DynamoDB locking (table per tenant or shared with tenant-prefixed LockID).

Why not workspaces? Terraform workspaces share the same backend configuration and provider credentials. The state files are separate keys in the same bucket, e.g. env:/prod/tenant-a/terraform.tfstate. A user with s3:ListBucket and s3:GetObject on the bucket can read every tenant's state unless you add IAM conditions. Workspace names are not a security boundary; they're just strings. So workspaces are fine for ephemeral dev environments or internal teams with low blast radius, but not for production tenants with compliance requirements.

Account-per-tenant increases operational overhead: more accounts to manage, cross-account networking (VPC peering or Transit Gateway), and quota limits (e.g. AWS default 10 VPCs per region per account). Workspace-per-tenant is cheaper but relies on IAM policy correctness and state backend isolation. When not to use account-per-tenant: if tenants are internal teams with no regulatory separation and you already have strong IAM guardrails, workspace-per-tenant with separate state prefixes and OPA policies in CI is acceptable.

Concrete failure modes: (1) State enumeration: a tenant with s3:ListBucket on the shared bucket discovers other tenants' state keys. Detect via CloudTrail data events on the bucket. (2) Forged ownership: a tenant edits their workspace name to match another tenant's prefix. Prevent with immutable tags and IAM conditions on aws:RequestTag. (3) Output leakage: a tenant uses terraform_remote_state to read another tenant's outputs. This fails if the IAM role lacks s3:GetObject on the other tenant's state key. (4) Shared module compromise: a malicious module in a shared registry exfiltrates secrets. Mitigate with module signing and private registries.

BoundaryBlast radiusIAM complexityCostTypical use
WorkspaceSame account, same credentialsLow (prefix conditions)LowDev, internal teams
AccountSeparate account, separate IAMMedium (cross-account roles)MediumProduction tenants
ClusterSeparate Kubernetes clusterHigh (networking, RBAC)HighRegulated tenants

IAM policy for the state bucket:

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::tf-state-bucket/tenants/${aws:PrincipalTag/tenant}/*"
    }
  ]
}

Trace: Tenant A's runner tries to read Tenant B's output via terraform_remote_state. The data source calls s3:GetObject on arn:aws:s3:::tf-state-bucket/tenants/tenant-b/terraform.tfstate. The IAM policy for Tenant A's role only allows s3:GetObject on tenants/tenant-a/*. The request is denied with AccessDenied. If the role had s3:GetObject on *, the request would succeed and leak Tenant B's outputs. So the isolation depends on the IAM condition, not the workspace name.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design break-glass infrastructure access.

Answer

Assumptions I'd state first: humans responding to a production incident, cloud IAM as the primary control plane, infrastructure defined in code, and an on-call rotation with at least two people reachable. If any of those is false the design changes, and I'd say so before drawing anything.

The answer. Break-glass is a pre-provisioned identity that is off by default and can only be turned on by a deliberate, logged act. Four moves:

  1. A standing role with no standing access. The role exists, its trust policy requires MFA and a named approver, and its permission policy names specific actions on specific resources. Nobody holds it day to day.
  2. Activation is a single API call that produces an audit event: sts:AssumeRole with a session name encoding the incident ID.
  3. The credential expires on its own, so there is no revoke step to forget.
  4. Everything the session does is attributable, because the session name rides on every subsequent API call.

Why scoped credentials beat disabling controls. Turning off an SCP, a deny policy, or a firewall rule changes the state of the whole account: every principal gets the widened access, not just the responder, and the revert is a second change that can be missed. A scoped role bounds the blast radius to the policy you reviewed, and the revert is the clock. The audit trail is also a normal API event rather than a config change that itself needs auditing.

ControlConcrete settingWhy
Session length--duration-seconds 3600 (STS default is 3600; a role can go to 43200, but role chaining caps at 3600)Long enough for a fix, short enough that a leaked key dies
ScopeNamed actions on named ARNs, e.g. ec2:RebootInstances on one instanceBlast radius equals the policy
ApprovalA second engineer holding breakglass-approver approves in the incident channel; a bot writes it to the incident recordTwo-person rule without a ticket queue
AuditCloudTrail to S3 with Object Lock and log file validation; EventBridge rule on AssumeRole for the role ARNImmutable, and alerts in about a minute

Trace of one activation:

  1. INC-4471 declared; on-call requests approval in #inc-4471.
  2. A different human with breakglass-approver approves; the bot records it against the incident.
  3. aws sts assume-role --role-arn arn:aws:iam::111122223333:role/breakglass-prod --role-session-name INC-4471-alice --duration-seconds 3600 --serial-number arn:aws:iam::111122223333:mfa/alice --token-code 123456
  4. STS returns credentials valid for 3600 s. CloudTrail records AssumeRole with roleSessionName=INC-4471-alice.
  5. EventBridge matches the role ARN and pages #security within about a minute.
  6. Every call alice makes carries INC-4471-alice in CloudTrail, so the post-incident review is a query, not an interview.
  7. At 3600 s the credentials stop working. Anything long-lived created during the window (an IAM user, an access key, a security group rule) is not covered by the clock and has to be found by diffing live state against IaC; terraform plan -detailed-exitcode returns 2 when there is drift.

Failure modes and how I'd detect them:

  • Approval theatre. If median time-to-approve sits under about 30 s, the approver is rubber-stamping. Track approval latency; if it stays there, drop the second approver and lean on post-hoc review instead.
  • Policy drift. Someone adds "Action": "*". Detect in CI: hash the break-glass policy and fail the build when it differs from the reviewed baseline.
  • Control plane down. The self-service path is unavailable exactly when you need it. Keep a separate route: a hardware-MFA-protected identity in a different account, or the cloud root account with its MFA key in a physical safe. Detect with a synthetic canary that assumes the role every 5 minutes; a failing canary means the path is broken before the incident, not during it.
  • Leaked session credentials. Detect via CloudTrail GetCallerIdentity from an unexpected source IP, or GuardDuty findings on the session.
  • Unreconciled changes. The fix works, nobody imports it into code, and the next apply reverts it. Detect with the drift check above, run as a scheduled job.

When not to use this: with fewer than about five engineers and no real rotation, the second-approver step costs more than it saves. Use one MFA-gated role with mandatory post-hoc review. And if the incident is a compromise of the account that hosts the break-glass role, break-glass into that account is useless; the out-of-band path is the whole answer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design policy-as-code for self-service requests.

Answer

Assume "self-service" means an engineer opens a PR that calls a Terraform module, CI plans it, and a merge applies it. Policy-as-code means the allow/deny rules live in a versioned repo, a program evaluates them against the request, and the result is machine-readable: a list of violations with resource addresses, not a wiki page.

I'd put the decision at four points. Each catches a different class of mistake, and each costs a different amount to get wrong.

LayerInputToolBudgetCatches
Shaperequest YAMLJSON Schema, or OPA<10 msmissing owner tag, bad env name, unknown module version
Staticmodule sourceCheckov, tfsecsecondspublic bucket, unencrypted default, wildcard IAM in the module
Planterraform show -jsonOPA/Conftest, or Sentinel1–2 sresolved region, real CIDR, cost delta, deletion of stateful resources
Runtimecloud API, k8s admissionAWS Config, Gatekeeper, Kyvernocontinuousconsole edits, drift from the applied plan

The budgets are SLOs you set, not measurements: measure your own plan sizes before committing to them.

Why four and not one: shape checks are cheap and run before you spend money on a plan, but they can't see a value computed from a variable. Static checks read the module source and catch most misconfigurations in under a second, but they can't see what a for_each resolves to. Plan checks see resolved values (the actual region, the actual CIDR) which is where the expensive mistakes live. Runtime checks are the only ones that catch a change made after apply.

Here's the plan-layer rule, in Rego:

REGO
package terraform.encryption

deny[msg] {
  r := input.resource_changes[_]
  r.type == "aws_ebs_volume"
  r.change.after.encrypted != true
  msg := sprintf("%s: EBS volume not encrypted", [r.address])
}

Trace it against terraform show -json plan.out:

JSON
{"resource_changes":[
  {"address":"aws_ebs_volume.data","type":"aws_ebs_volume",
   "change":{"after":{"encrypted":false}}},
  {"address":"aws_ebs_volume.logs","type":"aws_ebs_volume",
   "change":{"after":{"encrypted":true}}}
]}

First element: type matches, encrypted is false, false != true holds, so it emits aws_ebs_volume.data: EBS volume not encrypted. Second: true != true is false, body fails, nothing emitted. A destroy has after: null, so after.encrypted is undefined and the comparison is undefined: the rule doesn't fire. That's the fail-closed behaviour you want: absent or null encryption fails, only explicit true passes.

Trade-offs. Prevent (block the merge) versus detect (alert after apply): decide by blast radius and reversibility. Cross-account IAM or a database deletion: prevent. A missing cost tag: warn, and let a nightly job catch it. OPA versus Sentinel: OPA is open source, runs in CI and in-process, and Rego is a real learning curve; Sentinel only runs in Terraform Cloud/Enterprise but reads the plan natively. Static scanners are faster and need no credentials; plan-based checks need a plan artifact and cloud read access. Don't reach for any of this if you get a handful of requests a week: a review checklist is cheaper than maintaining a policy engine and its test suite.

Failure modes, and how you'd know:

  • Plan/apply divergence. A provider default or a console edit lands between plan and apply. Detect by hashing the plan and comparing applied attributes to it; alert on mismatch.
  • False positives cause bypass. Engineers route around a noisy policy. Detect by counting override requests per policy per week: a policy with a high override rate is mis-specified, not disobeyed.
  • The policy repo becomes the bottleneck. Detect time-to-merge on policy PRs; if it exceeds your app PR time, the central review is the problem.
  • Drift. Policy passed at apply, someone changed it in the console. Detect with provider config rules or a scheduled terraform plan.

Overrides: scope to one resource, one policy, one expiry (30 days is a reasonable default), require justification and a compensating control, and write the whole thing to the audit log. An override without an expiry is just a policy deletion with extra steps.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Handle a policy service outage.

Answer

What I'd say first

Before touching anything: which service, and what does it gate? I'd assume a centralized policy decision point (OPA or Cedar behind an ext_authz-style sidecar) fronting two things: Kubernetes admission for production workloads, and API authorization for user-facing requests. The outage is the PDP being unreachable or erroring, not a wrong policy. Different incidents.

The core answer: the failure mode is a per-call-path decision made before the outage, not a global switch flipped during it. Fail closed on destructive and production-mutating paths; fail open on reads and low-risk paths. The reason is mechanical: the PDP sits on the request path, so a global fail-closed turns a PDP outage into an outage of everything, including the break-glass tooling and deploy pipeline you need to fix the PDP. Fail-closed on the recovery path is self-defeating.

How the fallback works

Every decision is cached keyed by (principal, action, resource, context-hash) with a TTL. On a PDP error or timeout, the enforcement point serves the cached decision if it's within TTL, otherwise applies that path's failure mode. The TTL is not a performance knob: it is the maximum revocation latency you accept. If a policy change must take effect within 5 minutes, TTL ≤ 5 min. Set it per path: 30 s for admin actions, 5 min for reads.

Timeout: the PDP call gets a hard deadline (say 50 ms) well under the caller's own budget, so a slow PDP degrades to the fallback instead of exhausting the caller's connection pool. Envoy's ext_authz failure_mode_allow defaults to false, fail closed, so fail-open paths must be opted in explicitly.

PathFailure modeCache TTLDetection
Prod admission (create/update/delete)fail closed30 sadmission denials spike, PDP error rate
Break-glass / incident toolingfail open, audited5 minone audit entry per use
User-facing readsfail open5 min4xx/5xx ratio, PDP latency p99
Secret / credential accessfail closedno cachePDP-unreachable alert

Worked trace: request arrives, PDP down:

  1. t=0 ms: enforcement point checks cache. Hit within TTL → allow/deny from cache, no PDP call. This is the common case: a 60 s TTL at 20k rps serves ~1.2M requests without the PDP.
  2. Miss → call PDP with a 50 ms deadline.
  3. t=50 ms: deadline exceeded. Prod admission → deny, emit policy_pdp_unreachable, return 503 with Retry-After.
  4. Read path → serve fail-open, tag the response, enqueue the decision for replay.

Recovery

Restore the PDP, then replay the queued decisions against the unchanged request plans and diff against what was actually admitted. Any admitted change the replayed policy would have denied gets flagged. Invalidate cached decisions and any approvals minted during the window: they were issued under a degraded policy. Scan what got through.

Failure modes and detection

  • Stale cache serving a revoked permission: compare cache TTL against your policy-change SLA; alert when TTL > SLA.
  • Fail-open quietly becoming the norm: alert when fail-open rate > 0.1% for 5 min.
  • Retry storm on recovery: the PDP returns and every enforcement point retries at once. Jittered backoff plus a queue cap; drop-and-deny rather than unbounded queueing.
  • Repeated apply: idempotency keys on admitted mutations so replay doesn't double-apply.

Design for next time: HA PDP (≥3 replicas across zones), dependency isolation so PDP failure doesn't cascade, an SLO on decision latency (p99 < 20 ms), synthetics probing the PDP every 10 s, and break-glass authority that is audited and expires.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design quotas and rate limits.

Answer

Clarify first. "Quotas and rate limits" is two controls people conflate. I'd ask: is the goal protecting shared capacity (rate), or capping consumption and cost (quota)? And what is the tenant boundary: team, project, or billing account? I'll assume a multi-tenant internal platform: tenants are teams, each with projects, one shared API gateway, and a downstream provider with its own limits.

Core answer. Three controls, enforced at different points:

  • Rate limit: short window (seconds), protects shared capacity and the downstream provider. Token bucket per tenant at the gateway: sustained 50 rps, burst 100. Reject with 429 and a Retry-After header.
  • Concurrency limit: in-flight requests, not requests/sec. A tenant under 50 rps can still hold 500 slow requests open and starve everyone else. Cap in-flight per tenant at 20.
  • Quota: long window (monthly), controls cost. 10M requests or $5k. Checked at admission against a cached counter, reconciled daily from provider billing.

The load-bearing decision: rate limits are enforced synchronously and near-exactly; quotas are enforced softly with a backstop, because exact real-time quota accounting across a distributed fleet costs more than the overshoot it prevents.

algorithmburst behaviormemorywhen to use
fixed windowallows 2× at the boundaryO(1)never for correctness-sensitive limits
sliding window counternear-exact, small errorO(1)default at the gateway
sliding window logexactO(requests)low-volume, strict limits
token bucketcontrolled burstO(1)default when bursts are legitimate

Arithmetic that separates the two axes. 50 rps sustained is 50 × 2.6M s/month ≈ 130M requests/month. A 10M quota is 10M / 50 = 200,000 s ≈ 2.3 days at full rate. So a tenant can sit well under its rate limit and blow its quota in an afternoon, or the reverse. Set them independently; don't derive one from the other.

Failure modes and how they're detected.

  • Retry storm. Clients retry immediately on 429 and synchronize. Fix: exponential backoff with full jitter, honor Retry-After. Detect: 429 rate spikes while downstream load stays flat.
  • Hot key. One tenant at high rate serializes on its Redis bucket. Fix: local token buckets per gateway node, synced every 100 ms (allows up to N× overshoot, N = node count) with the global quota as backstop. Detect: p99 on the limiter itself, not on the API.
  • Label evasion. A tenant spins up a new project for a fresh quota. Fix: bind quota to the billing account, not the project; detect via the ownership graph.
  • False denials. Clock skew or counter drift denies a tenant under its limit. Detect: alert when denials > 0 while measured usage < 80% of limit.
  • Never auto-delete resources on threshold. A quota denial rejects new work; it does not destroy running infrastructure.

When not to. Don't put interactive and batch traffic in one bucket: batch consumes the burst and starves interactive; use separate classes. Don't hard-stop internal teams with no override path: that produces ticket-driven unblocking, the exact thing quotas exist to remove. Give a time-bound authorized burst instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design cost visibility and controls.

Answer

Core answer (first 90 seconds)

Assume one cloud (AWS), a few hundred workloads on EKS plus managed services, tags that exist but are inconsistent, and finance wanting monthly chargeback. The design is three layers (allocation, visibility, enforcement) shipped in that order, because enforcement on top of bad allocation just breaks things.

Allocation first. Every resource gets four immutable labels at creation (owner (team), workload, environment, cost_center) written by the provisioning path (Terraform module, Helm chart, platform API), never by a human afterward. Immutability matters: if you can retag a resource, last month's chargeback silently changes. Activate those as cost-allocation tags in the billing console so they land in the Cost and Usage Report.

Visibility second. Two numbers per workload: total cost and unit cost. Unit cost is total ÷ a business denominator: requests served, GB stored, tenants. A service at $5,606/mo serving 120M requests is $0.047 per 1,000 requests; that number survives a 3× traffic increase, raw spend doesn't.

Forecast before apply, reconcile after. Price the Terraform plan against the pricing API and label it a forecast with a range. Reconcile against the billing export once it lands.

Worked trace, where forecast error comes from

40 × m5.xlarge at $0.192/hr × 730 h = $5,606/mo (us-east-1 on-demand list; prices move). A compute savings plan at ~40% off → $3,364. Now autoscaling: if the cluster runs 40 nodes for 80% of the month and 55 for 20%, the average is 40×0.8 + 55×0.2 = 43 nodes → $6,027, i.e. 7.5% over the flat forecast. That gap is the mechanism: plan cost assumes a steady state, actual cost follows the autoscaling curve.

Controls, with the lag each one has

ControlSettingCatchesDetection lag
Budget$6,000/mo, alert at 80% actual and 100% forecasttrend overspend~8 h (Budgets refreshes ~3×/day)
Anomaly detectionCost Anomaly Detection, $100/day thresholdunexpected service spike24–48 h (daily granularity)
Hard quotaEKS max nodes 60, per-namespace ResourceQuotarunaway jobseconds
ExpiryTTL tag, nightly reaper deletes untagged-after-30dorphaned EBS/EIP24 h

The lag column is the point: anomaly detection is too slow to stop a runaway, so real-time caps have to exist separately.

Failure modes and how you see them

  • Unallocated spend: untagged resources. Detect as unallocated % of the bill; target under 5%. At 20% unallocated, chargeback is fiction and teams dispute it.
  • Anomaly lag: a job burning $500/hr spends $12k before the 24 h detector fires. Node caps and quotas are the only thing that stops it.
  • Idle spend: unattached EIP $3.60/mo, idle ALB ~$16/mo, orphaned gp3 volume $0.08/GB-mo. Trivial individually; 200 of them is $4k/mo.
  • Forecast miss: the plan doesn't price data transfer, NAT gateway ($0.045/GB processed), or cross-AZ traffic. Track forecast error per workload and fix the pricing model, not the number.

Trade-offs: showback vs chargeback vs enforceback

Showback is visibility only, no teeth; right for the first two quarters while tags mature. Chargeback is an internal invoice; it changes behavior but needs allocation accuracy above ~95% or it gets ignored. Enforceback is hard quotas and budget actions that stop resources: use it where blast radius is acceptable (dev, sandbox), never on a customer-facing path without an SLO-aware override.

Don't rank individuals by raw spend; it drives hoarding and shadow infra. Rank by unit-cost trend and forecast accuracy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design self-service database provisioning.

Answer

Core answer (first 90 seconds)

The load-bearing decision is where the self-service boundary sits. Fix three things and the rest is plumbing: the catalogue of blessed modules, the fields a requester may set, and the risk tiers that force a human approval. Everything else (the portal, the plan output, the credentials) is downstream of that boundary.

Concretely: one golden Terraform module per database class (Postgres 16 on RDS, Aurora Serverless v2, DynamoDB), pinned to a version. The requester chooses class, environment, region, a size from a bounded set, retention, and an owner. They cannot type an engine version, a subnet, or a parameter group. The platform renders a plan, shows the monthly cost delta and any destructive action, and routes it: dev with no regulated data auto-applies; prod or anything touching regulated data goes to the owning team plus a platform reviewer.

Execution runs in a CI identity that assumes a per-request role via OIDC, scoped to the target account and a resource-name prefix, with a session capped at one hour. Terraform state lives in S3 with a DynamoDB lock table; the apply takes the lock, so two requests against the same stack serialize instead of racing. What gets written back is a status, an endpoint, and a reference to the secret, a Secrets Manager ARN or a Vault path, never the credential itself.

Why this shape, and the alternatives

modellead timeblast radiuswhen it wins
DBA-gated ticketdaystinyregulated, low-volume, few teams
Templated self-serviceminutes to hoursbounded by the modulemost platform teams
Free-form IaC from the requesterminutesunboundedsandboxes only, never prod

The templated model wins because the module is the unit of review. You review it once per engine-version bump, not once per request. Free-form hands the requester the ability to open 0.0.0.0/0 or pin a three-year-old engine. The ticket model gives you a queue that grows with headcount.

Failure modes and how you see them

  • State lock contention. Two applies on the same stack: the second fails with Error acquiring the state lock, naming the lock ID and holder. Detection is the error itself. The fix is per-request workspaces or a queue, not retries.
  • Quota exhaustion. AWS defaults to 40 DB instances per region. Request 41 fails at apply, after the plan looked clean. Check quota during plan, not apply.
  • Orphaned secrets. An apply that fails after the secret was created leaves a credential with no database. Tag every secret with the request ID and reconcile on a schedule.
  • Drift. Someone edits a parameter group in the console. terraform plan shows it on the next run; a nightly plan-only job surfaces it without applying.
  • Destructive apply. Changing storage_encrypted or the engine forces replacement. The plan must mark it and the approval tier must escalate.

Arithmetic

Say a DBA-gated request costs two engineer-hours of queue plus thirty minutes of work, and the templated path costs four minutes of requester time plus one minute of CI. At 30 requests a month that is roughly 75 hours against 2.5. The templated path pays for itself in the first month; the recurring cost is module maintenance, which is one review per engine-version bump.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design ephemeral environment lifecycle.

Answer

I’d design this as a lease-based controller, not a checklist. Assume: GitHub PRs, Kubernetes, Terraform, AWS, one namespace per PR, synthetic data, default TTL 72h, hard max 168h. The core answer: every environment gets an owner, a source revision, a TTL, and a reaper that deletes it. Creation and deletion are idempotent reconciliations, so a failed create or a missed delete self-heals.

Request: a PR label preview triggers GitHub Actions. It writes a record: owner=PR author, repo, SHA, purpose, data class=synthetic, TTL=72h, max=168h. Provision: a Terraform module creates a namespace, an IAM role with no prod secrets, an RDS schema from a masked snapshot, and an ingress host like pr-123.preview.example.com. Argo CD ApplicationSet watches the record and syncs manifests. Cost tags env=pr-123, owner=..., ttl=... make billing attributable.

Use: the bot posts URL, status, and cost to the PR. Renewal is bounded: only the PR author or team lead can extend, max 168h, and only if the PR had activity in the last 24h. Mechanism: an annotation such as preview.example.com/ttl: 72h; the controller compares now > created + ttl.

Expire: at T-2h the bot comments. At T-0 the reaper quiesces jobs by scaling Deployments to 0, exports logs/artifacts to S3, revokes IAM, deletes the namespace, then runs Terraform destroy. Verify: AWS Config and CloudTrail checks for orphaned ENIs, EBS volumes, and RDS instances. Retry with backoff 1m, 5m, 15m; after 3 failures, page the owner.

Alternatives and deciding criteria:

ApproachIsolationCostStartupWhen wrong
Shared staging namespaceLowLowSecondsPer-PR DB migrations collide
Per-PR namespace on shared clusterMedium~$0.15/hr hypothetical2-5 minNoisy-neighbor CPU or network tests
Per-PR VPC + clusterHigh~$2/hr hypothetical15-25 minMost UI/API previews
On-demand VMHigh~$0.50/hr hypothetical5-10 minStateful services needing weeks of data

Use per-PR namespaces for UI/API tests. Use full VPC only for network/security tests. Don’t use per-PR ephemeral for compliance-bound data or long-lived integration; use a long-lived isolated account with manual approval.

Failure modes:

  • Abandoned PR: reaper deletes after TTL. If legal hold is set, tag hold=true, skip deletion, alert compliance.
  • Partial create: Terraform state lock and controller retry. If namespace exists but DB is missing, mark degraded and don’t post a URL.
  • Cleanup retries: idempotent destroy. Orphaned EBS from PVCs is detected by kubectl get pv plus AWS Cost Explorer.
  • Secrets: never copy prod secrets; use External Secrets with a per-env path.

Trace for a hypothetical env pr-123: created 2025-01-01T00:00Z, TTL 72h. At 2025-01-04T00:00Z the reaper sees expired, scales Deployments to 0, exports logs, deletes namespace, runs destroy, verifies 0 orphaned ENIs. If destroy fails, it retries at 00:01, 00:05, 00:15, then pages.

Measure creation p50/p95, active envs, extension count, and leak rate = orphaned resources / created envs. Target <1%. That tells you whether the lease model is actually cleaning up.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design safe infrastructure deletion.

Answer

Assumptions I'd state up front: AWS, resources managed by Terraform 1.x, one production service with an ALB, an ECS service, an RDS Postgres instance, an S3 bucket, a KMS CMK, IAM roles and a Route53 record. Production, so irreversible loss needs a second approver.

The 90-second answer. Deletion is a two-phase operation: a plan bound to the state it was computed from, and an apply that refuses to run if anything moved in between. Order comes from the provider's dependency graph, not from a diagram someone drew. Every step has a reversible window, and the last step is verification against the billing API, because the console lies about what still exists.

Why plan-binding works. terraform plan -out=tfplan writes the plan plus the state serial it was computed against. terraform apply tfplan re-reads state and aborts with "Saved plan is stale" if the serial moved. That is the mechanism behind "stronger authorization for production": the approver signs a hash of a specific plan, not a category of action. Without it, an approval granted at 10:00 can be applied at 16:00 against a state that gained an RDS replica at 14:00, and the plan silently deletes it.

Why dependency order is derived, not authored. The graph is the provider's. terraform graph emits DOT; CloudFormation exposes DependsOn; AWS enforces edges at the API whether you modelled them or not:

  • VPC delete fails while any ENI exists: Lambda-created ENIs are the classic orphan and linger for hours after the function is gone.
  • Route53 hosted-zone delete fails until every record except NS and SOA is removed.
  • IAM role delete fails while the role is still in an instance profile.
  • S3 versioned-bucket delete fails until every version and delete marker is removed.

So the plan's order is a topological sort of that graph, leaves first. Author it by hand and you get it wrong exactly once, on the resource nobody remembered.

Why tombstoning prevents adoption. S3 bucket names are globally unique across all AWS accounts. Delete acme-prod-assets and another account can register it within minutes. Anything still pointing there (a stale DNS record, a hardcoded ARN in a partner's config, a backup job) now writes into someone else's bucket. The same class of bug exists for IAM role names and KMS aliases. A tombstone (a reserved name, a deleted_at tag, an entry in your inventory) keeps the identity claimed so it cannot be re-adopted, and gives you something to reconcile against when a stale reference surfaces six months later.

Reversible windows, and what each costs.

ResourceDelete semanticsUndo windowWhat blocks it
RDS instance--final-db-snapshot-identifier or --skip-final-snapshotsnapshot is permanentskipping the final snapshot is unrecoverable
KMS CMKschedule-key-deletion7–30 days, default 30key unusable immediately; the window is the only undo
S3 bucketversioned deletenone unless versioning + MFA deleteall versions and delete markers must go first
Elastic IPreleasenoneunassociated EIP billed at $0.005/hr (~$3.60/mo) since Feb 1 2024
EBS snapshotdeletenone$0.05/GB-month while it lives

Failure modes and detection. Partial deletion is the normal outcome, not the exception. Orphans bill quietly: a 500 GB snapshot is $25/month, a 200 GB log group is $6/month, an EIP is $3.60/month. Detect with aws resourcegroupstaggingapi get-resources filtered on the service tag, then reconcile against Cost Explorer grouped by the same tag: the delta is your orphan list. Alert on that delta, not on the delete job's exit code, because the job exits 0 when it deletes 9 of 10 resources.

When not to do this. Under legal hold or a retention obligation, the answer is archive-and-detach, not destroy: keep the data, drop the compute and the credentials. And never delete because catalog metadata disappeared: a missing entry in your service catalog is a bug in the catalog, not evidence the resource is gone. The provider API is the source of truth.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design ownership transfer for managed infrastructure.

Answer

Clarify first. Two questions decide the design: is the new owner in the same AWS account or a different one, and is this an internal team handover or a divestiture to another company? Those change the answer completely. Assume the common case: same company, a service moving from Team A to Team B, resources in a dedicated AWS account, Terraform-managed, prod and staging.

Core answer. Ownership transfer is an authority change, not a metadata change. Do it additively, then subtractively: grant the new owner everything it needs and prove it can operate, then revoke the old owner. Never flip both at once: revoke first and one missing grant locks you out of production with nobody who can apply. The two things that actually break are Terraform state and KMS keys, because both are secrets that live in the old owner's account.

Mechanism, step by step.

StepMechanismHow you know it worked
Grant new ownerAdd Team B's IAM role to the deploy role's trust policy, the S3 backend bucket policy, and the lock table (DynamoDB, or S3 native locking via use_lockfile since Terraform 1.10)Team B runs terraform plan and gets "No changes", not AccessDenied
Move state ownershipThe state file holds resource IDs and any secret not in a separate secret store, so treat it as a secret. Move it to Team B's bucket or grant Team B read/write on the existing onePlan is empty from Team B's CI
KMSIf the key lives in Team A's account, Team B cannot decrypt. Add Team B's account to the key policy and to Team B's IAM policy: cross-account KMS needs bothA read of an encrypted resource succeeds
Budgets and costAWS Budgets are per-account and filter by tag; retag resources to Team B's cost centerCost Explorer shows the new tag on the next bill
On-call and alertsReassign the PagerDuty service and escalation policyA test alert pages Team B, not a dead channel
Revoke Team ARemove from trust policy, bucket policy, key policy, PagerDutyTeam A's plan now fails with AccessDenied: the desired result
JSON
// KMS key policy: this alone is not enough; account 222222222222 also needs an IAM policy
{ "Sid": "AllowTeamB", "Effect": "Allow",
  "Principal": {"AWS": "arn:aws:iam::222222222222:role/deploy"},
  "Action": ["kms:Decrypt","kms:GenerateDataKey"], "Resource": "*" }
Shell
AWS_PROFILE=teamb terraform plan -detailed-exitcode   # 0 = no changes, 2 = drift, 1 = error

Trade-offs. Atomic cutover (one change window, both sides coordinated) versus dual-run, additive then subtractive. Dual-run is safer but creates two writers to one state file, which is how you corrupt state. So during the window exactly one party runs apply; the other is read-only. For a cross-account divestiture you cannot move resources at all: either recreate them in the new account, or share via AWS RAM (subnets, Transit Gateway, Resolver rules) and leave them where they are.

Failure modes. Tag-only transfer: the new owner cannot deploy, detected on the first apply as AccessDenied. State left in the old account with the old owner still holding write: silent corruption, detected only when a plan shows unexpected drift. KMS key not shared: detected at first decrypt, often in prod at 2am. Revoke before grant: lockout, recovered only with break-glass root.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Retire a self-service resource type.

Answer

Assumptions I'd state first: the resource type is a Terraform module published through a Backstage template, state in S3 with a DynamoDB lock table, consumers are ~40 CI pipelines and ~200 humans provisioning through a portal. If your type is a Kubernetes CRD or a Crossplane XRD the mechanics differ but the drain logic is the same.

Core answer. Retirement is three separate jobs, and conflating them is the usual failure: stop new provisioning, drain existing instances to zero or to an approved exception list, then remove the capability. Module, template, IAM, docs. That order matters because removing the capability before draining orphans state.

The decision that actually matters is hard cutover versus deprecation window. Cut over hard when the type holds no persistent data and you can name every consumer: you email them, you delete. Use a window when instances hold data or consumers are pipelines you don't control. Derive the window from arithmetic, not vibes. Take a concrete case: 240 provisioned resources, a team that can migrate 4/day, is 60 working days of migration; add 30 days of buffer for stragglers and you announce 90 days with a hard date. A window without a hard date never closes.

Why teardown fails. Two mechanisms cause most of the pain.

Finalizers. In Kubernetes, deleting an object that carries metadata.finalizers only sets metadata.deletionTimestamp; the object stays in Terminating until the controller removes the finalizer. So kubectl delete returns success and the resource is still there. You see it with kubectl get <kind> -o jsonpath='{.items[*].metadata.finalizers}'. Revoke the controller's IAM before the finalizer runs and the object is stuck permanently; clearing it needs kubectl patch <kind> <name> -p '{"metadata":{"finalizers":null}}', which is a manual, auditable act, not a cleanup step.

State drift and resurrection. Terraform plans from state, not from reality. Delete the module from the registry while a consumer's root module still has module "widget" and their next terraform apply recreates it. You find this with terraform plan -refresh-only across consumer workspaces, or by grepping the org for the module source. Resurrection is why you track runtime and API use (CloudTrail lookup-events on the provisioning API, the Terraform Cloud run API) and not portal page views. Portal traffic tells you who looked; the API tells you who is still creating.

Sequence. Announce the hard date and the replacement. Freeze new provisioning at the template layer: remove the Backstage template, and enable termination protection on existing AWS Service Catalog provisioned products so an accidental delete doesn't fire. Migrate by risk (data-holding instances first, stateless last) each with a rollback path, keeping the old module version pinned until the replacement has run a full change/recovery/delete cycle. Track the drain in a table:

statecountaction
provisioned240migrate or transfer
migrated180verify replacement in prod 7 days
exception12named owner, expiry date
orphaned0must be zero before revoke

Only when orphaned is zero and every exception has an owner and an expiry date do you revoke the runner role, terraform state rm the last instances, archive state and migration evidence, and delete policies, templates and docs. Then watch for 30 days for resurrection: a new resource appearing after the capability is gone means a consumer you missed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design platform SLOs for provisioning.

Answer

Provisioning is a pipeline, not one operation, so a single SLO over it hides the failure you actually care about. I'd split it into four user-visible steps (accept, plan, apply, observe) and put an SLI on each, because they fail for different reasons and are fixed by different teams. Assumptions first: an internal platform serving roughly 300 engineers, an asynchronous API where the caller gets a request ID rather than a finished resource, a 30-day rolling window, and about 20,000 applies a month.

PhaseSLITarget
Acceptcreate/update/delete return a durable request ID99.9% within 2 s
Plantime from accept to an inspectable planp95 under 30 s
Applyapplies reaching converged within the class deadline99.5%; p95 under 10 min, p99 under 25 min for the standard class (a VM plus two buckets)
Observereads reflecting the last recorded change99% within 30 s
Progressin-flight requests publishing a heartbeat99.9% with heartbeat age under 60 s

Clusters legitimately take 40+ minutes, so they get their own class; blending them into the VM class makes the number meaningless. Deadline-based success matters more than latency shape: a request that finishes at 14 minutes is slow, not failed, and those are different budgets.

99.9% of 30 days is 43 min 12 s of budget; 99.5% is 3 h 36 s. On accept, page at a 14.4x burn rate (2% of budget in an hour) and 6x (5% in six hours), file a ticket at 1x (10% in three days).

Three rules keep the numbers honest. Policy denials and invalid input are not platform failures: count them in a separate policy-decision SLI (p95 under 5 s), or the success rate improves every time you reject someone. Success alone is not enough: a clean apply that creates the wrong instance size is worse than a failure, so add a nightly drift check against the recorded plan (99.9% of resources matching at 24 h). And publish what survives an SLO miss: an accepted request is never dropped, even when the latency target is blown.

Why the failure modes exist. Orphans come from a non-atomic two-phase create: the provider makes the resource, then the inventory row or the ownership tag write fails. Terraform stopping mid-apply leaves the resources it already built, and if the partial state file is discarded, nothing can match them again. Detect them with a daily inventory diff (list provider resources by tag and project, subtract the database) and alert on the count, since a leak is a stock, not a rate. One leaked m5.large is roughly USD 70 a month.

Status freshness decouples from apply because reads must answer in milliseconds while apply runs for minutes and the provider rate-limits per-call. So the read path serves last-known state plus a heartbeat. Without heartbeat age, a dead worker is indistinguishable from a slow apply: that is the most common misread of a provisioning platform.

Retries are the other source of noise. Terraform applies with a default parallelism of 10, and client-go's default controller work queue backs off per item from 5 ms to a 1000 s ceiling while the controller itself is capped at 10 items/s with a burst of 100. One region-wide 429 therefore produces hundreds of retries per minute. Alert on the age of the oldest request still pending or applying, never on individual provider retries.

A trace, one request: at t=0.0 s the POST returns 202 with an ID, so accept is good. Plan is ready at t=11.2 s, inside p95. At 8 min 12 s into the apply the provider starts returning 429 for one node; the other two continue, and the heartbeat keeps the request in applying rather than failed. All three converge at t=14 min 05 s: slow, budget-consuming, not an error. If heartbeat age crossed 60 s it becomes stuck and pages; if it crosses the 25-minute deadline it is an error, and the reconciler must decide what to do with the two nodes that did come up, which is exactly where orphans are born.

I'd validate this against provider degradation, not just load: with a third of one region's capacity gone, the expected shape is p95 moving from 10 to 20 minutes with every accepted request eventually completing, rather than fast failures. Cleanup runs in quarantine mode (tag, wait 24 h, delete with capped concurrency) and no SLO miss ever justifies evicting or mutating a running workload to hit a number.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Measure self-service infrastructure success.

Answer

Assumptions first. "Self-service" here means a developer gets the resource with no human in the loop: no ticket, no Slack ping to the platform team. The eligible cohort is everyone who could legitimately request it, not the people who already did. Measure over a fixed window (a quarter) and segment by environment and team maturity, because a greenfield team and a regulated payments team have different ceilings.

The headline is assisted-completion rate and time-to-first-success, not adoption. Adoption is gameable: mandate the platform and adoption hits 100% while developers route around it. What separates real self-service from a dashboard is the fraction of requests that finish with zero human touches, and how long the slow tail takes.

Funnel for one resource (Postgres, one quarter, hypothetical figures):

stagecountnote
eligible engineers1,200could request it
requests340
self-served, no human25073.5% assisted-completion
human-assisted90ticket or Slack
retained at 90 days210still on platform

p50 time-to-first-success is 22 min; p90 is 2.5 days. The median is healthy; the p90 is where the tickets live, so the p90 is the number to move.

Mechanism. Instrument the request lifecycle with OpenTelemetry spans, one trace per request, tagged with outcome and whether a human touched it. A healthy request:

provision-postgres (trace 7f3a)
├─ validate-request        12 ms   ok
├─ policy-check (OPA)      38 ms   ok
├─ quota-check              4 ms   ok
├─ terraform-apply      18,400 ms  ok
└─ register-in-catalog     210 ms  ok
total 18.7 s

A request that ends in a ticket shows the same trace with policy-check denied and no apply span: that is the assisted path, and it is countable.

Trade-offs. Time-to-first-success is the right headline while the platform is young and the goal is trust; adoption rate is the right headline only after the platform is the default and you are measuring migration. A success measure misleads when the cohort is small and one expert absorbs the tickets: assisted-completion looks great because the human is fast, not because the platform works. Segment before you celebrate.

Counter-metrics, with detection.

  • Policy bypass: reconcile cloud inventory (AWS Config, GCP Asset Inventory) against platform-issued resource IDs; a growing delta means developers are going around you.
  • Privilege concentration: count distinct principals holding the platform's apply role; if it is one or two, self-service is a fiction.
  • Platform toil: platform-team hours per 100 requests; if it rises while requests rise, you have built a ticket queue with a UI.

Then act. Use the p90 tail and the bypass delta to change defaults, quotas and paths, not to publish a dashboard.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Roll out self-service infrastructure incrementally.

Answer

I'd clarify what 'self-service infrastructure' means here: a portal or API where product engineers provision approved resources (databases, queues, buckets) without filing a ticket. My assumptions: a platform team of 4, 60 product engineers, current median time-to-provision 9 days, p90 21 days, 40 tickets/week, and 15% of tickets are rework. The incremental rollout has four phases.

PhaseCohortScopeExit criteria
1. Design partners3 teamsOne journey: provision a Postgres database. Backstage portal, Crossplane control plane, Terraform modules. Quotas: 10 vCPU, 40 GB RAM, 5 S3 buckets per team.End-to-end lifecycle works: request, approval, provision, status, change, delete. Baseline: median 9 days, p90 21 days, 40 tickets/week.
2. Constrained canary10 teamsSame journey, canary modules/policies. Keep old ticket path.Median time-to-provision < 1 day, ticket volume down 80%, zero quota violations. Rehearse recovery.
3. Evidence-based expansion30 teams, then all 60Add more journeys (queues, buckets).Same exit criteria per cohort. Expand by evidence, not resource count.
4. Retire manual fulfillmentAllOnly after active consumers, exceptions, incident paths covered.Break-glass path for edge cases.

Here's a trace of a single request. An engineer opens Backstage, selects 'Postgres database,' fills in size and environment. Backstage calls Crossplane with a composite resource. Crossplane checks OPA policy: is the team within its 10 vCPU quota? If yes, it applies a Terraform module that creates an RDS instance. Crossplane reports status back to Backstage. If no, it rejects with a reason: 'Quota exceeded: request 4 vCPU, have 2 vCPU left.' The engineer can request a quota increase via the same portal.

Arithmetic on the payoff: baseline 40 tickets/week * 2 hours of platform engineer time = 80 hours/week. After self-service covers 80% of requests, that drops to 8 tickets/week * 2 hours = 16 hours/week, freeing 64 hours/week for platform work. At a fully loaded cost of $100/hour, that's $6,400/week, or $332,800/year.

Failure modes: If you don't enforce quotas, one team provisions 1000 vCPUs and blows the budget. Detect with cost alerts and quota dashboards. If you don't keep the old path, teams with edge cases are blocked. Detect with a rising exception backlog. If you expand by resource count rather than evidence, you scale the wrong thing. Detect by tracking time-to-provision and ticket volume per cohort.

Alternatives: Big-bang rollout. Faster but higher risk of a bad first impression. Build vs buy: Crossplane and Backstage are open source, but you could use a managed service like Terraform Cloud. Centralized vs federated: central platform team owns the control plane, but product teams own their modules.

When things go wrong: If a canary cohort hits a quota violation, pause expansion, fix the policy, and re-run. If time-to-provision doesn't improve, interview the cohort to find the friction. If the old path is still used for 20% of requests after expansion, investigate why before retiring it.

Curated: · Written: · Reviewed:

Difficulty: Hard