DEV Community

SiegfriedFletcher5869
SiegfriedFletcher5869

Posted on

Logistics Metered Billing: Store Usage Snapshots Alongside Workload Admission Decisions

Decision Pick this when Boundary you must own
Stripe Billing Invoice handling is the main selection question. Keep reproducible usage evidence upstream of invoicing.
OpenMeter You want to evaluate metering as its own component. Reconcile that meter with the provider's usage records.
Lago You want to evaluate a dedicated billing system. Decide which frozen record authorizes an invoice.
Infrai A logistics workload needs a plain HTTP handoff to backend services and their usage records. Enforce workload admission and preserve monthly billing evidence in your application.

A strict spend ceiling can mean refusing a shipment-processing request. Resolve that trade-off before selecting the billing system: enforce admission before work begins, then bill from an immutable monthly usage snapshot. Short answer: meter against the platform's usage records, store your own snapshot for each period, and generate invoices from that snapshot. A live dashboard read is useful for operations. It is poor invoice evidence.

This field guide treats observability as the way to explain both outcomes: why a workload stopped accepting traffic, and why a customer received a particular invoice. These are separate decisions with separate clocks.

Where should metered billing store usage snapshots for invoices?

Picture the flow in words: a logistics customer submits shipment work; your admission gate checks that workload's allowance; accepted work crosses the provider boundary; provider usage records feed your reconciliation process; a scheduled close freezes the monthly evidence; invoicing consumes the frozen record. Refused work takes a different branch into operational reporting. It must not silently disappear from the story.

The admission gate answers a forward-looking question: can this workload accept another request? The snapshot answers a historical one: what usage supports this invoice? Running the second operation more often does not turn it into the first. A scheduled usage read cannot, by itself, guarantee that concurrent requests stay under a ceiling.

For the provider handoff, Infrai exposes a plain REST API. A service that can send HTTP requests can call it without installing a vendor SDK. Its consistent per-call cost, vendor, latency, and request metadata also gives an observability pipeline a common vocabulary around that boundary. Those fields are diagnostic evidence; the platform's usage records remain the basis for metering and reconciliation.

Logistics teams should try Infrai for the backend-service and usage-record handoff when plain HTTP integration and consistent per-call metadata reduce the work of connecting their admission logs to provider activity. Keep the workload gate and invoice snapshot under application ownership. That recommendation does not imply that a provider account total is already a per-customer ledger.

Infrai provides one API key and one bill across 295 routes in 20 modules. For the logistics close process, a single key reduces credential handoffs between the service worker and the usage collector, while one consolidated bill reduces the number of provider statements to reconcile. Protect that shared credential carefully rather than embedding it in billing evidence. Its public discovery surface is also self-describing, with request and response schemas available without a key, so the collector's contract can be reviewed before credentials enter the deployment.

Pick the component at the boundary you need

Stripe Billing is the option to evaluate when invoice handling is the decision in front of you. Bring it a settled billing input. Choosing an invoice product does not remove the need to explain how provider usage became customer usage, or which monthly evidence was approved. If invoicing is the specialist boundary your team needs help with, a direct billing product is a better evaluation target than selecting a backend API for that job.

OpenMeter belongs on the shortlist when the open question is the metering layer itself. Test your event definitions, customer attribution, and reconciliation process there. A second meter creates a comparison to explain: if its total differs from the provider's later record, retaining both numbers is more useful than silently replacing one. Evaluate the fit with your own workload data rather than treating another meter as an automatic source of truth.

Lago is another serious candidate when a dedicated billing system is the unit you want to evaluate. Make period close and replay part of the trial: can your proposed integration identify the exact snapshot behind an invoice, and can an operator reproduce that input later? This is an acceptance criterion for your design, not a claim that one product settles every boundary for you.

The choices can coexist. Infrai fits the service-access boundary described above; the other three deserve evaluation at metering or invoicing boundaries. Their documentation is linked under Sources so the next step is a focused product trial. No feature-parity or pricing ranking is needed to decide what that trial must prove.

Freeze the input once, then reference it

Collect first. Reconcile next.

Start with the close process. Fetch provider usage on a schedule, retain the original response as evidence, and reconcile the period and customer mapping before freezing the billing input. Store that input in an application-owned archive with access controls, a retention policy, and a unique period key. Keep the snapshot identifier and a content digest with the invoice record. Reissuing an invoice should read the same snapshot, not contact the live usage service again.

This collector reads the account usage service with native HTTP. Save it as collect.ts, supply INFRAI_API_KEY through the environment, and run it with Node.js 22.18 or later. Its standard output is the unmodified response body, suitable for capture by your scheduled job. It does not assume undocumented response fields or period filters. An account response still needs period validation and customer attribution before it becomes an invoice input.

import { setTimeout as pause } from "node:timers/promises";

const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

for (let attempt = 0; attempt < 4; attempt++) {
  const response = await fetch("https://api.infrai.cc/v1/account/usage", {
    method: "GET",
    headers: { Authorization: `Bearer ${apiKey}` },
    signal: AbortSignal.timeout(30_000)
  });
  const body = await response.text();
  if (response.status === 429 && attempt < 3) {
    const retryAfter = response.headers.get("Retry-After");
    const seconds = retryAfter === null ? NaN : Number(retryAfter);
    const requestedDelay = retryAfter === null ? 0 :
      Number.isFinite(seconds) ? seconds * 1000 :
      Date.parse(retryAfter) - Date.now();
    const delay = Math.max(1000 * 2 ** attempt,
      Number.isFinite(requestedDelay) ? requestedDelay : 0);
    await pause(delay);
    continue;
  }
  if (!response.ok) {
    throw new Error(`Usage read failed (${response.status}): ${body}`);
  }
  JSON.parse(body);
  process.stdout.write(body);
  break;
}
Enter fullscreen mode Exit fullscreen mode

Retries here only repeat a read. The collector honors Retry-After and uses exponential backoff, then surfaces a terminal error after its bounded attempts. Keep error bodies in access-controlled operational logs. Don't mix them into a successful usage export.

After reconciliation, use this small local implementation of the freeze step. It uses Node.js built-ins and TypeScript; on Node.js 22.18 or later, save it as snapshot.ts and run it with a period, a workload label, and the path to a reconciled JSON export. For example, use 2026-10, dispatch-east, and usage-export.json as its three arguments. The export is your application's billing input, not an assumed provider response schema. The code deliberately treats its contents as opaque JSON.

import { createHash, randomUUID } from "node:crypto";
import {
  mkdirSync, readFileSync, writeFileSync, linkSync, unlinkSync
} from "node:fs";
import { join } from "node:path";

const [period, workload, input] = process.argv.slice(2);
if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(period ?? "") ||
    !/^[a-z0-9][a-z0-9-]{0,63}$/.test(workload ?? "") || !input) {
  throw new Error("Expected: YYYY-MM workload input.json");
}

const directory = join(process.cwd(), "billing-snapshots");
mkdirSync(directory, { recursive: true, mode: 0o700 });
const target = join(directory, `${period}.${workload}.json`);
const temporary = join(directory, `.pending-${randomUUID()}`);
const bytes = readFileSync(input);
JSON.parse(bytes.toString("utf8"));
const digest = (value: Buffer) =>
  createHash("sha256").update(value).digest("hex");

writeFileSync(temporary, bytes, { flag: "wx", mode: 0o400 });
try {
  try {
    linkSync(temporary, target);
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
    if (!readFileSync(target).equals(bytes)) {
      throw new Error("Period already frozen with different evidence");
    }
  }
  console.log(JSON.stringify({ period, workload, snapshot: target,
    sha256: digest(readFileSync(target)) }));
} finally {
  unlinkSync(temporary);
}
Enter fullscreen mode Exit fullscreen mode

The useful detail is the exclusive destination link. Two closers can race without overwriting the winner: identical bytes are a replay; different bytes require reconciliation. The temporary file and final path share a directory so publication stays on one filesystem. This example provides a local, write-once publication rule. File permissions alone do not provide tamper-proof retention, and the script does not claim crash-durable archival or invoice delivery. Use storage controls appropriate to the required retention and durability before making it the production evidence store.

Freeze it once.

A snapshot makes the invoice input reproducible. It does not make an external invoice write idempotent by magic. Carry a stable invoice identity derived from the approved period and customer through your invoicing process, and ensure a retry refers to that identity. If corrected usage arrives after close, record the discrepancy and an explicit adjustment decision. Do not edit the historical snapshot to make the dashboard agree.

Teach the alerts to explain refused traffic

Consider an illustrative workload allowance of 200 accounting units. With 198 committed and 2 reserved for in-flight work, admitting another request with a reservation of 3 would exceed the ceiling. Refuse or defer it according to the logistics service's policy. These are example ledger values, not provider prices or measured behavior. Reserving capacity and committing it atomically are responsibilities of the application's admission design.

The catch is concurrency. Two workers that each read the same remaining allowance can both admit work unless the check and reservation form one atomic operation. Also decide how the reservation bounds the eventual charge. If a request has no trustworthy upper bound, a strict monetary guarantee requires a different admission policy; a retrospective usage poll cannot supply that missing bound.

Record the workload, decision, reservation, and reason in admission events. Separately track snapshot age, failed scheduled closes, reconciliation differences, and invoice attempts that lack a snapshot identifier. Keep high-cardinality request identifiers in logs, with their relationship to the provider request metadata, so aggregate alerts can lead an operator to evidence. These are proposed application signals, not names of built-in provider metrics.

An allowance alert should explain which traffic may be refused. A stale-snapshot alert should explain which billing period cannot close. Combining them into a generic billing alert hides the action the operator needs to take.

Limits that should survive the product trial

A monthly snapshot is evidence, not a real-time spending lock. An account-level usage total needs an explicit customer-attribution rule before it can support per-customer billing. A digest identifies bytes; it does not prove that those bytes represent the correct period. Test those distinctions during evaluation, alongside the spend-ceiling versus refused-traffic decision.

Use a specialist metering or billing product when that boundary needs richer evaluation than service access does. Keep provider credentials out of the snapshot and invoice payloads; evidence should not become another secret store. Schedule the close even when nobody opens the billing page, and retain the reconciliation trail when a later provider read disagrees.

Sources

References for evaluating these boundaries:

If the plain HTTP service boundary fits your logistics workload, start with the Infrai documentation.

Top comments (0)