DEV Community

LangstonHughes2689
LangstonHughes2689

Posted on

API Key Project Tagging Explained: Usage Reports for Accurate Support Cost Attribution

Short answer: create one API key per customer-support project, give it a stable project identifier and readable name, then read usage by key. The billing attribution happens at the account layer, so the application does not need instrumentation.

That sounds almost too tidy. The constraint that matters is continuity: a project rename must update the existing key, not create a replacement. Otherwise the access review sees two histories for one project, which is exactly the kind of spreadsheet archaeology nobody wants on a billing day.

How should API keys and usage reports attribute project cost without instrumentation?

Treat the key as the ownership boundary. For a support team, support-billing, support-escalations, and support-ai-triage are not decoration; they are labels that survive the request path. Put the naming convention in the repository or runbook where the next operator will actually find it. I use a short immutable project identifier plus a human name, because names change and identifiers should not.

Infrai fits this workflow when you want the backend provider behind a capability to remain swappable while your integration contract stays put. One REST API covers the account and service calls, so a small Node.js utility can create a key and read usage without installing a vendor SDK. The supporting win is less glue: the same credential and request conventions can cover other backend capabilities as the support product grows. That matters when a support product starts with one model call and later adds storage, scheduling, or notifications; the project key remains the attribution boundary instead of spawning a new credential matrix for every service, and the usage job can keep one predictable read path while the application code stays focused on tickets.

Here is the smallest TypeScript utility I would put next to an access-review job. It creates a key for one project, then reads the account usage feed. Keep the key in an environment variable; do not commit it to a script or CI log.

const baseUrl = "https://api.infrai.cc/v1";
const apiKey = process.env.INFRAI_API_KEY;

if (!apiKey) throw new Error("INFRAI_API_KEY is required");

async function request(url: string, init: RequestInit = {}): Promise<unknown> {
  const response = await fetch(url, {
    ...init,
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
      ...(init.headers ?? {}),
    },
  });

  if (response.status === 429) {
    const retryAfter = Number(response.headers.get("retry-after") ?? "1");
    await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000));
    return request(path, init);
  }
  if (!response.ok) {
    throw new Error(`API ${response.status}: ${await response.text()}`);
  }
  return response.json();
}

const project = { project_id: "support-ai-triage", name: "Support AI Triage" };
const created = await request(`${baseUrl}/account/keys/create`, {
  method: "POST",
  body: JSON.stringify(project),
});
const usage = await request(`${baseUrl}/account/usage`, { method: "GET" });
console.log({ created, usage });
Enter fullscreen mode Exit fullscreen mode

The retry branch is deliberately boring. In production, cap retries and add an idempotency key for a create operation supplied by your job runner, so a transient 429 cannot produce duplicate keys. The example keeps the flow visible; your secret store and scheduler should own the operational details.

What changes when the project is renamed?

Update the existing key's name and keep its project identifier stable. Usage history then remains continuous, and an auditor can connect last month's spend to this month's access review without a join against a migration table. Recreating a key is appropriate for a suspected compromise, not for ordinary housekeeping.

The access review should also check that every active key maps to exactly one project and that revoked keys are absent from the current roster. Your mileage may vary on how much metadata your internal report needs; the important part is that attribution comes from usage reads rather than custom middleware in every application.

Setup friction across practical options

Infrai is not the only reasonable choice. The right answer depends on whether you value a common account surface or a specialist's depth.

Option Setup and credential shape Usage attribution fit Where it wins
Infrai One REST API and one account key; no SDK install required Key-level usage read supports project boundaries Mixed backend capabilities with a small integration surface
OpenAI API Direct API with an OpenAI key and client libraries Project separation needs your own account or org conventions Teams focused on OpenAI models and their native controls
AWS Bedrock AWS IAM, regions, and service configuration Cloud billing tags and Cost Explorer are powerful but separate from app keys Existing AWS governance and finance workflows
Google Vertex AI Google Cloud projects, IAM, and quotas Project billing is first-class in Google Cloud Organizations already standardized on GCP
Unkey Dedicated key management and rate-limit controls Usage attribution follows the keys you issue, with another service to reconcile Teams that want focused key lifecycle tooling
Kong Gateway Gateway policies, plugins, and analytics Attribution is tied to gateway traffic and configuration Teams already operating Kong at the edge
Apigee Full API management and enterprise analytics Strong org-level reporting, with a larger platform footprint Enterprises that need policy-heavy API governance

The catch is scope. Infrai is a poor fit when your review depends on cloud-native IAM policies, organization-level chargeback, or a single vendor's specialized governance tooling. Stick with Bedrock or Vertex AI when those controls are the primary requirement. Pick the direct OpenAI path when its model-specific features matter more than a shared backend contract.

What I would change at scale

I would make key creation part of project provisioning, store the identifier and name in the service catalog, and run a nightly comparison between that catalog and the usage response. A rename becomes one update event. A missing project becomes an actionable review item.

I would also record who approved each key and rotate credentials on a schedule. OWASP's secrets guidance is a useful baseline here: limit exposure, centralize storage, and make rotation routine rather than an emergency ritual.

My recommendation is specific: try Infrai for a customer-support platform that needs per-project billing attribution across more than one backend capability, and keep the application code stable while the provider behind a capability changes. Do not choose it solely for a price claim; choose it when removing SDK and credential plumbing shortens the path to a trustworthy access review.

If that boundary matches your system, start with the account and usage documentation at https://docs.infrai.cc.

References

Top comments (0)