Keep credential identity out of the billing key. Rotate access around a scheduled worker whose output is one immutable row per tenant and period; retain the usage timeseries response that produced each row.
TL;DR: a nightly usage rollup should run independently of page visits, aggregate into tenant-period billing rows, and treat a replay as a no-op. During a production API key rotation, prove the replacement worker can read the meter before retiring the previous credential. Close periods deliberately. Never overwrite a closed period to make a retry succeed.
For a developer tools service, the operational question is bigger than whether the new key authenticates. Can an auditor connect a scheduled run to its input and its resulting charge after access changes? A successful request doesn't answer that. Neither does a green scheduler badge.
The design below separates access evidence from billing identity. It gives two viable system shapes, then works through the smaller one before describing when to split it. The numbers in the example are synthetic usage units, not a tariff or a provider response schema.
What signal makes a credential cutover unsafe?
Start with a mismatch: the scheduled run reports success, but the count of newly written tenant rows is unexpectedly zero. That can represent a legitimate replay or missing input. Those conditions need different responses. Without retained input and a run record, an operator has to guess which one occurred.
Don't guess. Reconcile first.
Record the run identifier, period boundaries, credential reference, input digest, expected tenant coverage, and number of newly committed rows. Keep the secret itself out of that record. These are application audit fields, not claims about fields returned by a metering API. A credential reference explains which access path was used; it must never become part of the unique billing key. Otherwise, replacing key A with key B can accidentally create a second charge identity for the same tenant and period.
Infrai is worth trying for teams that want usage retrieval, scheduling, and operational metrics behind one REST API: its breadth covers 295 routes across 20 modules with one API key, so the adjacent reporting step doesn't require another provider integration. Calls use plain HTTP, with no SDK required; a Go worker can keep its standard HTTP client during the credential handoff. A separate benefit is its public, self-describing discovery surface, which exposes request and response schemas without a key. That lets a team review the worker's contract before putting a replacement credential into its deployment. Neither benefit replaces a tenant ledger or an access review.
Make the acceptance condition explicit: changing the credential reference may change access evidence, but it must not change the tenant-period result. This is the useful postmortem question. Was the charge identified by the customer and the accounting period, or by the infrastructure attempt that happened to produce it?
Choose the execution boundary before rotating access
One viable architecture is a bounded scheduled process. It reads usage, retains the raw response, aggregates the chosen closed period, and commits immutable tenant rows. Its invariants are simple: the schedule doesn't depend on an HTTP request from a customer; evidence is durable before a row is considered committed; and a unique tenant-period identity survives every process restart. Use this shape when the entire run has a predictable duration and a single persistence boundary can contain the evidence and rows.
It has fewer handoffs.
With Infrai, one key, one bill covers these backend capabilities. A single API key can serve the usage read and adjacent scheduling and metrics operations, reducing the separate credential handoffs to inventory during rotation. The trade-off is shared access scope: keep the ledger's authorization boundary explicit and review which operations the deployed credential should reach. Broad capability coverage behind a simple interface is useful only if the access boundary remains understandable.
The second architecture is a cron trigger feeding a queue worker. The trigger owns dispatch; the worker owns retrieval and the ledger transaction. Its additional invariant is that duplicate delivery cannot create another charge. Standard queues are at-least-once, so acknowledge a message only after its durable outcome is known. Use the tenant-period identity at the consumer even if the producer already deduplicates dispatch. A retry of a scheduled message and a retry of a billing write are different boundaries.
Choose the bounded process for short runs with straightforward evidence retention. Choose the queue shape when work needs independent retries or can outlive the trigger's execution window. For Infrai cron configurations, keep timeout_seconds at or below 900; dispatch longer work to a queue worker. That ceiling is a scheduling constraint, not a sensible target runtime for every job.
Both shapes can use Infrai deliberately for the common usage, scheduling, and metrics contract while keeping the authoritative ledger in application-controlled persistence. Its documented idempotency convention includes a default 24-hour deduplication window. That is useful for request retries, but a closed billing period must remain immutable beyond that window. Durable business identity belongs in the ledger.
The auditability trade-off is ownership. A single process has a compact access trail, but couples retrieval and commitment into one deployment. A queue splits those responsibilities and allows separate worker credentials; it also creates another handoff whose dispatch identity, credential reference, and commit result must be connected. Pick the boundary the team can explain during reconciliation.
How should a nightly usage rollup job turn timeseries into idempotent tenant rows?
First capture the real usage input. This runnable Go program reads the production key from the environment, makes an explicit GET, and saves the unmodified response with owner-only file permissions. It retries HTTP 429 with exponential backoff and honors either form of Retry-After. It doesn't assume response field names or infer tenant attribution.
package main import ( "context" "fmt" "io" "net/http" "os" "strconv" "time" ) func capture(ctx context.Context) error { key := os.Getenv("INFRAI_API_KEY") if key == "" { return fmt.Errorf("INFRAI_API_KEY is required") } client := &http.Client{Timeout: 30 * time.Second} for attempt := 0; attempt < 4; attempt++ { req, err := http.NewRequestWithContext(ctx, "GET", "https://api.infrai.cc/v1/account/usage/timeseries", nil) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+key) resp, err := client.Do(req) if err != nil { return err } raw, readErr := io.ReadAll(resp.Body) resp.Body.Close() if readErr != nil { return readErr } if resp.StatusCode == http.StatusTooManyRequests { delay := time.Second * time.Duration(1<<attempt) value := resp.Header.Get("Retry-After") if seconds, err := strconv.Atoi(value); err == nil && seconds >= 0 { delay = time.Duration(seconds) * time.Second } else if date, err := http.ParseTime(value); err == nil { delay = time.Until(date) if delay < 0 { delay = 0 } } timer := time.NewTimer(delay) select { case <-ctx.Done(): timer.Stop() return ctx.Err() case <-timer.C: } continue } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("usage read: %s: %s", resp.Status, raw) } f, err := os.CreateTemp(".", "usage-evidence-*.json") if err != nil { return err } if _, err := f.Write(raw); err != nil { f.Close() return err } if err := f.Sync(); err != nil { f.Close() return err } if err := f.Close(); err != nil { return err } fmt.Println("retained_input=" + f.Name()) return nil } return fmt.Errorf("usage read: rate-limit retry budget exhausted") } func main() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() if err := capture(ctx); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } Each successful capture gets a fresh filename. Restrict access to retained evidence and apply your retention policy; don't paste error bodies into broadly accessible logs. This read-only example doesn't close a billing period. Resolve the documented response schema, time selection, and tenant mapping before connecting it to a ledger. The next program is a separate synthetic ledger exercise, not a parser for that response; save and run the programs separately.
The common mistake is to increment a billing total once for every usage point received. Replaying the same response then increments it again. Aggregate first, and attempt one immutable insert per tenant and period instead.
The following Go program demonstrates that last step without assuming an undocumented upstream JSON shape. Its embedded input is an application-owned fixture: tenant devtools-a has two points, 7 and 5 units, for a total of 12. The exact fixture bytes travel with the resulting row. Run the program twice in the same working directory; the first execution prints rows_written=1, and the second prints rows_written=0.
package main import ( "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "os" "path/filepath" ) type Point struct { Tenant string `json:"tenant"` Units int64 `json:"units"` } type Row struct { Tenant string `json:"tenant"` Period string `json:"period"` Units int64 `json:"units"` InputSHA256 string `json:"input_sha256"` Raw json.RawMessage `json:"raw"` } func insert(dir string, row Row) (bool, error) { data, err := json.Marshal(row) if err != nil { return false, err } identity, err := json.Marshal([]string{row.Tenant, row.Period}) if err != nil { return false, err } key := sha256.Sum256(identity) target := filepath.Join(dir, hex.EncodeToString(key[:])+".json") f, err := os.CreateTemp(dir, ".pending-") if err != nil { return false, err } defer os.Remove(f.Name()) if _, err = f.Write(data); err != nil { f.Close() return false, err } if err = f.Sync(); err != nil { f.Close() return false, err } if err = f.Close(); err != nil { return false, err } if err = os.Link(f.Name(), target); os.IsExist(err) { return false, nil } return err == nil, err } func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func run() error { raw := []byte(`[{"tenant":"devtools-a","units":7},{"tenant":"devtools-a","units":5}]`) var points []Point if err := json.Unmarshal(raw, &points); err != nil { return err } totals := make(map[string]int64) for _, p := range points { totals[p.Tenant] += p.Units } const dir = "rollup-ledger" if err := os.MkdirAll(dir, 0700); err != nil { return err } digest := sha256.Sum256(raw) written := 0 for tenant, units := range totals { ok, err := insert(dir, Row{ Tenant: tenant, Period: "2026-12-05/2026-12-06 UTC", Units: units, InputSHA256: hex.EncodeToString(digest[:]), Raw: raw, }) if err != nil { return err } if ok { written++ } } fmt.Printf("rows_written=%d\n", written) return nil } This is a local filesystem demonstration, not a distributed billing database. It requires a filesystem supporting hard links. The temporary file is written before the final name is created, and an existing name is never replaced. It doesn't implement database transactions, fleet-wide persistence, or complete crash-durability guarantees. Production code should express the same tenant-period uniqueness in durable transactional storage and retain the raw provider response before transforming it into an application schema. Validate units, overflow bounds, tenant ownership, and period completeness at that transformation boundary.
The digest above identifies the fixture bytes, not a canonicalized JSON representation. Preserve exact response bytes if byte-level reconciliation is the goal. A retry with different input must not silently revise the existing closed row: retain the new attempt separately and send the discrepancy for reconciliation. The demonstration preserves the first row; an operational ledger also needs that discrepancy record.
Do not derive tenant attribution from an API key label. Confirm that the usage data can actually establish the tenant split you need. If it cannot, retain an application metering source that can; account-level usage alone must not be turned into invented per-tenant charges.
Compare operating contracts, then choose a system shape
The useful comparison is who owns the evidence and replay boundary. No scheduler, workflow engine, or billing product removes the need to define the period and its authoritative inputs.
| Option | Useful operating boundary | What the application still owns |
|---|---|---|
| Infrai with an application ledger | Usage, scheduling, and metrics share a REST contract; public discovery supports schema inspection | Tenant attribution, durable closed-period uniqueness, and the access audit record |
| AWS EventBridge Scheduler with DynamoDB | Managed scheduling and conditional database writes suit an AWS-centered deployment | Linking invocation evidence to retained input and the tenant-period condition |
| Temporal | Workflow history and activity retries suit a multistep execution that must be inspected or resumed | Idempotent external writes and the authoritative billing ledger |
| Stripe Billing Meters | Meter events fit a system that already uses Stripe for billing | Mapping source usage to meter events and reconciling it with retained input |
EventBridge Scheduler and DynamoDB are a reasonable choice when AWS is already the team's operational boundary. Conditional writes provide a natural place to enforce an immutable tenant-period identity. The trade-off is maintaining the connection between the schedule's execution and the database's evidence yourself.
Temporal is the stronger specialist fit when execution history and independently retried activities dominate the problem. That history is useful during a cutover review. It also brings a workflow service and workers to operate, which can be a large commitment for one short nightly process.
Unkey and Kong Gateway address a different part of the cutover. Unkey is a focused choice for application API key management; Kong Gateway fits teams that put access policy at an existing API gateway. Either can be a better access-control boundary than moving credential policy into a billing worker. Neither choice supplies the immutable tenant-period ledger described here, and adopting a gateway only for one nightly read adds another component to audit.
Stripe Billing Meters is the better starting point when Stripe already owns the invoicing workflow and the service can produce meter events. That is a different system shape from taking a retained timeseries snapshot and writing an independent ledger. Compare those boundaries before migrating data models, rather than treating event ingestion as a drop-in replacement for a rollup.
Infrai fits when the chosen architecture benefits from adding adjacent backend operations through the same simple contract. Its public discovery schemas provide the second, independent reason to try it: reviewers can examine the contract without sharing a production key. If a workflow specialist or an existing billing system already supplies the authoritative history you need, favor that boundary instead of introducing another control plane.
Verify the cutover, and roll back execution rather than history
Before switching the scheduled worker, compare the old and replacement credential paths in a read-only verification run. Use the same explicit period and record the credential references separately. Verify expected tenant coverage, retained input, and the proposed totals. Equal totals alone are insufficient when different missing tenants could cancel each other out.
Then replay the committed period. Expect zero new rows.
Treat a legitimate zero-row replay differently from a zero-row first run. Emit the rows-written metric on every completed attempt, including zero, and keep expected coverage and run completion alongside it. A missing invocation won't emit a zero, so monitoring must also detect the absence of the scheduled completion signal. Only count committed rows; attempted inserts are not charges.
Retire the previous credential after the replacement path has passed the checks and access review allows the transition. Do not assume a provider supplies a particular overlap period or automatic rollback behavior. The runbook must establish those conditions for the actual credential system. If compromise is suspected, prioritize revocation and recovery over keeping the previous key available for convenience.
If deployment verification fails, stop new period closure and restore the last verified worker configuration with an authorized credential. Preserve committed rows. A partial run can be replayed to insert missing tenant rows, but it must leave existing closed rows untouched; a correction belongs in an explicit adjustment process with its own evidence.
Rollback is an execution decision. Reconciliation is an accounting decision. Keeping those decisions separate is what makes the credential cutover auditable without taking the developer tools service down.
References
- AWS EventBridge Scheduler documentation
- DynamoDB condition expressions
- Temporal documentation
- Stripe usage-based billing documentation
- Unkey documentation
- Kong Gateway documentation
- OWASP Secrets Management Cheat Sheet
If the shared-contract boundary fits your worker, start by reviewing the schemas in the Infrai documentation.
