Skip to content
Tech Interview Prep
Technical interview guide

Platform APIs & Abstraction Layers

Designing the interface between a platform and the teams using it: what to expose, and what to hide.

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

Scope: AWS and Microsoft platform engineering guidance, Google Cloud API Design Guide/AIPs, and Kubernetes API documentation current 2026-08-31.

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-1

Choose the right abstraction boundary for a platform capability.

Answer

Core answer

Assume the capability is a managed Postgres offering on an internal Kubernetes platform, and the consumer is a product team whose SLO is p99 read latency under 200 ms and 99.95% availability. My rule: expose a knob when the consumer's own SLO, data model, security posture, or cost line moves when they change it; hide it when only the platform's internals move.

So I expose Postgres major version (16), instance class, storage size and IOPS, backup retention in days, and the maintenance window. I hide the connection pooler, the failover mechanism, the node pool, and the storage backend.

Why the boundary holds or leaks

A boundary holds when the hidden layer cannot be observed through the consumer's contract. It leaks the moment the consumer's failure modes depend on the hidden layer. Concretely: I hide PgBouncer, but its defaults are pool_mode = session, default_pool_size = 20, max_client_conn = 100. A consumer whose app opens 300 connections gets FATAL: no more connections allowed (max_client_conn): a failure caused entirely by a layer I told them not to think about. That is a leak, and it is my fault, not theirs.

Two fixes, both legitimate:

  • Raise max_client_conn and keep the pooler hidden, accepting that a connection storm now costs me memory on the pooler host.
  • Expose a max_connections field that maps to max_client_conn, so the consumer owns the number that decides their failure.

I pick the second when consumers have wildly different connection counts, a 4-replica API at 25 connections each versus a 200-worker batch fleet, because then no single hidden default is right.

The test I actually run

For each candidate knob, ask: if the consumer sets it wrong, whose SLO breaks? If theirs, expose it. If only mine, hide it and pick a default that survives their worst case.

CandidateConsumer SLO moves?Decision
Postgres major versionYes: extension and query compatibilityExpose
Backup retention (days)Yes: RPOExpose
pool_modeNo, unless they hold session stateHide, default transaction
Node pool / AZ placementNoHide
max_connectionsYes: connection stormsExpose as max_client_conn

Failure modes and detection

  1. Hidden default too low: no more connections allowed in app logs. Alert on PgBouncer cl_waiting > 0 sustained for 60 s.
  2. Exposed knob with no guardrail: consumer sets max_connections = 5000, exhausts Postgres max_connections (default 100) on the primary. Detect via pg_stat_activity count and enforce a hard cap in the API.
  3. Boundary change without versioning: renaming a field silently breaks Terraform state. Detect via plan diff in CI before apply.

Alternatives and when not to

If the capability is single-tenant with one consumer, do not build a boundary at all: hand them the raw resource. A boundary is a compatibility surface you now maintain forever; only pay for it when you have three or more consumers with divergent needs. When you do change the boundary, add the new field alongside the old, mark the old deprecated, and remove it only after a migration window you have actually measured.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design a platform API for managed databases.

Answer

The 90-second answer

I'd model this as a declarative resource in the control plane we already run (a Kubernetes CRD, databases.platform.example.com/v1) not as a REST wrapper around the provider SDK. The hard part isn't creating databases; it's that creation takes minutes, providers drift, and tenants need to know what they're allowed to ask for. A declarative resource with a reconciler gives you all three: the user writes intent, a controller owns the outcome, and status is the only place observed truth lives.

Assumptions: internal platform, tenants are teams, AWS and GCP behind one API, Kubernetes as the control plane, one region per resource in v1.

The resource

spec is intent, status is observed, and they never mix.

YAML
apiVersion: platform.example.com/v1
kind: Database
metadata:
  name: orders-primary
  namespace: team-payments
spec:
  engine: {family: postgres, majorVersion: "16"}
  class: production          # dev | staging | production
  region: eu-west-1
  availability: multi-zone
  capacity: {minVCPU: 2, maxVCPU: 8, storageGiB: 200, autoscale: true}
  backup: {retentionDays: 35, windowUTC: "02:00-03:00", pitr: true}
  connectivity: {privateOnly: true, allowedNamespaces: [team-payments]}
  deletionProtection: true
status:
  observedGeneration: 7
  phase: Ready
  endpointRef: {secretName: orders-primary-conn, key: uri}
  conditions:
    - type: Ready
      status: "True"
      observedGeneration: 7
      reason: Provisioned

Three decisions matter. majorVersion is a string, not a number, because 16.0 parses as a float and comes back as 16. Endpoints are references to a Secret, never inline: the API server is not a secret store, and kubectl get db -o yaml ends up in CI logs. capacity is a range, not a size, because the provider's instance class is an implementation detail the tenant shouldn't pin; the controller picks the smallest class satisfying the range and reports the choice in status.

Verbs and the async model

Create/get/list/update/delete, plus ?dryRun=All for validation and resourceVersion preconditions on update, so two operators editing the same object get a 409 instead of last-write-wins. There is no separate resize or restore RPC: those are spec changes the reconciler turns into provider calls. Long-running work is not an operation ID the client polls; it's status.conditions plus observedGeneration. If metadata.generation is ahead of status.observedGeneration, the controller hasn't caught up. That's the whole progress API, and it survives a client disconnect.

Trade-offs

The alternative is a REST service with POST /databases and GET /operations/{id}. Easier to consume outside Kubernetes and easier to version, but you re-implement watch, optimistic concurrency, RBAC, audit and finalizers. The other alternative is a Terraform module per team: no control plane to run, but no drift correction and no shared quota enforcement. I'd take the CRD because we already run the API server, and pay for it with a schema that has to stay backward compatible forever. If most consumers lived outside Kubernetes and we had no control plane, the REST service would win.

Failure modes

Deletion is the one that bites. A DELETE sets deletionTimestamp; a finalizer platform.example.com/deprovision keeps the object alive until the provider confirms the instance is gone. If that call hangs, the object sits in Terminating forever and the namespace can't be deleted. Alert on any Database with a deletionTimestamp older than 30 minutes. Second: quota drift. A tenant at 50 databases hits the cap mid-reconcile, so enforce quota in a validating webhook and fail at admission, not silently in the controller. Third: a spec change the provider can't do in place, like shrinking storage. Reject it in the CRD's CEL validation rules rather than letting the reconciler loop.

Scale check

200 tenants × 50 databases = 10,000 objects. At roughly 4 KB each that's ~40 MB in etcd: nowhere near the API server's 1.5 MiB etcd request limit, but kubectl get databases -A must paginate (limit=500 plus a continue token), and the controller should watch with an informer rather than listing everything every 30 seconds.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design idempotent create and retry behavior.

Answer

Assumptions: an HTTP create endpoint, clients that retry on timeout, and a side effect that is either a local row or a remote call (payment, VM launch). If any of those is false the design changes, and I say where below.

Core answer. Pick the mechanism by who owns the identifier. If the caller can name the resource, make the name the key: PUT /v1/buckets/{client_id} with a client-generated UUIDv4 (122 random bits, collision risk negligible). If the server must mint the ID, require an Idempotency-Key header, the IETF draft draft-ietf-httpapi-idempotency-key-header, and store it.

Either way the protocol is record-then-act:

  1. Insert into idempotency_keys(key, caller_id, method, path, request_hash, state, response_status, response_body, created_at), unique index on (caller_id, key), state in_progress. Use INSERT ... ON CONFLICT DO NOTHING and check whether a row came back.
  2. No row returned → duplicate. Read the existing row. Same request_hash → replay the stored response. Different hash → 409 Conflict (Stripe returns 400 with type idempotency_error; pick one and document it).
  3. Row inserted → do the side effect, then update the row to completed with the response.

When the side effect is a local DB write, run steps 1 and 3 in one transaction, so no key exists without its resource. When it is remote you cannot: commit in_progress, call the provider with a provider-level token, then mark completed.

Retention. Stripe keeps idempotency keys for 24 hours. Your window must be at least the client's maximum retry span plus the request timeout. A client retrying at hour 25 with the same key is a new request and you double-create. Set the client retry budget well inside the window and write the number down.

Crash windows. Crash before step 1 commits: nothing happened, retry is clean. Crash after step 1, before the side effect: row is in_progress, no resource. Safe to proceed or return 409 with Retry-After. Crash after the side effect, before completed: row is in_progress and the resource exists. This is the dangerous one. Do not retry blind: discover by querying the provider with the same client token (EC2 RunInstances ClientToken is case-sensitive, max 64 ASCII characters) and adopt the existing resource. Alert on in_progress rows older than the p99 request duration.

approachuse whencost
caller-supplied ID (PUT)caller can name the resourceleaks ID scheme; needs a name-reuse policy
Idempotency-Key headerserver mints IDs, several endpointskey table, retention, GC
unique constraint on natural keyside effect is one local rowonly works if a natural key exists

Deciding criterion: if a natural key exists, the unique constraint is the whole solution. No key table. Add the key table only when the ID is server-minted or the side effect is remote.

Failure modes. Concurrent duplicates with the same key: the unique index lets one win; the loser must return 409 with Retry-After rather than proceeding. Key reuse with a different body is almost always a client bug: log the caller and both hashes. Name reuse is the subtle one: delete prod-db, recreate it, and an old idempotency record points at a dead ID. Never reuse a deleted name; tombstone it, so a retry cannot bind to a different resource than the one it created.

When not to. GET is already idempotent. An upsert keyed by a natural key needs no key table. And if the provider offers no idempotency token, discovery is impossible, then either make the operation reversible or accept at-least-once with a reconciliation job, and say so out loud.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Handle API request timeouts and retries.

Answer

Core answer (first 90 seconds)

Assume a POST /charges that moves money, a client with a 5-second deadline, and a provider call that can take 30 seconds. The mistake is treating the client timeout as the operation's lifetime: they are two different clocks. The client deadline bounds how long the caller waits; the server operation lifetime bounds how long the work runs. Separate them and the design falls out: give every mutating request a client-generated idempotency key, persist the key and the response before returning, and let retries carry the same key so the server dedupes instead of re-executing.

Concretely, the client sends Idempotency-Key: <uuid> (Stripe's convention). On first sight of the key the server writes (key, request_hash, status=in_progress) before calling the provider, then stores the response body and status on completion. A retry with the same key returns the stored response; the same key with a different body returns 409. That is the whole contract.

Retry policy

Retry only idempotent requests: GET/PUT/DELETE, or POST carrying a key. Retry on connection errors, 408, 429, 500, 502, 503, 504. Never retry other 4xx; they are terminal. Honor Retry-After when present, otherwise use exponential backoff with full jitter.

Python
import time, uuid, random, requests

def charge(amount_cents, idem_key=None, deadline=5.0):
    idem_key = idem_key or str(uuid.uuid4())
    start = time.monotonic()
    for attempt in range(4):                 # 1 try + 3 retries
        remaining = deadline - (time.monotonic() - start)
        if remaining <= 0:
            raise TimeoutError("deadline exceeded")
        try:
            r = requests.post(
                "https://api.example.com/charges",
                json={"amount": amount_cents},
                headers={"Idempotency-Key": idem_key},
                timeout=remaining,
            )
        except requests.Timeout:
            pass                              # ambiguous: server may have committed
        else:
            if r.status_code < 500 and r.status_code != 429:
                return r                      # 2xx success or terminal 4xx
        sleep = random.uniform(0, min(2.0, 0.1 * 2**attempt))
        time.sleep(min(sleep, max(0, deadline - (time.monotonic() - start))))
    raise TimeoutError("retries exhausted")

Trace: attempt 0 sleeps uniform(0, 0.1), attempt 1 uniform(0, 0.2), attempt 2 uniform(0, 0.4), attempt 3 uniform(0, 0.8). Worst case 1.5s of sleep. Each request gets timeout=remaining, so the client never waits past 5s. The key is generated once outside the loop, so all four attempts carry the same Idempotency-Key; that is what makes the retries safe.

Where the timeout lands decides the action

WindowServer stateClient seesCorrect action
Before acceptancenothing persistedreset / 504retry same key, safe
After acceptance, before provider callop recorded, no side effecttimeoutretry same key → server resumes
After provider success, before state writecharge exists, no local recordtimeoutretry same key → server must query provider by key before re-charging
After terminal response writtenresponse storedtimeout on readretry same key → server returns stored response

Trade-offs: continue or cancel

Continue means returning 202 Accepted with an operation id the client polls via GET /operations/{id}. Choose it when the operation is long (batch export, video encode) and the client deadline is short: you decouple the two clocks. Cancel means aborting server work and letting the client retry; choose it when the operation is cheap and idempotent, so holding resources buys nothing. The deciding criteria are expected duration versus client deadline, cost of holding the resource, and whether partial effects are recoverable.

Failure modes

The dangerous one is the third row: the provider committed but your state write never landed. Retrying blindly double-charges. Detect it by reconciling provider records against your idempotency table on a schedule, and by passing your key through to the provider when it supports one. Idempotency keys stop helping when the provider itself is not idempotent and cannot be queried: there you need reconciliation, not retries. And retrying a POST with no key duplicates by construction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design a platform API error contract.

Answer

What I'd say first. Assume a public HTTP/JSON platform API, multi-tenant, with both human-driven clients and SDKs, sitting behind a gateway in front of services that each speak their own error dialect. The contract has one job: let a client decide what to do next without reading English. So the envelope is RFC 9457 Problem Details (application/problem+json, which obsoletes RFC 7807) plus a small closed set of machine-readable fields. Everything else (prose, help links, violation lists) hangs off that and is optional for a client to ignore.

JSON
{
  "type": "https://api.example.com/problems/rate-limited",
  "title": "Rate limit exceeded",
  "status": 429,
  "detail": "Tenant acme exhausted 100 requests/minute.",
  "instance": "/v2/orders/8f3c",
  "code": "rate_limit.exceeded",
  "request_id": "01HQ8Z6M4T9K",
  "retryable": true,
  "retry_after_seconds": 12,
  "violations": []
}

code is the contract; detail is for humans and may change wording any release. request_id is echoed in the X-Request-ID response header and matches the traceparent (W3C Trace Context) the gateway propagated, so a support ticket maps to a trace. When retryable is true the response also carries Retry-After (RFC 9110), and retry_after_seconds mirrors it for clients that only parse bodies.

The decision table is the actual design.

statuscode familyretryableclient action
400request.malformednofix payload; do not retry
401auth.unauthenticatednorefresh token once, then fail
403auth.forbiddennoescalate; retrying is pointless
404resource.not_foundno—
409resource.conflictnore-read state, reconcile, resubmit
412precondition.failednore-fetch ETag, reapply change
422request.validation_failednofix each entry in violations[]
429rate_limit.exceededyessleep Retry-After, then retry
500internalyes, idempotent onlyexponential backoff with jitter
503unavailableyesbackoff, honour Retry-After

How a client consumes it. A POST with an Idempotency-Key returns 409 resource.conflict. The SDK does not retry: it re-reads the resource, merges, and resubmits under the same key. Same request returns 429 instead: the SDK reads retry_after_seconds: 12, sleeps, and resubmits the identical key. That difference is the whole point of retryable being explicit rather than inferred from the status class: 409 and 429 are both 4xx, and a client that treats "4xx = don't retry" gets the 429 case wrong, while one that treats "5xx = retry" hammers a 500 that was a non-idempotent write.

Failure modes, and how you catch them.

Clients parsing detail. A regex on "quota exceeded" breaks the day someone edits the string. Detect it by grepping SDK and partner code for matches on detail/title, and by a contract test that mutates detail text and asserts client behaviour is unchanged.

Adapter internals leaking. A database adapter surfaces ORA-00001: unique constraint SYS_C0012345. Detect with a golden-file test per adapter that serialises a fixture error and diffs the body, plus an alert on any 5xx body matching a stack-trace or SQLSTATE pattern. Internally, keep the raw adapter error in the trace span and a cause field stripped at the edge: diagnostics survive, callers don't see them.

Retry storm. Marking 500 retryable without jitter means 10k clients retry in lockstep; retry QPS can exceed original QPS. Detect by comparing retry traffic to first-attempt traffic per endpoint and alerting when the ratio climbs.

Existence leak. Check authorization before existence: return 404 for a resource the caller cannot see, 403 only when they can see it and lack the action. Otherwise 403-vs-404 becomes an enumeration oracle.

Trade-offs. Don't version the envelope per endpoint: version code semantics and add codes, never repurpose one. Avoid 207 partial success unless the method is explicitly bulk or asynchronous; a client that has to reconcile half-applied writes needs a job ID and a status endpoint, not a mixed body. And keep type URIs dereferenceable to docs, but never make a client fetch them at runtime.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design long-running operation semantics.

Answer

What I'd pin down first. "Long-running" here means the work outlives one HTTP request, seconds to hours, and the caller is a CLI, console, or another service that can disconnect, retry, or restart. I'll assume a control-plane API that provisions a resource, and that the provider underneath is itself asynchronous and can fail after we've already returned 202. That last assumption is what drives most of the design.

The core answer: the operation is a first-class resource, not a status field on the target. POST /v1/clusters returns 202 Accepted with Location: /v1/operations/op-9a1 and Retry-After: 2. The operation carries an opaque id, the target id, tenant, actor, request id, and the submitted revision: the revision is what makes a retry idempotent instead of a second cluster.

Shape it like Google's AIP-151: name, metadata, done, and exactly one of response or error. While done is false, metadata carries stage and progress; once true, response holds the terminal payload or error holds a google.rpc.Status with code, message, and details. Wire errors use RFC 9457 problem+json. States: queued, running, succeeded, failed, cancelled. The last three terminal and immutable.

Polling is the contract; push is an optimization. I'd ship polling first because it survives every network topology, and add webhooks later as a latency win, never as the only way to learn an outcome. A dropped webhook must not strand a caller.

Concurrency: reject, don't queue. A second POST for the same cluster gets 409 unless it carries the same Idempotency-Key, in which case return the existing operation with the same Location. Stripe retains idempotency keys 24 hours; for provisioning that's too short, since the operation itself can run longer: I'd hold keys 7 days.

Cancellation is best-effort and the API should say so. It stops future steps; it does not roll back. The operation goes cancelling → cancelled, and the terminal payload lists residual resources (the load balancer already billed, the IP still allocated) so the caller can clean up. Kubernetes does the same with finalizers: deletionTimestamp is set, the object survives until the controller finishes.

Failure modes worth naming.

  • Ambiguous provider outcome. The worker dies after the provider accepted the create but before we recorded it. Every provider call carries our operation id as a client token; on restart, reconcile by listing provider resources tagged with that token before retrying. Never blind-retry a create.
  • Restart. Operation state lives in the same database as the target, written in the same transaction as the intent row, so a crash can't leave an operation with no target or a target with no operation.
  • Expiry. Operations are retained 30 days past terminal, then GET returns 404. The target resource is the source of truth after that; clients must not depend on operation history.

Permissions are four separate checks: create, get, list, cancel. get on an operation requires read on the target, not just on the operation id, or operation ids leak resource existence across tenants.

Worked trace.

teventoperation state
0.0sPOST /v1/clusters, Idempotency-Key: 7f3crow written: queued, revision 42
0.0s202, Location: /v1/operations/op-9a1, Retry-After: 2queued
0.4sworker claimsrunning, stage=network
38s—running, stage=nodes, progress 3/5
2m10sprovider returns endpointsucceeded, done=true, response={cluster_id, endpoint}
2m11sGET /v1/operations/op-9a1200, done=true
+30dGET404

The thing I'd defend hardest in review: the operation id is opaque and never encodes tenant or sequence, because both invite clients to parse it and both leak.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design optimistic concurrency and field ownership.

Answer

Core answer (first 60-120 seconds)

Assumptions I state before answering: the API fronts a shared store, the same object has multiple independent writers (a human in a UI, a CI pipeline, a controller), and there is no distributed lock between them.

Given that, three mechanisms: give every resource an opaque version token; require every mutation to carry the token it was based on and reject the write if the object moved; give every field exactly one owner, so writers rarely contend for the same field at all.

In practice the read returns metadata.resourceVersion (Kubernetes) or an ETag (plain HTTP: RFC 9110 If-Match). The write must include it. A stale token gets 409 or 412 and the response carries the current object, so the client re-reads, re-applies its intent, and retries. Never blind-retry a full-object write: re-read, re-merge, re-send.

How a conflict actually resolves

Two operators scale the same Deployment. Both GET at resourceVersion: 1024, seeing replicas: 3, image: app:1.7.

  1. A PATCHes replicas: 5 with 1024. Accepted, stored at 1030.
  2. B PATCHes image: app:1.8 with 1024. The API server compares 1024 to the stored 1030 and rejects with 409, body: Operation cannot be fulfilled on deployments.apps "web": the object has been modified; please apply your changes to the latest version and try again, plus the current object.
  3. B re-reads at 1030, sees replicas: 5, builds a patch containing only image, retries with 1030.

Both intents survive. Under last-write-wins, step 2 as a full-object PUT writes replicas: 3 back and A's change is gone with no error, no log, found later on a dashboard.

The same pattern outside Kubernetes is a compare-and-swap: UPDATE deploy SET replicas=?, version=version+1 WHERE id=? AND version=?, and zero rows affected means conflict.

Field ownership

Versions stop interleaving; ownership stops contention. Classify every field: user-settable spec, platform default, policy (set by an admission layer), controller-written status. Then:

  • Split subresources. spec is desired state the user writes; status is observed state the controller writes at /status, so its writes cannot race spec writes at all.
  • Record ownership. Kubernetes server-side apply (GA in 1.22) keeps a managedFields entry per field manager, with the operation (Apply or Update) and the field set. A second manager applying to a field the first owns gets 409 naming the owner; --force-conflicts takes ownership rather than merging.
  • Patch, don't replace. A merge patch or update mask touches only named fields, so a slightly stale writer cannot clobber unrelated fields.
  • Keep defaulting a pure function of the object. Defaulting runs at decode on every write, before validation, so a context-dependent default silently rewrites fields on unrelated writes.

For long-running operations, bind the accepted revision to the operation and compare-and-swap back on completion: if the object moved, either re-apply the delta or fail as superseded. Decide that per operation, not globally.

Failure modes and detection

FailureSignalCost
Conflict retry storm409 rate spikes while throughput is flateach retry is a fresh read plus write; a UI polling a hot object can exceed the write limit alone
Ownership fightone field flips every reconcile; managedFields shows two managerseach flip rolls the Deployment; replicas oscillating 3/5/3 restarts pods repeatedly
Token too coarseconflict rate near 100% on one busy resourcethroughput collapses to one writer at a time
Precondition never checkedno errors anywherelost updates; detect by diffing audit actor plus version across writes to the same object

What would change the decision

Additive fields (counters, log entries) want a CRDT or append-only log, not conflict detection. Single-writer resources are simpler with a lease. Telemetry that tolerates lost updates is fine with last-write-wins, and paying for CAS there is wasted complexity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design deletion semantics for a platform resource.

Answer

Core answer

First I'd pin down what "delete" means, because the word hides four different operations. My assumption: this is a multi-tenant platform resource that owns data, holds credentials, and can be referenced by other resources. Under that assumption I'd model deletion as an explicit state machine with a plan phase and an asynchronous execution phase: never a synchronous DELETE that returns 200 and calls it done.

The states: Active → PendingDeletion → Deleting → Deleted. Entering PendingDeletion sets a deletionTimestamp and blocks new writes while reads keep working: this is the Kubernetes finalizer pattern, where a resource with finalizers stays in Terminating until each finalizer is removed. Deleting runs ordered cleanup steps. Deleted leaves a tombstone row behind.

Why ordering matters

Cleanup order is not cosmetic. Revoke credentials and external bindings first, then detach dependents, then destroy data, then the record. Destroy the parent before detaching a child and the child holds a dangling reference: every read of it returns a 500 instead of a clean 404. Delete data before revoking a credential and a still-valid token can read or recreate what you just removed.

The four semantics and how to choose

OperationReversibleData keptUse when
Disableyes, instantallbilling or abuse hold, suspected compromise
Detachyesallremoving a dependency, not the resource
Archiveyes, slowcold copyretention or legal hold
Destroynononeuser-initiated, no hold attached

Deciding criterion: if a legal hold or retention policy is attached, destroy is off the table. Archive instead. If the caller is a human who might have clicked wrong, default to a recovery window.

Recovery window

GCP projects are soft-deleted and restorable for 30 days; that is a reasonable default for a platform resource. The cost is real: you keep paying for the storage and you must exclude soft-deleted names from quota accounting. Make the window a per-resource-type setting, not a global constant.

Failure modes

Stuck Deleting: a cleanup step fails and the resource sits in Deleting forever. Detect it with a per-step deadline, if a step reports no progress for, say, 15 minutes, mark the operation Failed and surface the failing step rather than retrying silently. Operational cost: a stuck resource still counts against quota and still bills.

Partial failure: cleanup is N steps and step 3 of 7 fails. The operation must report which steps succeeded so a retry is idempotent: each step keyed by operation ID, so re-running skips completed steps.

Name reuse: free the name immediately and a new resource can adopt the old one's identity, inheriting its audit trail, DNS records, or IAM grants. Keep a tombstone that reserves the name. GCP project IDs are never reusable for exactly this reason. Return 410 Gone for the old name, not 404.

Authorization

Irreversible effects need stronger auth than the read that preceded them: bind the confirmation to the resource revision the user saw, so a delete approved against revision 7 fails with 409 Conflict if the resource is now at revision 9. Otherwise a user approves deletion of a resource that has since gained a dependent.

Never treat HTTP acceptance as completion. 202 Accepted means the operation started. The client polls the operation until it reports Done, and only then is the resource gone.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design list, search, and pagination safely.

Answer

Assumptions I'd state before designing: multi-tenant SaaS on Postgres 15, one documents table around 40M rows, a list/search endpoint that clients poll while scrolling, and a hard rule that no tenant sees another tenant's rows, counts, or facets.

Core answer (first 90 seconds). Paginate with keyset (seek) pagination on a stable composite sort key, not OFFSET. Return an opaque, signed, expiring cursor that encodes the last row's sort key, the caller's tenant, and a hash of the active filters. Cap page size at 100 with a default of 25. Serve counts from a snapshot or an approximation, never a live exact COUNT(*). Push authorization into the query predicate so unauthorized rows are never fetched, not filtered after the fact.

SQL
-- index: CREATE INDEX ON documents (tenant_id, created_at DESC, id DESC);
SELECT id, created_at, title
FROM documents
WHERE tenant_id = $1
  AND (created_at, id) < ($2, $3)   -- last row of previous page
ORDER BY created_at DESC, id DESC
LIMIT $4;

The row-value comparison (created_at, id) < ($2, $3) is what makes the sort total: created_at alone is not unique, so ties would skip or duplicate rows. The index makes this an index seek: p99 around 8 ms at 40M rows, versus roughly 1.2 s for OFFSET 100000 LIMIT 25, which walks 100k index entries before returning anything.

Cursor. HMAC-SHA256 over a base64 JSON payload {tenant, created_at, id, filters_hash, exp}, truncated signature appended. TTL 15 minutes; expiry returns 410 with a restart hint. The server rejects a cursor whose tenant differs from the authenticated caller, and one whose filters_hash no longer matches the request's filters.

Alternatives, and when each is wrong.

ApproachCostUse when
OFFSET/LIMITO(offset) scan; drifts under insert/deleteSmall sets, or you genuinely need jump-to-page-N
KeysetO(log n) seek; no random page accessInfinite scroll, large tables: the default here
Snapshot countLong-lived transaction, bloatRarely; prefer embedding a count in the cursor
Live exact countFull filtered index scan per pageNever on 40M rows

Worked trace: why offset drifts and keyset doesn't. Five docs, page size 2, ordered created_at DESC, id DESC: A(10:00,5), B(09:59,4), C(09:58,3), D(09:57,2), E(09:56,1). Page 1 returns A, B. Now A is deleted.

  • Offset: page 2 is OFFSET 2 LIMIT 2 over the remaining B, C, D, E → returns D, E. C is silently skipped.
  • Keyset: cursor is (09:59, 4); page 2 is WHERE (created_at, id) < (09:59, 4) → returns C, D. No skip, no duplicate.

Failure modes and how I'd detect them.

  • Cross-tenant cursor replay. Attacker edits the cursor body; signature check fails → 403, alert on the counter. Without the tenant field inside the signed payload, a valid cursor from tenant X returns tenant Y's rows.
  • Permission revoked mid-scroll. Cursor carries the caller's authz version; if the role changed, return 409 and force a restart. Otherwise page 2 serves rows the caller can no longer see.
  • Count leakage. A total count reveals a hidden tenant's document volume. Compute counts only over the authorized predicate, and cap: count to 10,000 then return "10,000+".
  • Facet and autocomplete leakage. Facets computed before the authz predicate expose the existence of hidden docs. Compute after, and rate-limit: token bucket per tenant, 20 search req/s burst 40, separate bucket for full-text and facet queries.
  • Count drift. Live counts move between pages ("1,204" then "1,198"). Embed the count in the cursor at creation and label it "as of <time>".

When not to use keyset: if the product needs jump-to-page-500, keyset can't express it. Use offset with a hard cap (max offset 10,000) or a search engine that supports deep paging. And if the sort key isn't unique, add a tiebreaker column before shipping.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design authorization for the platform API.

Answer

Core answer (first 90 seconds)

Assume a multi-tenant platform API where resources nest org → team → workload → environment, and some operations are long-running (plan/apply) or delegated (a different human approves). I'd answer in three moves: pick the model, define the action surface, decide where the check runs.

Model: relationship-based authorization (ReBAC, Zanzibar-style) as the base, with attribute conditions layered on top. Ownership and tenancy are relationships (owner, member, parent), so "can team T read workload W" is a graph walk, not a role lookup. Attributes (environment, change-freeze window, request origin) are conditions on the edge. Pure RBAC can't express per-resource sharing without role explosion; pure ABAC becomes unauditable policy sprawl. ReBAC gives you the hierarchy for free and keeps sharing explicit.

Action surface: separate discover/list/get from propose/plan, mutate/apply, cancel, delete, override, admin. Different verbs, different blast radius, different approvers. A plan reads live state; apply mutates it. Don't collapse them into "write".

Where the check runs: at the API edge for the request, and again at execution for anything asynchronous. The edge check authorizes the submission; the execution check authorizes the effect. Between them the world changes, so bind the approval to a revision.

Mechanism

A check is check(subject, action, resource). The engine resolves the resource's relationship graph and evaluates conditions. For apply on workload:W:

  1. Resolve W's parents up to org.
  2. Find subjects with owner/member on any ancestor.
  3. Filter by the action's required relation (apply needs owner or deployer, not viewer).
  4. Evaluate attribute conditions (env in allowed set, no active freeze).
  5. Return allow/deny with the path that granted it.

The path matters: it's what you log and what an audit reads.

Confused deputy

The API runs with a service identity that can reach networks, secrets, accounts. That power is the API's, not the caller's. Never let a caller's request borrow it. Every referenced object (network, secret, account, dependency) is authorized against the caller's relationships at submission and again at execution. Short-lived provider credentials are how the API acts; they are not a grant to the caller.

Trade-offs

modelstrengthcost
RBACsimple, cacheablerole explosion for per-resource sharing
ABACfine-grained conditionspolicy sprawl, hard to audit
ReBAChierarchy + sharingneeds a consistent relationship store

Pick ReBAC when sharing and nesting dominate; RBAC when the org is flat and roles are few; ABAC only as conditions on top of one of them.

Failure modes

  • Stale approval: the revision drifts between plan and apply. Detect by comparing the approved revision hash to the current one; deny on mismatch.
  • Cross-tenant reference: caller passes another tenant's resource ID. Resolve the resource's tenant, compare to the caller's; deny and alert.
  • Enumeration: list/search/count leak existence. Filter every result set by scope, counts included.
  • Delegation laundering: a delegate acts with more power than the delegator. Preserve original actor and delegation chain through providers; audit every transition.

Trace

check(alice, apply, workload:W)
  W.parent = team:T, T.parent = org:O
  alice --member-->   T   (viewer)
  alice --deployer--> T   (granted 2024-03-01, expires 2024-06-01)
  action apply requires relation in {owner, deployer}
  condition: env=prod, freeze=none
  => ALLOW via alice--deployer-->T

Cache the resolved path per (subject, action, resource) with a short TTL; invalidate on relationship writes. That keeps the common read path off the relationship store without letting a revoked grant linger.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Decide whether to expose an API field.

Answer

What I'd say first

Assumptions: a public HTTP API, third-party clients I don't control, a versioned surface, and I run the storage. The question is whether to put a field on the wire, so the real cost is that it becomes a contract I have to honour for years.

My default: expose the field only if the caller's correctness depends on controlling it and I can hold the semantics unchanged for the life of the version. Otherwise keep it internal and pick a default that's safe for the common case.

Concrete case: a read API where I can serve from replicas (eventual) or the primary (strong). Should I expose consistency: "strong" | "eventual" per request?

Why exposure is the expensive direction

Once a client sends consistency=strong in a code path, that string is in their source, their tests, their retries. I can't remove it without a version bump and a migration window, and I can't weaken what strong means without silently breaking their correctness assumptions. That's the asymmetry: adding a field is a one-line change for me, removing it is a multi-quarter deprecation for them.

The deciding criteria

  • Does the caller's correctness actually depend on it? If a stale read causes a duplicate charge, yes. If it only affects freshness of a dashboard, no.
  • Can I define stable semantics? strong must mean read-your-writes and monotonic, not "probably fresh."
  • Can I afford the worst case where every caller sets the expensive value?

That last one is the one people skip. Say I serve 20k read rps and 30% go strong: that's 6k rps on a primary sized for 2k. p99 goes from 40 ms to 180 ms and the primary becomes the outage. The field's cost isn't the field, it's the traffic pattern it invites.

Alternatives, and when the rule flips

optioncaller controlmy costreversibility
per-request consistency enumfullstrong reads pin the primaryhard
session token (read-your-writes)implicitsticky routing, cheapmedium
separate /strong-read endpointcoarseroute-levelmedium
no field, always eventualnonecheapesteasy

I'd flip to exposing the enum only when the caller genuinely needs to choose per call and I can serve strong reads without a primary bottleneck: for example, strong reads go to a quorum of replicas. If strong reads must hit a single primary, I'd ship the session token instead: it gives read-your-writes for free and I can change the mechanism behind it.

Failure modes

  • Client sets strong on every read "to be safe." Detected by per-tenant strong-read ratio in telemetry; cost is primary saturation.
  • Client relies on the default and reads stale after a write. Detected by a read-your-writes test in CI; cost is a duplicate order or a lost update.
  • I later redefine eventual to include a 5-second cache. Silent, no error, wrong data. Detected only by a contract test.

Before release

Pin down: what absence means (default to eventual), what null means (reject it), mutability (immutable per request), validation (enum, 400 on anything else), and output visibility (echo it back so clients can log it).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Evolve a stable platform API compatibly.

Answer

Core answer

Assume I can't coordinate an upgrade across every consumer: some SDKs are pinned, some clients are third-party, and some stored objects were written years ago. So "compatible" means three separate contracts hold at once: source (does it still compile), wire (does it still parse), and semantic (does it still mean the same thing). The first two are mechanical. The third is where teams actually get burned.

My default is additive-only: new optional fields, new endpoints, new enum values only where the consumer treats enums as open. Nothing is renamed, removed, retyped, or reinterpreted in place. Anything that can't be expressed additively gets a new major version served alongside the old one, not a mutation of the old one.

Why additive works, and where it doesn't

Wire formats are built to tolerate the unknown. Protobuf skips fields it doesn't recognise, and proto3 preserves them (since 3.5) so a proxy can round-trip a message it doesn't understand. Most JSON parsers ignore unknown keys. That's the mechanism: the old reader never sees the new field, so it can't be affected by it.

The failure is on the other side. Jackson enables FAIL_ON_UNKNOWN_PROPERTIES by default, so a Java client with a strict mapper throws on a field you considered additive. A JSON Schema with additionalProperties: false rejects it. A proto2 closed enum drops an unknown value into unknown fields; a proto3 open enum keeps it, but a Java switch over that enum falls to its default branch. So "additive" is only additive relative to the consumers you've actually checked.

Change classes

ChangeVerdictWhy
New optional response fieldSafe if consumers ignore unknownsOld readers never see it
New enum valueRiskyClosed enums and exhaustive switches break
New required request fieldBreakingOld clients can't send it
Tighter validationBreakingInputs that passed now 400
Changed defaultSilent breakSame request, different result
Reordered list or changed page sizeSilent breakClients that assumed order or size
Renamed field or resourceBreakingWire and stored objects both

Deprecation on a clock

Kubernetes is the model I'd copy: GA APIs get at least 9 months or 3 releases of deprecation notice, beta at least 3 releases, and removal is announced in the changelog before it happens. Concretely, for a hypothetical platform with 40 services and 12 SDK versions in the wild, the oldest 3 years old, I'd set the window from the oldest supported client, not the newest: a 6-month window covering only the last two SDK releases strands everyone else.

When additive is the wrong answer

If the old behaviour is a security bug (a field that leaks a token, a default that's now unsafe) additive evolution is the wrong tool, because you need the old behaviour to stop, not to coexist. Same if the field's name is a lie about its units. There you ship a new field, mark the old one deprecated in the schema, and set a removal date; you don't quietly change what the old one means.

Failure modes and detection

  • Strict decoder rejects a new field: caught by running old SDK versions against the new server in CI, not by unit tests on the new client.
  • Persisted objects written under old semantics read wrong: caught by fixture replay of real stored records.
  • A consumer depends on ordering or page size you never promised: caught by consumer-driven contract tests (Pact) and by telemetry on which fields each client actually reads.

That last one is the point of consumer telemetry: you can't deprecate what you can't see being used.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Deprecate a platform API version.

Answer

What I'd say first

Deprecating an API version is a migration project with a deadline, not an announcement. Before I tell anyone anything, I need three things: a complete list of callers keyed by the credential they authenticate with, a replacement that covers the semantics they actually use, and a way to see who is still calling after the deadline. If I can't produce the first, the rest is guesswork.

Assumptions: I control the gateway in front of the version, the contract is documented, and consumers are a mix of external integrators and internal services.

Inventory by credential, not by portal

Portal traffic only shows the humans who logged in. It misses server-to-server calls, scheduled jobs, and anything embedded in stored resources. So I join gateway access logs (keyed by API key, OAuth client_id, or mTLS subject) against account and billing records. That gives me a caller list I can name an owner for.

The subtle part is semantic use. A client might hit /v2 only for a health check but store v2 resource IDs in its own database. The real dependency is the ID format, not the endpoint. So I sample response fields per credential, not just request counts, and I scan stored customer data for v2-shaped identifiers.

Timeline

PhaseDurationGateway behaviourWhat I measure
Announceday 0200 + Deprecation/Sunset headersnew keys issued against /v2
Migrate0–6 months200 + headers, weekly owner reportsdistinct credentials still calling /v2
Freezelast 30 days200 + headers, no new keyscredentials with zero v3 calls
Sunsetafter the date410 + Link to migration guide410 count per credential

Choosing the compatibility mechanism

Three options: an adapter that translates v2 requests to v3, dual-serve where both versions run against the same store, or a hard cutover. The adapter is cheapest when the gap is syntactic: renamed fields, moved paths. Dual-serve is right when the gap is semantic, different ID schemes or pagination, because an adapter can't fake consistency. Hard cutover only when you can enumerate every caller and they can all change. I'd avoid deprecating at all if the version is load-bearing for a paying customer with no migration path; better to freeze it and stop new adoption.

Failure modes and how I'd catch them

  • Resurrection. A credential goes quiet, then returns after sunset. Detect with a 410 counter per credential; alert on any non-zero after the sunset date.
  • Zombie scheduled jobs. A monthly billing job looks dead in a 30-day quiet window. Fix: measure the longest observed inter-arrival per credential and set the quiet window to at least twice that. A credential whose max gap is 31 days needs more than 62 days of silence before you call it dead.
  • Silent breakage of stored resources. v2 IDs embedded in customer data break on read, not on call. Detect by running a compatibility check against stored data before sunset, not after.

What the gateway returns

Before sunset:

$ curl -si https://api.example.com/v2/orders/42 -H 'Authorization: Bearer <key>'
HTTP/2 200
deprecation: @1735689600
sunset: Wed, 01 Jan 2025 00:00:00 GMT
link: <https://api.example.com/docs/v3-migration>; rel="deprecation"

After:

$ curl -si https://api.example.com/v2/orders/42
HTTP/2 410
sunset: Wed, 01 Jan 2025 00:00:00 GMT
link: <https://api.example.com/docs/v3-migration>; rel="deprecation"

410 Gone, not 404: it tells the caller the resource existed and was deliberately retired. Sunset is RFC 8594; the Deprecation header is RFC 9745.

Close

Only stop serving after the window and the evidence. Keep read-only or audit access where a contract or regulation requires it, revoke the retired credentials, and keep the 410 counter running so resurrection shows up.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Test platform API compatibility.

Answer

Clarify first. "Compatibility" is three different claims and they fail differently. Wire compatibility: the old client can parse the new server's bytes. Source compatibility: the old client's generated code still compiles against the new schema. Semantic compatibility: the old client's behaviour is unchanged. Most teams test the first, assume the second, and get paged for the third.

Assumptions I'd state out loud: a versioned HTTP/JSON API plus gRPC, clients pinned to a version (Stripe-style Stripe-Version header, or GitHub-style X-GitHub-Api-Version: 2022-11-28), server deploys independently of clients, and we support the current client plus two back. If clients are pinned by URL path instead (Twilio-style /2010-04-01/), the matrix collapses to one row per version and the problem is mostly deprecation, not compatibility.

The core answer: test the matrix, and make the matrix the artefact. Four supported client versions against three deployed server versions is 12 ordered pairs. Testing only adjacent pairs, old/old and new/new, is 4 runs and misses exactly the pairs that break: old client against new server. Run all 12 in CI against ephemeral servers; it's cheap because the payloads are fixtures, not live traffic.

pairwhat it catches
old client → new serverunknown response fields and enums, changed defaults, new pagination cursors
new client → old serverabsent fields, missing defaults, 404 on endpoints the client assumes exist
old client → old serverbaseline; if this fails, your fixture is wrong, not the server

Why wire compatibility is the easy half. Protobuf gives you most of it for free: unknown fields are retained (proto3 since 3.5), adding a field is safe, and the hard rules are narrow. Never reuse a field number, and reserved anything you delete. JSON gives you nothing for free. Go's encoding/json silently drops unknown fields unless you call Decoder.DisallowUnknownFields(), which is the right default for a server and the wrong one for a client.

The break is almost never the parse. It's the enum.

Go
type Status int32
const (
    StatusPending Status = 0
    StatusRunning Status = 1
    StatusDone    Status = 2
)

func terminal(s Status) bool {
    switch s {
    case StatusDone:
        return true
    }
    return false
}

Trace it: the server adds StatusCancelled = 3. An old client decodes 3 without complaint, wire-compatible, falls through the switch, returns false, and its poll loop never terminates. The same change in Java throws IllegalArgumentException out of Status.valueOf and surfaces as a 500. Identical wire bytes, two different outages. Detection: a contract test that feeds every enum value the new server can emit into every supported client's decoder and asserts a terminal state, not merely a successful parse.

Failure modes worth naming. A changed server-side default, page size 20 → 50, passes every parse test and silently doubles a client's peak memory; detect by asserting on response content, not status code. A cursor format change breaks a client mid-pagination; detect by replaying a captured multi-page sequence, not a single request. Long-running operation metadata gains a field the old client's discriminated union doesn't know; detect with a golden fixture per operation state. And rollback: the new server wrote a resource the old server can't read. Detect by upgrading, writing, rolling back, and reading: the only test that catches a storage-version mistake.

Trade-offs. The full matrix costs 12 CI runs plus a fixture per version. Pairwise-plus-canary costs less but only catches what production traffic happens to exercise, and you find out during an incident. I'd run the full matrix in CI, where fixtures are cheap, and reserve shadow and canary replay for traffic shapes you can't synthesise. Contract diffs in CI should fail the build only on wire-breaking changes; semantic changes need a human, because no diff tool knows your client's state machine.

Deprecation. Instrument real client versions from the request header, and don't deprecate until the tail is under your threshold. Kubernetes' own policy (beta APIs removed after 9 months or 3 releases, whichever is longer) is a floor, not a target.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design platform API documentation and SDKs.

Answer

Clarify and assume. "Platform" could mean an internal API for other teams or a public one for external developers. I'll assume external or cross-org consumers, because that's the harder case and the internal one is a subset. The core answer: one authoritative machine-readable contract, and everything mechanical generated from it.

Core. Write the contract as an OpenAPI 3.1 document in git. Generate the reference docs, the SDKs, and a mock server from it. Reserve hand-written prose for what a generator can't produce: task-oriented guides, migration notes, and the reasoning behind design choices.

Why 3.1 and not 3.0: 3.1 aligns with JSON Schema 2020-12, so nullable: true becomes type: [string, "null"], and the same schema that generates SDK types also validates requests in CI and drives the mock server. One definition, three consumers.

Pipeline: spec in git → CI lints it (Spectral) and validates schemas → generators run → SDKs publish to package registries, reference docs publish to the portal. A spec change that breaks a consumer fails CI before merge.

What's generated vs hand-written.

SurfaceSourceWhy
Reference: endpoints, fields, types, status codesGeneratedMechanical; must not drift
Typed SDKsGeneratedSame
Mock serverGeneratedConsumers build before the API ships
Task guides ("upload, then poll for completion")Hand-writtenA generator can't sequence a workflow
Changelog, migration guidesHand-writtenNeeds judgment about impact
Error catalogGenerated codes + hand-written remediationCodes are mechanical; fixes aren't

Trade-offs. Generated SDKs are often idiomatic-hostile: Java clients that ignore the ecosystem's builder patterns, Python clients that fight requests. Two options: ship the generated client and document its shape, or hand-write a thin SDK over a generated core. I'd hand-write the public surface for the one or two languages the customer base actually uses and generate the rest. The deciding criterion is support load: every hand-written SDK is another thing to maintain across API versions. When not to generate SDKs at all: fewer than ~5 consuming teams, all internal, and a documented REST API plus curl examples is enough. SDKs earn their keep when external consumers would otherwise reimplement auth, retry, and pagination.

Failure modes, with detection.

  • SDK drift from spec. Detect with a CI job that runs the generated SDK's integration tests against staging on every spec change.
  • Docs drift from behavior. Run every code example as a test against staging. An example that 404s is a broken doc.
  • Secrets in examples. Pre-commit hook plus CI scanner (gitleaks) over the docs repo. Examples use structurally valid but non-functional placeholders.
  • Idempotency misuse. If you document Idempotency-Key without stating the window, clients retry outside it and double-charge. State the window, Stripe's is 24 hours, and replay the original response inside it.

Artefact: the idempotency contract in the spec.

YAML
paths:
  /v1/transfers:
    post:
      parameters:
        - name: Idempotency-Key
          in: header
          schema: { type: string, maxLength: 255 }
      responses:
        '201': { description: Created }
        '409': { description: Key reused with a different body }
        '429':
          headers:
            Retry-After: { schema: { type: integer } }

Trace: client POSTs with key K, gets 500, retries with K inside 24h → server replays the original 201. Retries with K but a different body → 409. Retries after 24h → treated as a new request. That's the behavior the docs must state, and the SDK must not paper over.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Support portal, CLI, and GitOps clients from one API.

Answer

Answer

Make the API canonical and the clients thin. Assumption: the API owns resource semantics, validation, authorization, and audit, and no client writes to the datastore directly. The portal, CLI, and GitOps controller are then three renderings of one resource model. The moment a client owns a business rule, that rule drifts.

Each client needs a different contract from the same API:

ClientNeedsAPI contract
PortalDiscovery, form generation, progressive disclosureOpenAPI 3.1 + JSON Schema, OPTIONS for allowed methods
CLIStable machine-readable output, scriptable failure--output json|yaml with a versioned schema, exit 0 success / 1 error / 2 usage, no prompts under --non-interactive
GitOpsDeclarative apply, conflict detection, reconciliation statusresourceVersion on writes, status subresource, observedGeneration

Concurrency. GitOps is where the design is decided. The controller reads desired spec from Git, GETs the live object, and writes back carrying the resourceVersion it read. If another writer got there first, the server rejects the stale write. Two ways to express that, and you should pick one and document it: put resourceVersion in the body and return 409 Conflict (what the Kubernetes API server does), or use an HTTP ETag with If-Match and return 412 Precondition Failed. Don't mix them.

Idempotency. POSTs accept an Idempotency-Key header; the server stores key → response for 24 hours and replays it on retry. That's Stripe's convention and it's the right shape: a flaky CLI retry or a double-clicked portal form returns the original 201 instead of a duplicate. Use dryRun=All on POST/PUT/PATCH so both the portal's preview and cli apply --dry-run validate without persisting.

Reconcile loop (30s tick):

desired = readFromGit(path)              # spec only; Git holds no status
actual  = GET /v1/widgets/{name}         # 404 -> POST to create
if actual.metadata.generation == actual.status.observedGeneration:
    continue                             # this revision is already reconciled
resp = PUT /v1/widgets/{name}            # body carries actual.metadata.resourceVersion
if resp.status == 409:
    continue                             # lost the race; next tick re-reads
PATCH /v1/widgets/{name}/status          # observedGeneration = resp.metadata.generation

Note the generation check is against the live object, not the Git file: Git has no server-assigned generation. The status subresource exists so a spec write can't clobber status, and so RBAC can grant status writes to the controller alone.

Failure modes and detection.

  • No idempotency → duplicate resources on retry. Detect: duplicate names, or two creates in the audit log for one client action.
  • No optimistic concurrency → silent lost updates. Detect: a write whose resourceVersion predates the current one, or state that doesn't match the last applied spec.
  • Validation drift between clients → the portal accepts what the CLI rejects. Detect: a parity test that runs the same payload through both and diffs the error bodies.
  • Status never updated → observedGeneration stuck behind metadata.generation. Detect: alert on the age of that gap, not on error rate.

Trade-offs. Generate clients from OpenAPI when you have several languages and a stable surface; hand-write when there are one or two and the API moves weekly: generated clients bloat and lag. REST+JSON over gRPC: gRPC gives you streaming and codegen, but browsers need grpc-web and curl-style CLI scripting gets awkward. For a GitOps controller, REST with resourceVersion is the well-trodden path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design a provider adapter interface.

Answer

I'd clarify two things first: is this a multi-tenant platform calling several external providers, and who owns authorization? I'll assume yes to multi-tenant, Go 1.22, and the platform owns policy. The adapter is an outbound port: it translates domain operations into provider calls and normalizes what comes back. It does not decide whether a tenant may create a resource.

Go
type Operation string
const (
    OpCreate  Operation = "create"
    OpObserve Operation = "observe"
    OpUpdate  Operation = "update"
    OpDelete  Operation = "delete"
    OpImport  Operation = "import"
)

type Capabilities struct {
    InterfaceVersion string // "v1"
    Operations       map[Operation]bool
    RateLimit        RateLimit
}
type RateLimit struct{ RequestsPerSecond, Burst int }

type Adapter interface {
    Capabilities(ctx context.Context) (Capabilities, error)
    Create(ctx context.Context, req CreateRequest) (CreateResult, error)
    Observe(ctx context.Context, ref ResourceRef) (ResourceState, error)
    Update(ctx context.Context, req UpdateRequest) (UpdateResult, error)
    Delete(ctx context.Context, req DeleteRequest) error
    Import(ctx context.Context, req ImportRequest) (ImportResult, error)
    Health(ctx context.Context) (Health, error)
}

type CreateRequest struct {
    TenantID       string
    IdempotencyKey string // caller-generated, stable across retries
    Spec           ResourceSpec
}
type CreateResult struct {
    Ref               ResourceRef
    State             ResourceState
    ProviderRequestID string
}
type ResourceRef struct{ Provider, ID, Region string }
type ResourceState struct {
    Status    Status
    Version   string
    UpdatedAt time.Time
}
type Status string
const (
    StatusPending  Status = "pending"
    StatusReady    Status = "ready"
    StatusFailed   Status = "failed"
    StatusDeleting Status = "deleting"
    StatusDeleted  Status = "deleted"
)

type ErrorClass string
const (
    ErrInvalid     ErrorClass = "invalid"
    ErrNotFound    ErrorClass = "not_found"
    ErrConflict    ErrorClass = "conflict"
    ErrRateLimited ErrorClass = "rate_limited"
    ErrUnavailable ErrorClass = "unavailable"
    ErrAuth        ErrorClass = "auth"
    ErrUnsupported ErrorClass = "unsupported"
    ErrInternal    ErrorClass = "internal"
)
type Error struct {
    Class             ErrorClass
    Retryable         bool
    RetryAfter        time.Duration
    ProviderCode      string
    ProviderRequestID string
    Message           string
}
func (e *Error) Error() string { return string(e.Class) + ": " + e.Message }

Capabilities is the first call. If Operations[OpImport] is false, the adapter returns ErrUnsupported instead of pretending. That keeps unsupported behavior explicit and testable.

Trace a duplicate create. Caller calls Create with TenantID=tenant-42, IdempotencyKey=order-7, Spec.Kind=queue. Adapter maps to provider POST /resources with header Idempotency-Key: order-7. Provider returns 201, ID r-123, status CREATE_COMPLETE. Adapter normalizes CREATE_COMPLETE to StatusReady and returns CreateResult{Ref: r-123, State: Ready, ProviderRequestID: req-abc}. Caller's context hits a 2s deadline before reading the response. Caller retries with the same key. Adapter sends the same POST. Provider returns 200, same ID r-123. Adapter returns the same result. No second resource. If the adapter had generated a new key, the provider would create r-456 and the platform would have two queues for one order.

Normalize provider signals in one function per adapter:

Provider signalNormalizedRetryableRetryAfter
400 validationErrInvalidfalse0
404ErrNotFoundfalse0
409 duplicateErrConflictfalse0
429ErrRateLimitedtrueRetry-After header
503ErrUnavailabletrueexponential backoff
401/403ErrAuthfalse0
unknown 5xxErrInternaltruebackoff

Hypothetical arithmetic: provider allows 10 rps, burst 20. 50 tenants each create one queue. At 10 rps the queue drains in 50/10 = 5s. If the adapter retries every 429 immediately, each failed call doubles request count; 50 creates become 100 calls, drain time 10s, and the provider's 429 rate rises. With Retry-After: 2s and a 20-worker pool, the adapter sends at most 20 in the first burst, then 10/s, so p99 stays near the provider's 200ms create latency instead of seconds.

Trade-offs. A fat interface forces every adapter to implement Import even when the provider has no import API; the capability map lets it return ErrUnsupported. Choose the capability map when providers differ. Normalized types lose provider-specific fields but keep the platform testable; pass-through SDK types are faster for a single-provider internal tool but leak vendor types into domain code. Platform owns policy; adapter only enforces credential scope. If the adapter owns policy, every provider reimplements RBAC and audit. When not to use this: one provider, one tenant, no retries, then a thin client is enough.

Failure modes. Duplicate create: symptom two resources for one order; detect by Observe returning two IDs or provider 409; cost orphaned resource and manual cleanup. Lost idempotency key: retry creates duplicate; detect audit log missing key; cost data corruption. Cancellation treated as rollback: ctx cancel stops waiting but provider still creates; detect Observe finds resource; cost orphan. Rate limit ignored: 429s and p99 2.1s; detect adapter Health degraded and 429 count; cost tenant throttling. Version conflict: update overwrites; detect ExpectedVersion mismatch; cost lost update.

Health returns status, latency, checkedAt. It does not return provider URLs or credentials. Each adapter gets its own worker pool and circuit breaker: open after 5 consecutive ErrUnavailable, half-open after 30s. Interface version is in Capabilities; canary 1% of tenants on v2 before full rollout. A shared suite runs against every adapter: create→observe→update→delete, duplicate create with same key, timeout at 1s, 429 with Retry-After: 2s, and import of existing resource. Each adapter has an owner in the service catalog.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Represent differences across infrastructure providers.

Answer

Assumptions. The thing being represented is a declarative resource in a multi-provider control plane. I'll use a Terraform module (or OpenTofu) targeting AWS, GCP and Azure; the same shape applies to Crossplane or Cluster API CRDs. The question is what belongs in the shared resource and what stays behind the adapter.

Core answer. Represent only the differences that change an outcome a user can observe: durability, consistency, identity, network reachability, scaling limits, recovery, cost, lifecycle. Everything else is provider detail. One domain resource holds stable intent: size_gib, iops, retention_days, public_access. Each provider gets a typed implementation selected by a variable, never a free-form provider_options map. Provider versions are pinned in .terraform.lock.hcl (Terraform 0.14+). Capability is checked at plan time with precondition/postcondition (1.2+) or check blocks (1.5+), and every adapter runs the same conformance test (terraform test, GA in 1.6).

A provider-options map fails because it can't be validated: an unsupported key either errors at apply or no-ops, and it lets a caller set a value that contradicts the declared guarantee. public_access = false alongside an option that attaches a public bucket policy.

Worked trace. Same input, two volume types:

HCL
variable "volume" {
  type = object({
    size_gib        = number
    iops            = optional(number)   # Terraform 1.3+
    throughput_mbps = optional(number)
  })
}

resource "aws_ebs_volume" "this" {
  availability_zone = var.az_id          # use1-az1, not us-east-1a
  size              = var.volume.size_gib
  type              = "gp3"
  iops              = var.volume.iops
  throughput        = var.volume.throughput_mbps

  lifecycle {
    precondition {
      condition     = var.volume.iops == null || (var.volume.iops >= 3000 && var.volume.iops <= 16000)
      error_message = "gp3 accepts 3000-16000 IOPS; gp2 derives IOPS from size at 3/GiB."
    }
  }
}

Caller passes iops = 1000. On gp3 the API rejects it: the floor is 3,000 IOPS. On gp2 the same number is legal and silently means a ~334 GiB volume's baseline (3 IOPS/GiB). One input, one hard error, one quiet change of meaning. The precondition converts the second case into a plan-time failure.

Differences worth encoding.

differencewhy a shared resource can't ignore it
S3 bucket names are 3–63 chars and globally unique; Azure storage accounts are 3–24 lowercase alphanumerica name derived from a domain name fails on Azure at 24 chars
us-east-1a is a per-account mapping to a physical zone; use1-az1 is the stable ID. GCP zone names are consistent across projectsa module taking an AZ name puts two AWS accounts in different physical zones
S3 Object Lock must be enabled at bucket creation; a GCS retention policy can be set and locked later"immutable bucket" is not one operation, so a migration can't normalize the two
EBS gp3 has a fixed 3,000 IOPS / 125 MiB/s baseline; gp2 scales at 3 IOPS/GiBthe same iops input means different things

Alternatives. Capability discovery at plan time (terraform providers schema -json, check blocks) tells you an attribute exists on the pinned provider version, not whether a value is legal or the guarantee holds. gp3's iops exists and still rejects 1000. Use it to fail fast on missing attributes, not as the portability contract. Typed per-provider variants are right when outcomes genuinely differ, and wrong if you don't run one conformance test across all of them, because they drift. A single lowest-common-denominator resource gives one code path and silently drops the guarantees you can't express: usually the reason the system exists.

Failure modes. Silent guarantee loss from provider drift: the AWS provider deprecated inline S3 bucket settings in v4.0 (Feb 2022) and removed them in v5.0 (Feb 2023). A module pinned ~> 4.0 that set versioning {} inline keeps working; on ~> 5.0 the same config fails to plan, and if someone "fixes" it by deleting the block, it applies cleanly with versioning off. Detect it with a postcondition that reads the bucket's versioning status after apply, or a conformance test asserting it. Blast radius is every bucket the module created; the cost is no recovery from an overwrite or delete. Identity drift is the second: a hardcoded AZ name across two accounts, caught by comparing AZ IDs at plan time.

Migration. moved blocks (1.1+) for renames, import blocks (1.5+) for adoption, terraform state mv for the rest. A cross-provider change that alters residency, immutability or durability needs explicit user confirmation, not a plan diff nobody reads.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Test provider adapter conformance.

Answer

Assume the adapter is a class behind a Provider interface in a control plane, and I can run it against either a fake provider that speaks the provider's HTTP API or a sandbox account. The adapter under test is the only variable; the suite never imports provider-specific code.

What I say first: I test the contract, not the provider. The contract is a state machine with explicit capabilities. Three layers: contract (shape, capabilities, error taxonomy), behavioral (idempotency, concurrency, drift, cancellation), operational (auth, rate limits, credential leak, cleanup). Every case exists to catch a specific production bug, and the harness asserts on side effects, not just status codes.

Mechanism. Idempotency is the highest-value case. The fake commits a create at t=1s but delays the response to t=2s; the client cancels at t=1.5s and retries with the same Idempotency-Key. The assertion is not "retry returns 200" but "the side-effect counter is 1 and both responses carry the same resource id". Without that, a timeout after commit creates twins. Optimistic concurrency: two PUTs with version v1 must yield one 200 and one 409/412, and the final read must show the first writer's value. Drift: the fake mutates the resource out of band, then refresh must report drifted=true and a plan that updates, not a silent no-op. Error mapping: 429 with Retry-After: 1 maps to a typed RateLimited error with retryAfter=1s; 500 maps to Retryable; 400 maps to Permanent; the error message must not contain the provider's raw JSON or stack. Capability discovery: if the adapter declares no import, calling import must return UnsupportedCapability, not panic or pretend success. Credential leak: the recorder captures outbound headers and logs; a regex for "Bearer ", "AKIA[0-9A-Z]{16}" and "-----BEGIN" must return zero hits.

The harness detects these by recording every request/response at the transport boundary and driving a fake provider (a stub server such as WireMock, or the provider's sandbox emulator) with deterministic fault injection: delay, commit-then-timeout, partial success (created but list stale), stale read, 429, and 5xx. A nightly live canary runs one low-risk resource per adapter, tagged with a run id, and asserts cleanup returns the list count to baseline.

Trade-offs. Fake-provider contract tests run on every PR: fast, deterministic, but only as faithful as the fake. Recorded provider fixtures replay real payloads and catch schema changes, but they go stale and a recorded success can hide a new error code. Live canaries catch real auth, real rate limits and real error mapping, but they are slow, flaky and spend quota. I use fake for every commit, recorded for nightly, and live canary as a release gate on one resource per adapter. When not to canary: no sandbox, destructive operations, or a quota so low the canary starves production (e.g., a provider with 100 writes/day where the canary needs 6). Then I rely on contract plus recorded fixtures and certify manually.

Failure modes: a capability that lies (update returns 200 but state never changes). Detect with read-after-write and version check; an idempotency window shorter than the retry window. Replay the key after the provider's stated TTL, which may force adapter-side dedupe; a new provider error code that maps to Unknown, alert if Unknown count > 0; cleanup failure, assert final list count equals baseline.

Artifacts. Worked trace for the timeout case:

  1. t=0 POST /resources, Idempotency-Key: k1.
  2. t=1 provider commits; response held until t=2.
  3. t=1.5 client cancels, returns timeout.
  4. t=2.5 retry with k1.
  5. Provider returns existing id, side-effect count stays 1.
  6. t=3 list returns exactly one resource.

Table (hypothetical numbers for an 8-adapter suite):

CaseInjectionAssertionSignal
Idempotent createdelay 2s, cancel at 1.5ssame id, side effects = 1duplicate count
Optimistic conflicttwo PUTs at v1one 200, one 409, final = firstconflict code
Partial success201 then stale list for 5sretry same key, no twinlist count
Rate limit429, Retry-After: 1typed RateLimited, backoff 1sretry count <= 2
Credential leaknonezero secret regex hitsleak count
Unsupported capabilityimport declared falseUnsupportedCapabilitypanic count = 0

Budget, say 120 contract tests on 4 workers run in 45s wall; a nightly canary of 8 adapters * 30 requests = 240 requests, inside a 600 req/min sandbox quota with 60% headroom. If a provider's quota is 100 req/day, skip the canary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design a governed escape hatch.

Answer

What I'd say in the first minute

Before designing anything I need the system and the pressure. I'll assume a Kubernetes-style control plane: the platform team owns a CRD-based API, teams declare resources, and an admission webhook enforces policy. The pressure is that a team needs a field or behaviour the schema doesn't have, and the platform team won't add it to the core API this quarter. The design question is how to let them proceed without turning the API into an unvalidated free-for-all.

My answer: the escape hatch is a typed, namespaced, versioned extension block with a named owner and an expiry, not arbitrary code, and not provider credentials handed to a team controller.

Mechanism

Every extensible resource gets one reserved field, spec.extensions, a map keyed by a namespaced group like ext.acme.io/v1alpha1. The admission webhook does four things in order:

  1. Rejects any key that isn't a valid DNS-subdomain group plus version.
  2. Caps each extension block at 16 KiB and the whole object at 64 KiB (my proposed limits, not a vendor default) so etcd and every watch payload stay bounded.
  3. Rejects any extension that writes a reserved path: metadata.name, metadata.uid, owner references, and anything the policy engine reads. Extensions are additive only.
  4. Stamps owner, createdAt and expiresAt from the request's annotations.

Why typed data rather than arbitrary code: a webhook or controller running team-supplied code has to be trusted with the API server's credentials and the cluster network. A typed block is data the platform can validate, diff and delete. That is the whole trade.

Deciding criteria

OptionUse whenCost
Typed extension blockThe need is field-shaped, no new behaviourConsumers must tolerate unknown fields
Composable capability (a CRD the platform already supports)New behaviour, but it maps to an existing primitiveNeeds a controller, but the platform owns it
Off-road resource class (separate CRD, team-owned controller)A whole new resource with its own lifecycleTeam owns the controller, its SLO and upgrades
Arbitrary code or provider credentialsAlmost neverPlatform can't validate, audit or revoke it

Refuse the hatch when the real need is to bypass policy. If the extension would change who can read or write the object, that isn't an extension: it's a policy change, and it goes through the normal review.

Failure modes and how I'd detect them

  • Extension sprawl: forty teams each add ext.<team>.io/v1alpha1 and nobody can tell which are live. Detect by counting distinct extension groups per resource type in inventory; alert when it grows past a few per quarter.
  • Silent consumer breakage on upgrade: a consumer reads an extension key and assumes it exists; the owner expires it and the consumer panics. Detect by making expiry two-phase (mark deprecated for 30 days, then reject writes, then strip the key) and emit a warning event to readers of a deprecated key.
  • Size blowup: an extension carries a 2 MiB blob and every watch on that resource ships it. The 16 KiB cap catches this at admission, not at 3 a.m.

Worked trace (hypothetical figures)

A team submits a resource with ext.acme.io/v1alpha1: {retentionDays: 45}. The webhook sees a valid key, 38 bytes under the cap, no reserved path touched, and stamps owner team-payments, expiresAt at +90 days. The object is admitted. An inventory job records the group, owner and expiry. At day 60 the expiry job emits a warning event; at day 90 writes carrying that key are rejected; at day 120 the key is stripped from stored objects. If three teams add the same retentionDays key, that repetition is the signal to pave it into the core schema as a first-class field.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Migrate from a provider-shaped API to a domain API.

Answer

Assume you own both APIs and the state layer, existing clients call the provider-shaped API, and stored state (webhooks, cron jobs, saved queries) references provider IDs. The migration is a strangler: the domain API becomes the only writer to the authoritative domain model, and the provider API becomes a thin adapter over it. Do not build a second store.

Inventory endpoints, fields, clients, automations, stored state, and real resources. Map provider concepts to domain intent. Mark fields that cannot round-trip. Example: provider provider_instance_type: m5.2xlarge maps to domain compute_class: general-purpose; the exact type is lost unless you keep it in provider_metadata. That is a migration decision, not a detail.

Why this works: one binding/state layer prevents dual-write divergence. The adapter translates provider-shaped requests into domain commands. Shadow reads duplicate reads to both APIs, normalize responses, and compare. Mismatches are the backlog. Cohort migration routes by client ID or tenant: 1% -> 10% -> 50% -> 100%. Rollback is a routing flip.

Alternatives: big-bang rewrite only if no stored state and few clients. Dual-write to separate stores is rejected: reconciliation cost and divergence. Provider passthrough with renamed fields fails because provider concepts leak. When not to use: if provider API is already domain-shaped and no stored state, a rename may suffice; if provider is being decommissioned and no consumers, deprecate instead.

Failure modes:

  • Non-round-trippable fields. Detection: shadow read diff counts; alert if mismatch > 0.1% of 10k daily reads. Cost: support tickets, capacity planning errors.
  • Dual-write divergence. Detection: nightly reconciliation job comparing domain object version and provider adapter output; alert on checksum mismatch. Cost: inconsistent state, rollback impossible.
  • Resource identity loss. Detection: AWS CloudTrail shows RunInstances instead of ModifyInstanceAttribute during migration. Cost: downtime, data loss.
  • Stored obligations. Detection: scan for webhook URLs, cron jobs, saved queries containing old IDs. Cost: silent failures after retirement.
  • Cohort without rollback. Detection: error budget burn > 2% in 5 min; canary metrics. Cost: prolonged outage.

Artefacts:

Mapping table:

Provider fieldDomain fieldRound-trip?Notes
provider_instance_idresource_idyesstable identity
provider_instance_typecompute_classnoexact type lost; keep in provider_metadata
provider_regionregionyesmap to domain region
provider_network_idnetwork_idyes
provider_tagslabelspartialreserved keys conflict

Adapter code (Python 3.12):

Python
from dataclasses import dataclass

@dataclass(frozen=True)
class DomainResource:
    resource_id: str
    compute_class: str
    region: str
    provider_metadata: dict

def map_compute_class(instance_type: str) -> str:
    if instance_type.startswith("m5"):
        return "general-purpose"
    if instance_type.startswith("c5"):
        return "compute-optimized"
    return "unknown"

def from_provider(payload: dict) -> DomainResource:
    return DomainResource(
        resource_id=payload["provider_instance_id"],
        compute_class=map_compute_class(payload["provider_instance_type"]),
        region=payload["provider_region"],
        provider_metadata={"instance_type": payload["provider_instance_type"]},
    )

Trace: input {"provider_instance_id": "i-123", "provider_instance_type": "m5.2xlarge", "provider_region": "us-east-1"}. map_compute_class("m5.2xlarge") sees startswith("m5"), returns "general-purpose". Output: DomainResource(resource_id="i-123", compute_class="general-purpose", region="us-east-1", provider_metadata={"instance_type": "m5.2xlarge"}).

Shadow read trace: provider GET /v1/instances/i-123 returns provider_instance_type: m5.2xlarge; domain GET /v1/resources/i-123 returns compute_class: general-purpose. Normalize both to domain shape and compare. If mapping returns unknown, count a mismatch. At 10k reads/day, 10 mismatches is 0.1%; block migration above that.

Cohort arithmetic: 200 clients, 10k calls/day. Start 1% = 2 clients, 100 calls/day. Observe 24h. If error rate < 0.1% and shadow mismatch < 0.1%, move to 10% = 20 clients, 1k calls/day. Then 50%, then 100%. Support window: 90 days dual telemetry. Retire when old API call count = 0 for 30 days and stored obligations = 0.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design rate limiting and backpressure.

Answer

What I'd say first

Assume a multi-tenant HTTP API in front of a shared downstream, say a payments provider with its own quota, an SLO of p99 ≤ 300 ms, and tenants who can be noisy. Two mechanisms, not one: a rate limiter at the edge that bounds arrival rate per tenant, and a concurrency limiter plus bounded queue at each service boundary that bounds in-flight work. A rate limit alone doesn't protect you. If the downstream slows to 2 s, 500 rps becomes 1000 concurrent requests and you fall over anyway. A concurrency limit alone gives no fairness: one tenant can hold every slot. They answer different questions: how fast may you arrive, and how much may be in flight.

Mechanism

Token bucket: the bucket holds B tokens, refills at r tokens/second, and each request costs 1 (or its measured cost). It permits a burst of B while enforcing r over any long window. GCRA is the same policy stored as a single timestamp, the theoretical arrival time, so it's O(1) memory per key with no refill timer:

Python
class GCRA:
    def __init__(self, rate_per_sec, burst):
        self.T = 1.0 / rate_per_sec          # emission interval
        self.tau = (burst - 1) * self.T      # burst tolerance
        self.tat = 0.0                       # theoretical arrival time

    def allow(self, now):
        if now < self.tat - self.tau:
            return False
        self.tat = max(now, self.tat) + self.T
        return True

Trace with r = 10/s, B = 5, so T = 0.1 s and τ = 0.4 s:

t (s)tat beforetat − τdecisiontat after
0.000.00−0.40allow0.10
0.000.10−0.30allow0.20
0.000.20−0.20allow0.30
0.000.30−0.10allow0.40
0.000.400.00allow0.50
0.000.500.10reject0.50
0.050.500.10reject0.50
0.100.500.10allow0.60

Five requests at t=0 pass, the sixth is rejected, and nothing refills until t=0.1. That's the burst-then-sustain shape you want.

Concurrency: Little's Law, L = λW. At 500 rps and a 200 ms service time you need 100 in flight. Set the concurrency limit to 100 and the queue to 50; at a 500 rps drain rate the queue adds at most 100 ms, so worst-case latency is 300 ms and anything older than that is shed rather than served late.

Backpressure propagates by making queue age visible. When the oldest queued item passes the deadline, reject. If you don't, latency grows without bound and you enter a metastable state where the queue stays full after the trigger is gone, because clients keep retrying into it.

Trade-offs

choiceuse whendon't
reject vs queuecaller has a deadline and the result is worthless after it (interactive reads)async jobs whose result still matters in 10 minutes: queue those
edge vs service limiteredge for per-tenant fairness and quota; service for self-protectionedge-only: it can't see downstream saturation. Service-only: every service reimplements tenant identity
token bucket vs concurrency limitboth: bucket bounds arrival, concurrency bounds in-flightbucket alone under a slow downstream; concurrency alone lets one tenant take the pool
fixed window vs GCRAGCRA when boundary bursts matterfixed window is fine for coarse quotas where 2× at the boundary is acceptable

Don't rate limit health checks or the control plane. A limiter that sheds your own probes turns a load problem into an outage. And skip a global limiter if the system is sharded such that tenants can't affect each other: you've added a coordination point and a new failure mode for nothing.

Failure modes

Retry storm: clients retry on 429 without jitter, all land at the same instant after Retry-After, and the queue refills. Detect it by request rate staying high while success rate stays low, and by load not dropping when you remove the trigger. Fix with jittered backoff and a retry budget.

Boundary spike: a fixed-window limiter resets at :00 and every client fires then. A per-second histogram shows the spike at window edges.

Limiter as SPOF: a Redis-backed counter that's down forces a choice. Fail open (overload downstream) or fail closed (outage). Decide per route: fail open for reads, closed for writes.

Unfairness: one tenant with 10k connections starves others while global p99 looks fine. Compare per-tenant p99, not the aggregate.

Instrument queue depth, oldest-item age, per-tenant rejection rate and downstream health. Alert on age, not on depth.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Define platform API SLOs and telemetry.

Answer

What I'd say in the first 90 seconds

Assume a multi-tenant platform API that fronts third-party providers through adapters: it serves synchronous reads and accepts long-running operations (create, cancel, delete). I'd put SLOs on the user-visible contract, not on adapter internals, and pick four SLIs: availability, read latency, operation terminal success, status freshness. Adapter health, queue age and retry counts are telemetry that explains those four; they are not SLOs of their own, because a candidate who pages on adapter health ends up paging for someone else's outage.

The SLOs

SLI (measured at the edge, 30-day rolling)DefinitionTarget
Availabilitynon-5xx ÷ authenticated requests99.9% reads, 99.5% writes
Read latencyp99 server-side300 ms
Operation terminal successaccepted ops reaching terminal success within deadline99% within 24 h
Status freshnessstatus reads with revision age ≤ 5 s99%

99.9% over 30 days is 43 min 12 s of allowed unavailability: that is the error budget, and it is what funds risky deploys. 99.5% on writes is looser on purpose: writes touch providers we don't control.

Telemetry

Three signals, each with a job. Metrics: RED per method class, plus a queue-age histogram, a stale-revision counter and an adapter-health gauge. Traces: one trace per request, W3C traceparent propagated into every adapter call, so a slow operation shows a user_wait span and a separate provider span. That split is the whole point, because it tells you whether to page your team or open a provider ticket. Logs: structured, with an error_reason enum, no payloads.

Dimensions stay bounded: method class, region, tenant tier, adapter name, error reason. Never tenant ID, never request body. Cardinality is the failure mode of telemetry, not volume.

Trade-offs

Measure at the edge and in the service. Edge catches LB and network loss; service isolates your code. Alert on edge, debug with service. On provider latency: fold it into the SLO and you get paged for a provider's bad afternoon; exclude it entirely and you hide real user pain. So the SLO covers total user wait, and a separate dependency dashboard covers the provider-caused portion. And don't put an SLO on a low-volume endpoint: under roughly 1,000 requests per 30 days the signal is noise; use a synthetic probe instead.

Failure modes and how you catch them

  • Stale revisions: status cache TTL drifts past the provider's update cadence. Detect with the freshness SLI plus a synthetic that writes then polls until the revision changes. Cost: users act on old state.
  • Abandoned operations: client disconnects, worker keeps running. Detect with queue-age p99 and an orphan counter. Cost: burned provider quota.
  • Retry storms: alert on the retry ratio, not on individual retries. Per-retry alerts are noise.
  • Adapter degradation: circuit breaker opens; the adapter-health gauge and the provider-span error rate move together.

Synthetics cover the lifecycle paths (create → poll → cancel) that real traffic hits too rarely to alert on.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Handle an API outage without harming workloads.

Answer

Clarify first. "API outage" is two different failures: our own management API is down, or an upstream provider API we call is down. Assume the data plane, the processes actually serving customer traffic, does not call the management API on the request path; it reads desired state from a local cache or mounted config. If that assumption is false, nothing below saves you and the fix is architectural, not operational.

Core answer. Keep the data plane running by keeping the control plane off its request path. Shed or durably queue new control-plane work instead of accepting it invisibly. Restore reads before writes. Reconcile before replay.

Why the data plane survives. In Kubernetes, kubelet runs pods from its own cached spec; the API server being down does not stop containers. The eviction logic lives in the control plane (node lifecycle controller), so while the API server is down no node is marked NotReady and nothing is evicted. The trap is recovery: when the API server returns, the node controller sees stale heartbeats, taints nodes NotReady, and default-not-ready-toleration-seconds (300s) starts counting. You get an eviction wave roughly five minutes after recovery, not during the outage. Detect it by watching node taints and eviction counts in the minutes after the API server comes back, and by the gap between kubelet node-status-update-frequency (10s) and node-monitor-grace-period (40s).

LayerReads desired state fromSurvives API outage?
Data plane (serving traffic)local cache / mounted configyes, if it never calls the API per request
kubelet / agentcached pod specyes; eviction logic is in the control plane
Control plane (controllers)API server + etcdno: this is what is down
New provisioningprovider APIno: reject or queue

Bounding new work. Two options with different costs. Reject with 503 + Retry-After: cheap, truthful, nothing to reconcile, but the client must retry and you lose the request if it does not. Durable queue: survives, but you now own replay, ordering and duplicate suppression. Decide by whether the operation is idempotent and whether the client can retry. For non-idempotent creates, reject unless you have a client token: EC2 RunInstances takes a ClientToken that makes retries idempotent. Kubernetes uses resourceVersion for optimistic concurrency: a stale update returns 409 Conflict, which is the check you want, not last-writer-wins.

Rate-limit recovery. When the API returns, every client retries at once. Kubernetes API Priority and Fairness (FlowSchema / PriorityLevelConfiguration) caps in-flight requests per priority level so leader-election and system traffic is not starved by a retry storm. On the client side, exponential backoff with full jitter; the AWS SDKs' standard retry mode defaults to 3 attempts. Without this, recovery itself becomes the outage.

Fence stale workers. A worker partitioned during the outage can return and act on stale state. Fence it with a monotonic epoch or lease: the worker must present a token newer than the current lease or its writes are rejected. Detect by comparing lease epochs in the audit log.

Reconcile before replay. Before replaying queued operations, walk every in-flight operation and its provider side effect: a RunInstances that succeeded but whose response was lost leaves an orphan instance. Reconcile by listing provider resources and diffing against desired state, then replay only the delta.

Break-glass. A separate, short-lived, audited credential path for critical lifecycle actions, not a shared admin key, invalidated after use.

What changes the decision. If the data plane does call the control plane on the request path, degrade to a read-only cached mode rather than trying to keep writes flowing. If operations are not idempotent and clients cannot retry, queue durably and accept the replay cost.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Govern inner-source platform API providers.

Answer

Core answer, first 90 seconds

Assume the platform team owns a core API, a deployment or service-catalog API, and internal teams want to plug in providers: a new cloud backend, a secrets store, a notification channel. The question is how much of that reaches the core contract.

My answer: the platform owns the contract, contributors own the implementations, and there is a hard gate between experimental and supported.

The platform owns the domain schemas, the auth model, the error taxonomy and the operation semantics. That is the part you cannot let fragment, because every consumer codes against it. Contributors own adapters that implement a versioned provider interface.

The interface is a real artifact, not a wiki page. In Go it looks like this:

Go
// provider/v1, checked against Go 1.22
type Provider interface {
    // Create must be idempotent on (namespace, name).
    Create(ctx context.Context, spec ResourceSpec) (ResourceID, error)
    Delete(ctx context.Context, id ResourceID) error
    // Health is polled every 30s; a non-nil error removes the provider from rotation.
    Health(ctx context.Context) error
}

Then the gate. A provider registers as tier: experimental: it is in the registry, it is not in the supported matrix, it carries no SLA, and it may break on any release. Promotion to supported requires three things: the conformance suite passes, two named maintainers are in CODEOWNERS, and a security review clears the supply chain and the capability claims. The conformance suite is roughly 40 tests run in CI against a fake control plane; it asserts idempotency, error mapping, timeout behavior, and that every outbound call goes through the platform broker.

Why the gate matters: without it the interface drifts. One adapter returns a raw cloud error, another wraps it, and no consumer can write a single retry policy. The conformance suite is what makes the contract real rather than aspirational.

Trade-offs, and when not to do this

The alternative is a plugin model with no gate: anyone ships anything. That is fine for a small, trusted set of providers, say under five, all owned by teams you sit with. It fails at scale because consumers cannot tell a supported provider from a hobby one, and cannot reason about reliability.

The other alternative is absorbing everything into core. Don't. Absorb only when a provider is used by a large share of consumers and the domain is genuinely core; otherwise you have turned the platform team into a bottleneck for every backend.

Failure modes and how you detect them

  1. Adapter bypasses policy: it calls the cloud API directly instead of through the broker, skipping quota and audit. Detect with an egress NetworkPolicy plus an audit-log check: any provider pod with outbound traffic not to the broker is a violation. The conformance test catches it before promotion; the policy catches it after.

  2. Abandoned provider: the maintainer stops responding. Signal: no commits in 90 days and no issue response in 14 days. Action: mark deprecated, announce it, keep it for two release cycles, then remove it with a migration guide. Do not silently absorb it into core.

  3. Contract drift: a provider ships behavior the interface does not describe. Detect by running the conformance suite on every release of every provider, not just at promotion.

What would change my answer

If all providers are owned by one team, drop the tiering and the conformance suite: you are paying governance cost for a coordination problem you do not have. If consumers are external, the gate gets stricter, not looser.

The thresholds above are illustrative defaults; set them from your own incident and usage data.

Curated: · Written: · Reviewed:

Difficulty: Hard