hardcount

module
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: MIT

README

Hardcount

Usage billing for AI products, on your own servers.

CI Go License Release

Price tokens per model, sell prepaid credit, and see what each customer costs you. Hardcount makes the invoices, and Stripe charges the card. Your billing data stays in your own Postgres.

An open-source alternative to Stripe Billing and Lago: no Stripe Billing fee, no paid edition, and light enough to run yourself. Why Hardcount →


What it looks like

One month of AI usage for one customer, from the demo in test mode: one invoice line per model and token type, $5.73 due. Your margin on it is 51.9% (Sonnet 67.1%, Haiku 20.0%), shown only to you. ▶ Watch the 65-second walkthrough, narrated, with captions.


Quick start

Try Hardcount on your own computer. It runs in test mode, where no real money moves.

You need git and Docker 24 or newer with the Compose plugin. On Windows, run it inside WSL.

1. Start Hardcount

git clone --branch v0.10.0 https://github.com/gethardcount/hardcount.git
cd hardcount/deploy/compose
./quickstart.sh

You see: "Hardcount is running.", then your dashboard address, email, password and a test API key. The password is shown only once; the script also saves all four in deploy/compose/quickstart-credentials.json.

Open http://localhost:8080 and sign in. Hardcount opens in test mode, and it is empty.

2. Run the demo

./quickstart.sh demo

The demo sets up AI token prices, creates a customer and sends token usage the way a LiteLLM proxy would. Then it moves the customer's test clock (a pretend clock for test customers) to the end of the month, and Hardcount makes the invoice, its PDF and the margin report shown above.

You see: nine steps, each ending in a green ✓, then links to the invoice and the customer. Home still reads $0, because its totals leave out test-clock customers; use the links instead. Each demo step, and where to click

3. Stop or remove it

./quickstart.sh stop keeps your data. ./quickstart.sh destroy deletes it, and cannot be undone. If port 8080 is taken, start with HARDCOUNT_PORT=9000 ./quickstart.sh.

Next: send your own usage and get a first invoice · run it for real on one VM · change Hardcount itself


How it works

flowchart LR
    A["Your app or LiteLLM"] -->|"usage events"| B["Hardcount<br/>counts and prices"]
    B -->|"month ends"| C["Invoice + PDF"]
    C -->|"saved card"| D["Stripe charge"]
    D -.->|"card declined"| E["Retries and emails"]

Your app tells Hardcount what each customer used. Once the customer and its prices exist, one usage event looks like this:

curl -X POST http://localhost:8080/v1/usage-events \
  -H "Authorization: Bearer $HARDCOUNT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"event_name": "tokens",
       "external_customer_id": "acme",
       "quantity": 1200,
       "dimensions": {"model": "claude-sonnet-4.5", "token_type": "input"},
       "idempotency_key": "req-42:input"}'

external_customer_id is your own ID for the customer. The dimensions pick the price: here, Sonnet 4.5 input tokens. If you send the same idempotency_key again, Hardcount counts the event once. Already run a LiteLLM proxy? It sends these events for you. Your first invoice, step by step


Why Hardcount

The gaps Hardcount is built for:

The gap What Hardcount does
Stripe Billing takes a cut: 0.7% of billing volume on its pay-as-you-go plan, and its basic usage billing can't price each model and token type on one meter. No Stripe Billing fee. Stripe still charges the card. One meter prices every model and token type.
Key parts sit behind a paid licence, such as automatic failed-payment retries and invoice previews in Lago. One free edition. MIT, with no paid edition.
Some are heavy to run: Flexprice's default setup runs nine services, including Kafka and ClickHouse. One Go program, Postgres and Redis. The ready-made Compose setup runs five small containers.
No way to fast-forward time to test a billing change. Test clocks: move a test customer forward a month and see the invoice before any real customer gets it.
A customer can cost you more than they pay, because AI costs move with usage. Margin per customer and per model, from the provider cost Hardcount records on each usage event as it arrives. OpenMeter and Flexprice report cost too.

Stripe still charges its normal card fee, and Stripe Tax's fee if you use it. Every claim above has a source in Why Hardcount exists, and How it compares lists where the other projects are ahead.


Is Hardcount right for you?

Pre-1.0. Hardcount is young: one maintainer, Stripe and cards only, no SDKs yet, no production users yet. Until 1.0.0, a minor release can break the API, and a patch release can change something you rely on (versioning before 1.0).

A good fit if:

  • You charge by usage, most of all an AI product that prices per token, by model and token type.
  • You want billing on your own servers. Usage and invoice records stay in your own Postgres. Stripe sees each charge, and the invoice lines too if you use Stripe Tax.
  • You are a small or mid-size team. One engineer can run it, on one server or several.
  • Your volume is up to about a million usage events a day. A €6.49-a-month server took that rate for 20 minutes with no errors (measured on v0.8.0). Plan 15 to 18 GB of database disk a month at that volume. How we measured

Not a fit if you need:

  • Simple per-seat pricing paid by card. Stripe Billing already does that well.
  • Automatic charging through a processor other than Stripe. Stripe is the only one built in today. Tell us which one you need.
  • A marketplace that splits payouts between sellers (Stripe Connect). Hardcount bills your own customers.
  • Revenue recognition or accounting reports. Export the data to your own warehouse.
  • Quotes or multi-phase contracts for sales-led deals.

What's inside

  • Pricing: per-unit, graduated and package prices; rates per model and token type on one meter; a base fee plus usage on one invoice; prepaid credit that later usage draws down. AI pricing
  • Billing you can trust: Hardcount never bills the same period twice, because the database refuses a second invoice for it. Every usage line on an invoice links to the events behind it. How Hardcount keeps a bill right
  • Getting paid: cards through Stripe, with automatic retries and emails when a payment fails. Customers can also pay another way, such as a bank transfer, and you mark the invoice paid. Payment failure handling
  • Running it: one Go program with its background jobs inside, Postgres and Redis. No telemetry and no licence check. Self-host

Every feature: What Hardcount does.


Docs

docs/README.md lists every doc by what you want to do: decide if Hardcount fits, try it, connect your product, run it in production, or contribute. Good places to start:


Community and contributing

  • Questions, or evaluating a deployment: GitHub Discussions
  • Bugs: Issues. Money-path bugs are triaged first.
  • Security: SECURITY.md. Report privately, not in a public issue.
  • Contributing: we are not accepting outside pull requests at this time. A bug report or a proposed fix in an issue is welcome, and credited: CONTRIBUTING.md.

License

MIT

Directories

Path Synopsis
cmd
hardcount command
Hardcount is the billing server.
Hardcount is the billing server.
hardcount-bench-seed command
hardcount-bench-seed prepares a database for an ingest benchmark and prints the credentials the load generator needs.
hardcount-bench-seed prepares a database for an ingest benchmark and prints the credentials the load generator needs.
hardcount-bootstrap command
hardcount-bootstrap runs the database migrations, then creates a tenant with its settings, API keys and owner login, and prints the credentials.
hardcount-bootstrap runs the database migrations, then creates a tenant with its settings, API keys and owner login, and prints the credentials.
hardcount-docs-run command
hardcount-docs-run runs the commands of a Markdown page, in order, in one bash shell, and checks that each prints what the page says it prints.
hardcount-docs-run runs the commands of a Markdown page, in order, in one bash shell, and checks that each prints what the page says it prints.
hardcount-doctor command
hardcount-doctor sweeps a Hardcount database for money-invariant violations: states that no legal writer can produce.
hardcount-doctor sweeps a Hardcount database for money-invariant violations: states that no legal writer can produce.
internal
api
Package api provides the HTTP server and route wiring for Hardcount.
Package api provides the HTTP server and route wiring for Hardcount.
api/middleware
Package middleware holds the HTTP middleware of the API server.
Package middleware holds the HTTP middleware of the API server.
api/respond
Package respond writes the API's JSON responses: success bodies, list pages and the error envelope.
Package respond writes the API's JSON responses: success bodies, list pages and the error envelope.
api/timefilter
Package timefilter parses the ?from and ?to query parameters, and named variants such as ?date_from and ?date_to, for the operator-facing list and export endpoints.
Package timefilter parses the ?from and ?to query parameters, and named variants such as ?date_from and ?date_to, for the operator-facing list and export endpoints.
auth
Package auth issues API keys and decides who may do what.
Package auth issues API keys and decides who may do what.
billing
Package billing contains the billing cycle engine, scheduler, and invoice preview.
Package billing contains the billing cycle engine, scheduler, and invoice preview.
config
Package config reads Hardcount's settings from the environment and checks them at start-up.
Package config reads Hardcount's settings from the environment and checks them at start-up.
dashmembers
Package dashmembers is the minimal team-membership surface: invite by email, tokenized accept, list, revoke, remove.
Package dashmembers is the minimal team-membership surface: invite by email, tokenized accept, list, revoke, remove.
doctor
Package doctor is the money-invariant sweep: a read-only check of a Hardcount database for states that no legal writer can produce.
Package doctor is the money-invariant sweep: a read-only check of a Hardcount database for states that no legal writer can produce.
domain
Package domain holds what Hardcount's packages share: the types and status words that cross a package boundary or the wire, and the pure rules two packages must apply the same way, as Go functions or as the SQL text of a condition.
Package domain holds what Hardcount's packages share: the types and status words that cross a package boundary or the wire, and the pure rules two packages must apply the same way, as Go functions or as the SQL text of a condition.
errs
Package errs provides structured domain errors with machine-readable codes.
Package errs provides structured domain errors with machine-readable codes.
hostedinvoice
Package hostedinvoice serves the public /v1/public/invoices/* surface — Stripe's hosted_invoice_url equivalent.
Package hostedinvoice serves the public /v1/public/invoices/* surface — Stripe's hosted_invoice_url equivalent.
integrations/litellm
Package litellm adapts LiteLLM Proxy's StandardLoggingPayload to Hardcount usage events.
Package litellm adapts LiteLLM Proxy's StandardLoggingPayload to Hardcount usage events.
payment/breaker
Package breaker provides a global circuit breaker around Stripe API calls, built on sony/gobreaker/v2.
Package breaker provides a global circuit breaker around Stripe API calls, built on sony/gobreaker/v2.
paymentmethods
Package paymentmethods is the customer-facing view of payment methods.
Package paymentmethods is the customer-facing view of payment methods.
pdffonts
Package pdffonts embeds the TTF fonts that Hardcount's PDF renderers use (invoice, credit note).
Package pdffonts embeds the TTF fonts that Hardcount's PDF renderers use (invoice, credit note).
platform/activity
Package activity holds the shape of an activity line and the words that more than one activity surface shares (ADR-128).
Package activity holds the shape of an activity line and the words that more than one activity surface shares (ADR-128).
platform/clock
Package clock gives code the current time.
Package clock gives code the current time.
platform/crypto
Package crypto encrypts stored values, such as PII fields and API secrets, with AES-256-GCM.
Package crypto encrypts stored values, such as PII fields and API secrets, with AES-256-GCM.
platform/leader
Package leader holds singleton-role leadership as a row, not as a Postgres session (ADR-114).
Package leader holds singleton-role leadership as a row, not as a Postgres session (ADR-114).
platform/leader/leadertest
Package leadertest lets store tests call leader-only methods with a real, live lease token and no heartbeat.
Package leadertest lets store tests call leader-only methods with a real, live lease token and no heartbeat.
platform/listorder
Package listorder is the one rule for a list's ?sort and ?dir.
Package listorder is the one rule for a list's ?sort and ?dir.
platform/logging
Package logging holds ErrorLevel, which picks the log level for an error from work done for a request.
Package logging holds ErrorLevel, which picks the log level for an error from work done for a request.
platform/migrate
Package migrate applies Hardcount's database migrations with goose (ADR-125).
Package migrate applies Hardcount's database migrations with goose (ADR-125).
platform/money
Package money holds small, dependency-free helpers for integer-cents math, shared by billing, subscription proration and tax.
Package money holds small, dependency-free helpers for integer-cents math, shared by billing, subscription proration and tax.
platform/postgres
Package postgres opens database transactions with the settings that row-level security (RLS) reads.
Package postgres opens database transactions with the settings that row-level security (RLS) reads.
platform/request
Package request holds one HTTP request's record: what the layers of the request learn about it, readable by every layer, inner or outer.
Package request holds one HTTP request's record: what the layers of the request learn about it, readable by every layer, inner or outer.
platform/request/requesttest
Package requesttest gives tests a request's record: request.Begin with a route that holds only the method, and no mw.TrustedClientIP in front, so the record's client address is the request's TCP peer.
Package requesttest gives tests a request's record: request.Begin with a route that holds only the method, and no mw.TrustedClientIP in front, so the record's client address is the request's TCP peer.
platform/scheduler
Package scheduler hosts the standard tick-loop runner that every ticker-driven singleton worker in Hardcount uses.
Package scheduler hosts the standard tick-loop runner that every ticker-driven singleton worker in Hardcount uses.
platform/telemetry
Package telemetry sets up OpenTelemetry tracing for Hardcount.
Package telemetry sets up OpenTelemetry tracing for Hardcount.
platform/timeline
Package timeline holds the two ordering rules that every activity or timeline surface must keep:
Package timeline holds the two ordering rules that every activity or timeline surface must keep:
platform/walk
Package walk reads a list to its end, one page at a time, in the order of the list's key.
Package walk reads a list to its end, one page at a time, in the order of the list's key.
recipe
Package recipe implements pricing recipes.
Package recipe implements pricing recipes.
session
Package session implements dashboard sessions, issued by the email and password login (ADR-011).
Package session implements dashboard sessions, issued by the email and password login (ADR-011).
subscription/subscriptiontest
Package subscriptiontest holds test-only fixtures for the subscription domain, in the same shape as platform/leader/leadertest.
Package subscriptiontest holds test-only fixtures for the subscription domain, in the same shape as platform/leader/leadertest.
tax
Package tax defines the tenant-selectable tax calculation backend and three concrete implementations: NoneProvider (skip tax), ManualProvider (flat tenant-level rate), and StripeTaxProvider (Stripe Tax API; defers the invoice to tax_status=pending for retry on error).
Package tax defines the tenant-selectable tax calculation backend and three concrete implementations: NoneProvider (skip tax), ManualProvider (flat tenant-level rate), and StripeTaxProvider (Stripe Tax API; defers the invoice to tax_status=pending for retry on error).
testclock
Package testclock owns the TestClock resource: a tenant-scoped frozen-time simulator used to walk test-mode subscriptions through full billing lifecycles (trials, cycles, dunning retries) in compressed wall-clock time.
Package testclock owns the TestClock resource: a tenant-scoped frozen-time simulator used to walk test-mode subscriptions through full billing lifecycles (trials, cycles, dunning retries) in compressed wall-clock time.
testclock/testclocktest
Package testclocktest runs the test-clock catch-up in tests the way the testclock_catchup leader runs it in production (ADR-140).
Package testclocktest runs the test-clock catch-up in tests the way the testclock_catchup leader runs it in production (ADR-140).
testutil
Package testutil holds helpers that tests share: the integration test database (SetupTestDB, AdminPool), a database role for one test (CreateRole), a wait for a backend blocked on a lock (WaitForLockWaiter), and small readers for credit balances and the mode on a context.
Package testutil holds helpers that tests share: the integration test database (SetupTestDB, AdminPool), a database role for one test (CreateRole), a wait for a backend blocked on a lock (WaitForLockWaiter), and small readers for credit balances and the mode on a context.
testutil/pdftest
Package pdftest reads back what Hardcount's PDF renderers drew, for tests.
Package pdftest reads back what Hardcount's PDF renderers drew, for tests.
usage
Provider cost rates + per-customer margin (ADR-079).
Provider cost rates + per-customer margin (ADR-079).
user/breachedpw
Package breachedpw holds the breached-password list that user.ValidatePassword checks when a password is set or reset (ADR-095, "Offline breached-password").
Package breachedpw holds the breached-password list that user.ValidatePassword checks when a password is set or reset (ADR-095, "Offline breached-password").
user/breachedpw/gen command
Command gen rebuilds internal/user/breachedpw/passwords.txt from a downloaded copy of the source list.
Command gen rebuilds internal/user/breachedpw/passwords.txt from a downloaded copy of the source list.
version
Package version carries the build-time version stamp.
Package version carries the build-time version stamp.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL