Skip to content

Find a component

Loading the directory…

↑ ↓ to select · Enter to open · Esc to closeBrowse all →
Contributor login

Metering

Metered usage records — idempotent usage events rolled up per billing period, as a Bijection component

Bijection source
git clone https://github.com/bijectionhq/metering.git
cd metering
git checkout cd6bd628943344281d9e38e2aedd0f6aad0585c6

Bijection repository access is required. Request access.

Description

Metered usage records — idempotent usage events rolled up per billing period, as a Bijection component

Explore the package README for API concepts, configuration, and examples. Check the Bijection source for adaptation-specific setup.

Available to evaluate

Review the source and its dependencies before adopting this package. Source availability does not establish npm publication or runtime qualification.

Getting started

  1. Get the source at the revision above and read its package documentation.
  2. Check the required Bijection SDK version, dependencies, and external service credentials.
  3. Follow the package setup instructions and the guide to using components.
  4. Exercise the component in your deployment according to your project’s verification rules.

Open source

Maintained source: bijectionhq/metering. Based on vllnt/convex-metering. License: MIT. Consult the repository for license terms, notices, and contributor attribution.

From the upstream publisher

Metered usage records — idempotent usage events rolled up per billing period, as a Convex component

Explore the demo ↗

Upstream overview

From the upstream package documentation.

@vllnt/convex-metering turns usage events into per-subject, per-period totals. Choose sum, max, or last aggregation and define your own units and period labels, without tying your product to a payment provider.

Define a meter, record quantities with idempotency keys, and read period totals. recordWithLimit checks a cap and records usage in one transaction. adjust corrects sum meters; closePeriod freezes a period. Raw records and a separate deduplication ledger support retention and reconciliation.

Your app verifies usage, supplies billing periods, sets rates, and generates invoices or charges through its provider. The component does not process payments. Deduplication retention and record pruning remain operational choices your backend must manage.

Maintained by bntvllnt at VLLNT. Find the author on GitHub and X.

Use cases

From the upstream package documentation.

  • Developer APIs: total requests or processed units per workspace.
  • AI tools: record token counts, generations, or compute units supplied by your backend.
  • Storage products: track peak usage or the latest measured storage value.
  • Media and data apps: aggregate processing minutes, exports, or completed jobs for reporting or billing.

How it works

From the upstream package documentation.

Define a meter, record quantities with idempotency keys, and read period totals. recordWithLimit checks a cap and records usage in one transaction. adjust corrects sum meters; closePeriod freezes a period. Raw records and a separate deduplication ledger support retention and reconciliation.

Your app verifies usage, supplies billing periods, sets rates, and generates invoices or charges through its provider. The component does not process payments. Deduplication retention and record pruning remain operational choices your backend must manage.

Upstream package FAQ

Does @vllnt/convex-metering handle billing and pricing?

@vllnt/convex-metering tracks accurate usage counts and rollups but does not store rates or compute invoice amounts. The component is intentionally rate-agnostic: you store pricing in your own Convex tables and multiply the usage value returned by usage() by your rate at billing time.

What aggregation types does convex-metering support and can they be changed later?

@vllnt/convex-metering supports three aggregations per meter: sum (accumulate all quantities), max (track peak value), and last (gauge, keeps the most recent value). The aggregation type is locked once any usage exists for that meter, so it cannot be changed after the first record call.

How does period handling work and what format is required?

The period argument in @vllnt/convex-metering is an opaque string chosen by the host application. It can be anything: '2026-06', '2026-W24', 'all', or a custom string. The component does no date parsing, so any calendar system or timezone convention works as long as the host applies it consistently.

Can I verify that usage rollups are accurate after pruning raw records?

The verify method in @vllnt/convex-metering recomputes the rollup from remaining raw records and compares it to the stored value, returning consistent: true or false along with rollupValue, recomputedValue, and recordsRemaining. This is intended for billing reconciliation audits, not real-time reads.

How do I install and configure @vllnt/convex-metering in a Convex app?

Install with npm install @vllnt/convex-metering, then register the component in convex/convex.config.ts by importing metering from '@vllnt/convex-metering/convex.config' and calling app.use(metering). Instantiate Metering with components.metering in your mutation or query files. The peer dependency is convex@^1.41.0.

Use with agents and CLI

Give your coding agent the component’s source identity and setup guidance.

agent-prompt.md
Help me integrate Metering with Bijection.

Read: https://bijection.com/components/metering/SKILL.md

Check SDK compatibility and dependency availability.
Follow this project's execution and verification rules.

Upstream README.md

View repository ↗

Documentation from vllnt/convex-metering, recorded October 23, 2026. APIs and setup may differ in the Bijection adaptation.

@vllnt/convex-metering

Metered usage records — idempotent usage events rolled up per billing period, as a Convex component.

const metering = new Metering(components.metering);
await metering.defineMeter(ctx, "api_calls", { aggregation: "sum", unit: "requests" });
await metering.record(ctx, "api_calls", orgId, 1, {
  period: "2026-06",
  idempotencyKey: requestId, // a retry won't double-count
});
const used = await metering.usage(ctx, "api_calls", orgId, { period: "2026-06" });

Define a meter, record usage for an opaque subject into host-chosen period buckets, and read O(1) per-period rollups for billing or limit checks. Recording is idempotent, so at-least-once retries never double-count. Price it in your own tables — this owns accurate usage, not your rates.

Features

  • Idempotent recording — idempotencyKey makes a retry a no-op; the dedup ledger is separate from records, so it survives pruneRecords (no double-count after pruning).
  • Per-meter aggregation — sum (accumulate), max (peak), or last (gauge), locked once usage exists.
  • Corrections + freeze — adjust posts signed refunds/credits (sum, never below zero); closePeriod freezes a billed period so late events can't restate it.
  • Atomic limits — recordWithLimit checks a cap and records in one transaction (no read-then-write overage race).
  • Reconciliation — verify recomputes the rollup from records and flags drift for billing audits.
  • Lifecycle + GDPR — listMeters/listSubjectUsage discovery, batched reset, and eraseSubject (erase a subject across all meters).
  • Period rollups — each (meter, subject, period) rolls up independently; reads are O(1).
  • Host-owned periods — period is an opaque string you choose ("2026-06", "2026-W24", "all"); no date parsing, any calendar/timezone.
  • Audit + retention — raw records back every rollup; prune old records on your schedule, rollups stay.
  • Scopes — global by default, or namespace per tenant.
  • Fully typed — quantities, periods, and units are concrete types end to end; no any.
  • Server-sourced time — record timestamps come from the server, never the caller.

Installation

pnpm add @vllnt/convex-metering

Peer dependency: convex@^1.41.0.

Usage

// convex/convex.config.ts
import { defineApp } from "convex/server";
import metering from "@vllnt/convex-metering/convex.config";

const app = defineApp();
app.use(metering);
export default app;
// convex/usage.ts — host owns auth; pass an opaque subjectRef + period in.
import { components } from "./_generated/api";
import { mutation } from "./_generated/server";
import { v } from "convex/values";
import { Metering } from "@vllnt/convex-metering";

const metering = new Metering(components.metering);

export const meterApiCall = mutation({
  args: { orgId: v.string(), requestId: v.string() },
  handler: async (ctx, { orgId, requestId }) => {
    return metering.record(ctx, "api_calls", orgId, 1, {
      period: "2026-06",
      idempotencyKey: requestId, // safe under retries
    });
  },
});

Read usage(ctx, "api_calls", orgId, { period }) for a limit check, or bill from it at your own rate in your own table — see example/convex/example.ts.

API Reference

MethodKindResult
defineMeter(ctx, key, { aggregation?, unit?, scope? })mutation{ created: boolean }
record(ctx, meter, subjectRef, quantity, { period?, idempotencyKey?, actorRef?, scope? })mutation{ recorded: true; value; count } | { recorded: false; reason: "duplicate" }
recordWithLimit(ctx, meter, subjectRef, quantity, limit, opts?)mutationRecordOutcome | { recorded: false; reason: "limit_exceeded"; value; limit }
adjust(ctx, meter, subjectRef, delta, opts?)mutationRecordOutcome (sum-only signed correction)
closePeriod(ctx, meter, subjectRef, { period?, scope? })mutationboolean (freeze)
reset(ctx, meter, subjectRef, { period?, scope?, batch? })mutationnumber (records removed this pass)
eraseSubject(ctx, subjectRef, { scope?, batch? })mutationnumber (GDPR erasure)
pruneRecords(ctx, before, batch?) · pruneSeen(ctx, before, batch?)mutationnumber
getMeter(ctx, key, scope?) · listMeters(ctx, scope?)queryMeterDefinition | null · MeterDefinition[]
usage(ctx, meter, subjectRef, { period?, scope? })query{ value, count, closed } | null
listUsage(ctx, meter, subjectRef, scope?)query{ period, value, count, closed }[]
listSubjectUsage(ctx, subjectRef, scope?)query{ meter, period, value, count, closed }[]
verify(ctx, meter, subjectRef, { period?, scope? })query{ rollupValue, recomputedValue, recordsRemaining, consistent, … }

Full reference: docs/API.md.

React

Optional, tree-shakeable hooks via @vllnt/convex-metering/react (react is an optional peer dep). Each wraps useQuery over a query reference you re-export from your app — the component never owns your api. useUsage derives a progress-bar view from an optional limit.

// convex/usage.ts — re-export a host wrapper (auth gated)
// export const myUsage = query({ args: { orgId: v.string() },
//   handler: (ctx, { orgId }) => metering.usage(ctx, "api_calls", orgId, { period: "2026-06" }) });

import { useUsage } from "@vllnt/convex-metering/react";
import { api } from "@/convex/_generated/api";

function UsageBar({ orgId }: { orgId: string }) {
  const u = useUsage(api.usage.myUsage, { meter: "api_calls", subjectRef: orgId, period: "2026-06" }, { limit: 10000 });
  if (u.isLoading) return <Spinner />;
  return <Meter value={u.fraction} label={`${u.value} / ${u.limit}`} warn={u.exceeded} />;
}
HookWrapsReturns
useUsage(usageRef, args, { limit? })usage{ isLoading, value, count, closed, limit?, remaining?, fraction?, exceeded? }
useUsageList(listUsageRef, args)listUsageUsageEntry[] | undefined

Security

  • Auth-agnostic — the host resolves identity and decides who may define meters, record, reset, or read.
  • Tables sandboxed — reached only through the exported functions; subjectRef, scope, and period stay opaque.
  • Server-sourced timestamps — a caller cannot supply record time.

See docs/API.md.

Testing

pnpm test           # single run
pnpm test:coverage  # enforced 100% on covered files

Tests run against the real component runtime via convex-test (@edge-runtime/vm), not mocks.

Contributing

See CONTRIBUTING.md.

Author

Built by bntvllnt · bntvllnt.com · X @bntvllnt

Part of the @vllnt Convex component fleet — vllnt.com

If this is useful, sponsor the work.

License

MIT — see LICENSE.

Keywords