Case study

Meter

Usage metering for AI apps. Send token and API-call events. Meter totals them per customer, prices them against a plan and produces an invoice.

Project
My own, open source
Stack
NestJS, PostgreSQL, Redis
Meter simulated demo: live metering screen with usage totals per customer

The problem and what I built

The problem

  1. An AI app pays its model provider per token.
  2. Its customers often pay a flat fee.
  3. A heavy user can cost more than they pay.
  4. Charging for usage needs counts that stay correct when a sender retries.

What I built

  1. An API that records usage events for each customer and keeps running totals.
  2. Plans with a base fee, an allowance and an overage price.
  3. Period closing that turns the totals into an invoice with line items and a CSV file.
  4. Usage reports as CSV, JSON or PDF.

What is in the repository

  • 26tests

    Pricing math and period dates have unit tests. Duplicate rejection, auth, period closing and usage deletion run against the live service and its database.

  • 1×count per event_id

    Ingest is idempotent. A replay is reported as a duplicate and adds nothing.

  • ↻invoice worker with retries

    A queue worker writes each invoice and is safe to repeat. Unissued invoices are queued again on boot.

  • 1Docker command

    docker compose up --build -d --wait starts the whole stack.

Design decisions

  • The database enforces idempotency. event_id is unique per customer. The event insert and the running total share one transaction.
  • Running totals sit next to the event log. Reading the bill does not scan events.
  • Periods are calendar months in UTC. An admin call closes a period. There is no scheduler.
  • Closing takes two steps. One transaction snapshots totals and plan prices into a pending invoice. A queue worker then writes the lines and the file.
  • Money is computed with integers. Each line rounds half up to cents, and the total is the sum of the lines.
  • The API key identifies the customer. There is one key per customer, stored as a SHA-256 hash. Admin routes take a separate key.
  • Files use plain S3 calls. SeaweedFS locally, Cloudflare R2 or another S3 service for deploys. Downloads go through the API.

Current limits

  • No payment provider is connected.
  • Plans are defined in a seed script.
  • API keys cannot be rotated or revoked yet.
  • Workers run inside the API process.

Roadmap, not built: agent-assisted setup through MCP.

Stack

  • NestJS
  • TypeScript
  • Drizzle ORM
  • PostgreSQL
  • Redis
  • Bull
  • SeaweedFS
  • Docker Compose

Need usage billing in your app?

Tell me what you meter and how you charge for it.

Book a call

No prep needed