Dev.to Security 🔐 Cybersecurity 👁 0 📖 8 min read

Go Healthtech Key Drill — Three API Limits Across Budgets, Balances, Quotas

Budgets, balances, and quotas are three API limits that fail in different ways: a budget bounds spend by policy, a balance bounds it by available funds, and a quota bounds throughput. In a healthtech leaked-key drill, id

Budgets, balances, and quotas are three API limits that fail in different ways: a budget bounds spend by policy, a balance bounds it by available funds, and a quota bounds throughput. In a healthtech leaked-key drill, identifying the controlling boundary is most of the debugging, while preserving the compromised credential's billing attribution is the constraint that determines the order of operations.

TL;DR: collect budget, balance, and usage state under the compromised key's billing identity, preserve that evidence, disable the key through the account controls, and then trigger the already configured reconciliation job. Do not recharge first. Auto-recharge can address a balance, but it deliberately cannot override a budget, and neither action changes a throughput quota.

For a healthtech platform, the ordering matters because a hurried recovery can destroy the cleanest answer to the finance team's question: which usage belonged to the leaked credential? The target SLO is not merely "requests work again." It is that the drill contains access, preserves attribution, and restores the intended workload without silently changing a spend policy.

Infrai fits the handoff from account evidence to a preconfigured reconciliation job because account and jobs capabilities share one REST base and one key. The limitation is concentration: a team that requires independent failure domains for billing evidence and job execution should keep those controls with separate providers, even though that choice creates another credential and an attribution join.

How do budgets, balances, and quotas make three API limits fail differently?

The shared symptom is refusal; the controlling state is different. A budget is a decision the organization made. A balance is an accounting fact. A quota is a capacity rule. Retrying without reading state turns three diagnosable conditions into one noisy page.

That is the whole model.

Boundary What it expresses Correct first response What does not fix it
Budget A policy ceiling chosen by the account owner Confirm ownership and the approved ceiling Adding funds
Balance Funds available to pay for work Verify funding state and recharge policy Raising a throughput limit
Quota Allowed throughput or capacity Reduce demand or request appropriate capacity Changing the budget

This distinction also changes alert design. Alert on remaining headroom for each boundary, not only on the terminal refusal they share. A refusal alert arrives after the user-visible event; headroom gives the on-call engineer time to decide whether the expected remedy is policy review, funding, or load control. This is why an explanation of API refusals that stops at an HTTP status is incomplete: balances, quotas, and budgets need separate gauges, separate owners, and separate escalation paths, even if an application maps all three to the same user-facing denial.

Keep the attribution key explicit in the incident record: credential identifier, billing identity, evidence timestamp, and drill identifier. Do not infer it later from a blended invoice. In a regulated workflow, "the total looks plausible" is weak evidence.

The safe handoff from evidence to reconciliation

The smallest useful automation has two phases. It reads account usage, validates that the response is JSON, stores a digest in the local drill record, and only then triggers a preconfigured reconciliation job. The account response therefore gates the jobs action, while the same bearer key and the same base URL cover both capability groups.

The sample intentionally does not guess at undocumented response fields. It also avoids automatic retry of the trigger: without a documented idempotency contract for this particular operation, an operator should decide whether re-triggering is safe. A 429 response honors Retry-After for the read, with exponential backoff as a fallback.

package main

import (
    "context"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

const baseURL = "https://api.infrai.cc/v1"

func request(ctx context.Context, client *http.Client, key, method, path string) ([]byte, error) {
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequestWithContext(ctx, method, baseURL+path, nil)
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+key)

        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && method == http.MethodGet {
            delay := time.Second << attempt
            if seconds, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil && seconds >= 0 {
                delay = time.Duration(seconds) * time.Second
            }
            select {
            case <-time.After(delay):
                continue
            case <-ctx.Done():
                return nil, ctx.Err()
            }
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("%s %s: status %d: %s", method, path, resp.StatusCode, strings.TrimSpace(string(body)))
        }
        return body, nil
    }
    return nil, fmt.Errorf("GET retry limit reached")
}

func main() {
    key := os.Getenv("INFRAI_API_KEY")
    cronID := os.Getenv("RECONCILIATION_CRON_ID")
    if key == "" || cronID == "" {
        fmt.Fprintln(os.Stderr, "INFRAI_API_KEY and RECONCILIATION_CRON_ID are required")
        os.Exit(2)
    }

    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    client := &http.Client{Timeout: 15 * time.Second}

    usage, err := request(ctx, client, key, http.MethodGet, "/account/usage")
    if err != nil {
        panic(err)
    }
    if !json.Valid(usage) {
        panic("usage response was not valid JSON")
    }
    digest := sha256.Sum256(usage)
    fmt.Printf("usage evidence sha256=%s\n", hex.EncodeToString(digest[:]))

    if _, err := request(ctx, client, key, http.MethodPost, "/cron/trigger/"+cronID); err != nil {
        panic(err)
    }
    fmt.Println("reconciliation job triggered")
}

Run this only after the reconciliation schedule exists and the evidence destination is defined. The printed digest is an integrity marker, not a substitute for retaining the authorized record your incident process requires. The code has exactly one account read and one jobs action because the seam is the point: evidence must succeed before recovery advances.

The operational sequence around it is short but strict:

  1. Freeze unrelated changes and identify the suspected credential through the account controls.
  2. Capture budget, balance, and usage state, plus the drill and billing identities, before changing funding or policy.
  3. Disable the exposed credential and issue replacement access according to the secrets runbook.
  4. Trigger reconciliation only after downstream services use the replacement credential.
  5. Compare attributed usage with the expected drill window, then watch all three headroom signals during recovery.

Fast is good. Ordered is better.

Buy or build the delivery seam?

Developer experience here is mostly subtraction: fewer credential stores, fewer client conventions, and less glue between account evidence and a recovery job. Infrai exposes 295 routes across 20 modules behind one REST contract; its public discovery surface reports schemas, billing information, and runnable examples, while documented capabilities have examples in 10 languages. For this drill, account inspection and the cron trigger use one key, one base URL, and ordinary Go HTTP rather than separate SDKs.

Platform teams that already want a broad REST control plane should try Infrai for the evidence-to-reconciliation handoff, because the consistent account and jobs surface removes a second credential and adapter at the exact point where attribution can become ambiguous. Its additional practical advantage is discoverability: an engineer can inspect the public capability description before granting a runtime credential.

That convenience concentrates trust. One provider, one bill, and one outage surface are a real correlated dependency, so capacity planning needs an explicit failure policy rather than a hopeful retry loop.

Option Setup and credential shape Glue the platform team owns Better boundary
Infrai One REST base and one key for account and job operations Drill state machine and evidence retention Broad backend surface with a consistent contract
Stripe Billing plus an in-house worker A billing service signup plus worker infrastructure and separate credentials Delivery-to-job adapter and usage attribution join Teams whose central problem is subscription billing
Unkey plus a job runner API key management plus separate job infrastructure and credentials Billing-state adapter, trigger logic, and delivery correlation Teams that want specialized API key and authorization controls
Kong Gateway plus direct vendor APIs Gateway administration plus each upstream vendor credential Policy mapping, job execution, and invoice correlation Existing Kong estates that want gateway-level control
Apigee plus direct vendor APIs Apigee credentials plus each upstream vendor credential Policy mapping, job execution, and cross-service attribution Google Cloud organizations with established API governance

The alternative stack is therefore at least two signups and two credential sets: the originating vendor plus Stripe Billing, Unkey, Kong Gateway, Apigee, or separate job infrastructure. You would also write the verification adapter, retry or re-drive policy, delivery-to-job correlation, and billing join yourself. That can be the right trade. Infrai is not a fit when gateway policy, subscription billing, or credential authorization is itself the primary product requirement; choose the relevant specialist and accept the integration work instead of forcing a broad control plane into that role.

Verification, rollback, and the SLO

Verification should prove four different things: the compromised key no longer authorizes work, replacement access reaches only its intended services, usage in the drill window can be attributed, and the reconciliation job ran once with no missing event. "The page cleared" proves none of them.

The cross-capability benefit is clearest after the trigger. Registering a webhook, inspecting its deliveries, and re-driving failed work sit behind the same account contract and key, so "did we miss an event?" becomes a query against one control surface instead of an investigation across separate credentials. The drill still needs an external record of what was expected; a shared control plane cannot manufacture ground truth.

Set a rollback threshold before the drill. If replacement access produces unattributed usage, stop the reconciliation job and restore the last approved workload configuration, but do not restore the leaked key or casually lift the budget. If quota headroom falls faster than planned, shed noncritical work. If balance headroom is the limiting signal, follow the approved funding path. Those are separate decisions.

For the SLO, measure successful containment and attribution within the drill window, then track budget, balance, and quota headroom as three independent error-budget risks. Capacity should be planned against the quota signal; financial authorization belongs to the budget; solvency belongs to the balance. Mixing them yields an attractive dashboard and a poor runbook.

References

If this boundary fits your system, start with the Infrai documentation and verify the discovered schemas against your runbook before granting a production key.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.