Usage-based billing

Meter what customers use, rate it against a plan, and issue invoices that add up, with tests for every rounding rule.

This is an app part spec on Spekkr, published by juno. It is listed with the other specs. Paste the line to an agent that can open a web address, and the agent fetches the files and builds from them.

Spec
juno/usage-billing
Version
0.1.2
Published by
juno
Updated
15 Nov 2026

Build this spec

Build the spec at https://spekkr.com/juno/usage-billing/start.md.

Paste this to your AI agent. It opens the address, fetches the spec's files, records your choices and builds from them. Nothing to install, no account.

Published by juno.

What does the result look like?

Usage-based billing: plansUsage-based billing: customersUsage-based billing: invoicesUsage-based billing: invoice detail

What can I customize?

Database
How invoices are paid A payment provider charges a saved card. Manual marks invoices paid by hand.

Your choices go into the line you copy. Anything else is yours to edit, but it leaves the tested path.

What do I get?

  • spec.md Requirements and acceptance criteria.

    Usage-based billing

    What this builds

    A billing service for a product that charges by usage. The product reports usage events. The service totals them per customer and billing period, prices them against the customer's plan, issues an invoice, and collects payment.

    Read spekkr.inputs.json first. Every amount is in the currency input. The person's other choices decide the first meter, whether plans include usage, and how invoices are paid.

    Out of scope

    • Tax calculation. Invoices carry a tax line that is always zero in this version.
    • More than one currency.
    • Refunds and credit notes.
    • Seat-based pricing.

    Terms

    • Meter: one kind of usage, counted in whole units. The first is the meter_name input.
    • Plan: a monthly base fee, a price per unit for each meter, and, if included_usage is on, an included amount per meter.
    • Period: one calendar month in UTC.

    Requirements

    Each requirement has an id. Tests name the id they cover.

    R1. Usage events
    • The product sends events with a customer id, a meter, a quantity, a timestamp and an idempotency key.
    • The endpoint is authenticated with INGEST_API_KEY.
    • Sending the same idempotency key twice records the event once and answers with success both times.
    • An event with a quantity below 1, an unknown meter or an unknown customer is refused with a message that names the problem.
    • An event is counted in the period of its timestamp. Events for a period that has been invoiced are refused.

    Accept when: 1,000 events sent twice in random order produce the same totals as sending them once.

    R2. Plans and subscriptions
    • An operator creates plans. A plan in use cannot be edited; create a new one instead.
    • A customer has at most one active subscription.
    • Changing plan takes effect at the start of the next period.
    • Cancelling ends the subscription at the end of the current period.

    Accept when: a mid-period plan change leaves the current period priced on the old plan.

    R3. Rating
    • Usage for a meter is the sum of quantities in the period.
    • Billable units are usage minus the included amount, never below zero. With included_usage off, the included amount is zero.
    • The charge for a meter is billable units times the unit price.
    • All money is held as whole minor units, such as cents. Unit prices may have up to four extra decimal places; round each line to the nearest minor unit, halves away from zero, once, after multiplying.

    Accept when: the worked examples in design.md produce exactly the amounts shown.

    R4. Invoices
    • On the first day of each month the service issues one invoice per active subscription for the period that just ended.
    • An invoice has a base-fee line, one line per meter with billable units, a zero tax line and a total. The total equals the sum of its lines.
    • Running the invoice job twice for a period creates no duplicates.
    • An issued invoice never changes, except its status.
    • Invoice numbers increase by one with no gaps.

    Accept when: running the job three times for one period leaves exactly one invoice per subscription, and every total equals the sum of its lines.

    R5. Collection
    • payment_provider: charge the customer's saved payment method for the invoice total. Mark the invoice paid only when the provider's signed webhook confirms it. Retry a failed charge after 3, 5 and 7 days, then mark the invoice uncollectible.
    • manual: an operator marks an invoice paid and records a reference.
    • A paid invoice cannot be charged again.

    Use the payment provider's current documentation for every API call. Do not rely on memory for endpoint names, fields or webhook formats.

    Accept when: a duplicated or replayed webhook leaves the invoice paid once, and a webhook with a bad signature is refused.

    R6. Payment reminders

    Only if payment_reminders is on. Email the customer when an invoice is 3 and 10 days overdue. Stop when it is paid.

    Accept when: a paid invoice sends no further reminders.

    R7. Operator pages
    • Customers with their plan and this period's usage so far.
    • Invoices with status, and one invoice with its lines.
    • Plans, with a form to create one.

    Accept when: the usage shown for a customer equals the sum of their events for the period.

    Definition of done

    • Every acceptance check above has an automated test, and all tests pass.
    • A README explains how to configure the secrets, send a test event and run the invoice job by hand.
    # Usage-based billing
    
    ## What this builds
    
    A billing service for a product that charges by usage. The product reports usage
    events. The service totals them per customer and billing period, prices them against
    the customer's plan, issues an invoice, and collects payment.
    
    Read `spekkr.inputs.json` first. Every amount is in the `currency` input. The
    person's other choices decide the first meter, whether plans include usage, and how
    invoices are paid.
    
    ## Out of scope
    
    - Tax calculation. Invoices carry a tax line that is always zero in this version.
    - More than one currency.
    - Refunds and credit notes.
    - Seat-based pricing.
    
    ## Terms
    
    - **Meter**: one kind of usage, counted in whole units. The first is the `meter_name` input.
    - **Plan**: a monthly base fee, a price per unit for each meter, and, if
      `included_usage` is on, an included amount per meter.
    - **Period**: one calendar month in UTC.
    
    ## Requirements
    
    Each requirement has an id. Tests name the id they cover.
    
    ### R1. Usage events
    
    - The product sends events with a customer id, a meter, a quantity, a timestamp and
      an idempotency key.
    - The endpoint is authenticated with `INGEST_API_KEY`.
    - Sending the same idempotency key twice records the event once and answers with
      success both times.
    - An event with a quantity below 1, an unknown meter or an unknown customer is refused
      with a message that names the problem.
    - An event is counted in the period of its timestamp. Events for a period that has
      been invoiced are refused.
    
    Accept when: 1,000 events sent twice in random order produce the same totals as
    sending them once.
    
    ### R2. Plans and subscriptions
    
    - An operator creates plans. A plan in use cannot be edited; create a new one instead.
    - A customer has at most one active subscription.
    - Changing plan takes effect at the start of the next period.
    - Cancelling ends the subscription at the end of the current period.
    
    Accept when: a mid-period plan change leaves the current period priced on the old plan.
    
    ### R3. Rating
    
    - Usage for a meter is the sum of quantities in the period.
    - Billable units are usage minus the included amount, never below zero. With
      `included_usage` off, the included amount is zero.
    - The charge for a meter is billable units times the unit price.
    - All money is held as whole minor units, such as cents. Unit prices may have up to
      four extra decimal places; round each line to the nearest minor unit, halves away
      from zero, once, after multiplying.
    
    Accept when: the worked examples in `design.md` produce exactly the amounts shown.
    
    ### R4. Invoices
    
    - On the first day of each month the service issues one invoice per active
      subscription for the period that just ended.
    - An invoice has a base-fee line, one line per meter with billable units, a zero tax
      line and a total. The total equals the sum of its lines.
    - Running the invoice job twice for a period creates no duplicates.
    - An issued invoice never changes, except its status.
    - Invoice numbers increase by one with no gaps.
    
    Accept when: running the job three times for one period leaves exactly one invoice
    per subscription, and every total equals the sum of its lines.
    
    ### R5. Collection
    
    - `payment_provider`: charge the customer's saved payment method for the invoice
      total. Mark the invoice paid only when the provider's signed webhook confirms it.
      Retry a failed charge after 3, 5 and 7 days, then mark the invoice uncollectible.
    - `manual`: an operator marks an invoice paid and records a reference.
    - A paid invoice cannot be charged again.
    
    Use the payment provider's current documentation for every API call. Do not rely on
    memory for endpoint names, fields or webhook formats.
    
    Accept when: a duplicated or replayed webhook leaves the invoice paid once, and a
    webhook with a bad signature is refused.
    
    ### R6. Payment reminders
    
    Only if `payment_reminders` is on. Email the customer when an invoice is 3 and 10 days
    overdue. Stop when it is paid.
    
    Accept when: a paid invoice sends no further reminders.
    
    ### R7. Operator pages
    
    - Customers with their plan and this period's usage so far.
    - Invoices with status, and one invoice with its lines.
    - Plans, with a form to create one.
    
    Accept when: the usage shown for a customer equals the sum of their events for the period.
    
    ## Definition of done
    
    - Every acceptance check above has an automated test, and all tests pass.
    - A README explains how to configure the secrets, send a test event and run the
      invoice job by hand.
    

    Open spec.md as plain text

  • design.md Data model, money rules and the invoice run.

    Design

    This file fixes the parts that are easy to get wrong. Choose the language and framework that fit the person's project; nothing here depends on them.

    Data model

    Use the database in the database input.

    TableColumns
    customersid, name, email, provider_customer_ref, created_at
    metersid, name (unique)
    plansid, name, base_fee_minor, created_at, archived_at
    plan_pricesplan_id, meter_id, unit_price_scaled, included_units; primary key on both ids
    subscriptionsid, customer_id, plan_id, starts_on, ends_on, next_plan_id
    usage_eventsid, customer_id, meter_id, quantity, occurred_at, idempotency_key (unique), received_at
    invoicesid, number (unique), customer_id, subscription_id, period_start, status, total_minor, issued_at, paid_at, payment_ref; unique on subscription_id and period_start
    invoice_linesid, invoice_id, kind, meter_id, units, amount_minor, description
    charge_attemptsid, invoice_id, attempted_at, outcome, provider_ref (only for payment_provider)

    Money rules

    • Never use floating point for money.
    • base_fee_minor and every amount on an invoice are whole minor units.
    • unit_price_scaled is the unit price in minor units times 10,000, as an integer. A price of 0.25 cents per unit is stored as 2,500.
    • Line amount = round(billable units × unit_price_scaled ÷ 10,000), halves away from zero. Do the multiplication in the application, not the database, with 128-bit or arbitrary-precision integers: at high volumes the product overflows 64 bits.
    Worked examples

    Use these as tests. The plan has a base fee of 2,900 minor units, a unit price of 0.25 minor units (2,500 scaled) and 10,000 included units.

    UsageIncluded usageBillable unitsUsage lineInvoice total
    0on0no line2,900
    10,000on0no line2,900
    10,001on102,900
    10,002on212,901
    12,345on2,3455863,486
    12,345off12,3453,0865,986

    Check: 2 × 0.25 = 0.5, which rounds away from zero to 1. 2,345 × 0.25 = 586.25, which rounds to 586. 12,345 × 0.25 = 3,086.25, which rounds to 3,086.

    A usage line with zero billable units is left off the invoice. A line whose units are above zero but whose amount rounds to zero is kept, as in the third row.

    Invoice run

    Run once a day. For each subscription active at any time in the previous month, in one transaction:

    1. Stop if an invoice exists for that subscription and period. The unique index is the real guard; the check only avoids noise.
    2. Sum usage events for the period per meter.
    3. Build the lines, compute the total, take the next invoice number and insert.
    4. Apply next_plan_id to the subscription if one is set.

    Take the invoice number from a single-row counter locked inside the same transaction, so numbers have no gaps.

    Reject events for a period once any invoice for that customer and period exists.

    Collection

    Keep the provider behind one small interface with two operations: charge an invoice, and verify and parse a webhook. Tests use a fake.

    • Send the invoice id as the provider's idempotency key so a retried request cannot charge twice.
    • Verify the webhook signature with PAYMENT_WEBHOOK_SECRET before reading the body.
    • Handle each webhook event id once; store the ids you have handled.
    • Move an invoice from open to paid only inside the webhook handler.

    Statuses: open, paid, uncollectible.

    Configuration

    SecretPurpose
    DATABASE_URLConnection string for the chosen database.
    INGEST_API_KEYAuthenticates usage events from the product.
    PAYMENT_PROVIDER_KEYCharges invoices. Only for payment_provider.
    PAYMENT_WEBHOOK_SECRETVerifies provider webhooks. Only for payment_provider.

    Named here

    • The keys of an ingest body are customer_id, meter, quantity, occurred_at and idempotency_key.
    • The retries are 3, 5 and 7 days after the invoice was issued. A fourth failure marks it uncollectible.
    • A plan is in use when any subscription has it as its plan or its next plan.

    What this spec leaves to you

    Where this spec names something, use that name, so that two builds of it agree. Where it does not, the choice is yours. List what you chose in the README.

    # Design
    
    This file fixes the parts that are easy to get wrong. Choose the language and
    framework that fit the person's project; nothing here depends on them.
    
    ## Data model
    
    Use the database in the `database` input.
    
    | Table | Columns |
    | --- | --- |
    | `customers` | `id`, `name`, `email`, `provider_customer_ref`, `created_at` |
    | `meters` | `id`, `name` (unique) |
    | `plans` | `id`, `name`, `base_fee_minor`, `created_at`, `archived_at` |
    | `plan_prices` | `plan_id`, `meter_id`, `unit_price_scaled`, `included_units`; primary key on both ids |
    | `subscriptions` | `id`, `customer_id`, `plan_id`, `starts_on`, `ends_on`, `next_plan_id` |
    | `usage_events` | `id`, `customer_id`, `meter_id`, `quantity`, `occurred_at`, `idempotency_key` (unique), `received_at` |
    | `invoices` | `id`, `number` (unique), `customer_id`, `subscription_id`, `period_start`, `status`, `total_minor`, `issued_at`, `paid_at`, `payment_ref`; unique on `subscription_id` and `period_start` |
    | `invoice_lines` | `id`, `invoice_id`, `kind`, `meter_id`, `units`, `amount_minor`, `description` |
    | `charge_attempts` | `id`, `invoice_id`, `attempted_at`, `outcome`, `provider_ref` (only for `payment_provider`) |
    
    ## Money rules
    
    - Never use floating point for money.
    - `base_fee_minor` and every amount on an invoice are whole minor units.
    - `unit_price_scaled` is the unit price in minor units times 10,000, as an integer.
      A price of 0.25 cents per unit is stored as 2,500.
    - Line amount = round(billable units × `unit_price_scaled` ÷ 10,000), halves away
      from zero. Do the multiplication in the application, not the database, with
      128-bit or arbitrary-precision integers: at high volumes the product overflows 64 bits.
    
    ### Worked examples
    
    Use these as tests. The plan has a base fee of 2,900 minor units, a unit price of
    0.25 minor units (2,500 scaled) and 10,000 included units.
    
    | Usage | Included usage | Billable units | Usage line | Invoice total |
    | --- | --- | --- | --- | --- |
    | 0 | on | 0 | no line | 2,900 |
    | 10,000 | on | 0 | no line | 2,900 |
    | 10,001 | on | 1 | 0 | 2,900 |
    | 10,002 | on | 2 | 1 | 2,901 |
    | 12,345 | on | 2,345 | 586 | 3,486 |
    | 12,345 | off | 12,345 | 3,086 | 5,986 |
    
    Check: 2 × 0.25 = 0.5, which rounds away from zero to 1. 2,345 × 0.25 = 586.25,
    which rounds to 586. 12,345 × 0.25 = 3,086.25, which rounds to 3,086.
    
    A usage line with zero billable units is left off the invoice. A line whose units are
    above zero but whose amount rounds to zero is kept, as in the third row.
    
    ## Invoice run
    
    Run once a day. For each subscription active at any time in the previous month, in
    one transaction:
    
    1. Stop if an invoice exists for that subscription and period. The unique index is
       the real guard; the check only avoids noise.
    2. Sum usage events for the period per meter.
    3. Build the lines, compute the total, take the next invoice number and insert.
    4. Apply `next_plan_id` to the subscription if one is set.
    
    Take the invoice number from a single-row counter locked inside the same transaction,
    so numbers have no gaps.
    
    Reject events for a period once any invoice for that customer and period exists.
    
    ## Collection
    
    Keep the provider behind one small interface with two operations: charge an invoice,
    and verify and parse a webhook. Tests use a fake.
    
    - Send the invoice id as the provider's idempotency key so a retried request cannot
      charge twice.
    - Verify the webhook signature with `PAYMENT_WEBHOOK_SECRET` before reading the body.
    - Handle each webhook event id once; store the ids you have handled.
    - Move an invoice from `open` to `paid` only inside the webhook handler.
    
    Statuses: `open`, `paid`, `uncollectible`.
    
    ## Configuration
    
    | Secret | Purpose |
    | --- | --- |
    | `DATABASE_URL` | Connection string for the chosen database. |
    | `INGEST_API_KEY` | Authenticates usage events from the product. |
    | `PAYMENT_PROVIDER_KEY` | Charges invoices. Only for `payment_provider`. |
    | `PAYMENT_WEBHOOK_SECRET` | Verifies provider webhooks. Only for `payment_provider`. |
    
    ## Named here
    
    - The keys of an ingest body are `customer_id`, `meter`, `quantity`,
      `occurred_at` and `idempotency_key`.
    - The retries are 3, 5 and 7 days after the invoice was issued. A fourth failure
      marks it uncollectible.
    - A plan is in use when any subscription has it as its plan or its next plan.
    
    ## What this spec leaves to you
    
    Where this spec names something, use that name, so that two builds of it agree.
    Where it does not, the choice is yours. List what you chose in the README.
    

    Open design.md as plain text

  • tasks.md Build tasks in order, each with a check.

    Tasks

    Work in order. Finish a task's check before starting the next.

    1. Set up the project. Pick the stack, add the database from the database input, a migration tool and a test runner. Check: an empty test run passes and the service answers on a health route.
    2. Create the schema. Add the tables in design.md and seed the first meter from the meter_name input. Check: migrations run from empty, and a test proves a second invoice for the same subscription and period is rejected by the database.
    3. Money arithmetic. Write the rating function on its own, with no database. Check: every row of the worked examples in design.md passes, with included_usage both on and off.
    4. Usage events (R1). Build the ingest endpoint. Check: the R1 acceptance test passes.
    5. Plans and subscriptions (R2). Check: the R2 acceptance test passes.
    6. Invoice run (R3, R4). Build the daily job and a way to run it by hand for a given period. Check: the R4 acceptance test passes and invoice numbers have no gaps.
    7. Collection (R5). Build the method in the collection input. For payment_provider, read the provider's current documentation first. Check: the R5 acceptance test passes against a fake provider.
    8. Payment reminders (R6). Only if payment_reminders is on. Check: the R6 acceptance test passes with emails captured in memory.
    9. Operator pages (R7). Check: the R7 acceptance test passes.
    10. Finish. Write the README and run the whole test suite. Check: every item under "Definition of done" in spec.md is true.
    # Tasks
    
    Work in order. Finish a task's check before starting the next.
    
    1. **Set up the project.** Pick the stack, add the database from the `database`
       input, a migration tool and a test runner.
       Check: an empty test run passes and the service answers on a health route.
    
    2. **Create the schema.** Add the tables in `design.md` and seed the first meter from
       the `meter_name` input.
       Check: migrations run from empty, and a test proves a second invoice for the same
       subscription and period is rejected by the database.
    
    3. **Money arithmetic.** Write the rating function on its own, with no database.
       Check: every row of the worked examples in `design.md` passes, with
       `included_usage` both on and off.
    
    4. **Usage events (R1).** Build the ingest endpoint.
       Check: the R1 acceptance test passes.
    
    5. **Plans and subscriptions (R2).**
       Check: the R2 acceptance test passes.
    
    6. **Invoice run (R3, R4).** Build the daily job and a way to run it by hand for a
       given period.
       Check: the R4 acceptance test passes and invoice numbers have no gaps.
    
    7. **Collection (R5).** Build the method in the `collection` input. For
       `payment_provider`, read the provider's current documentation first.
       Check: the R5 acceptance test passes against a fake provider.
    
    8. **Payment reminders (R6).** Only if `payment_reminders` is on.
       Check: the R6 acceptance test passes with emails captured in memory.
    
    9. **Operator pages (R7).**
       Check: the R7 acceptance test passes.
    
    10. **Finish.** Write the README and run the whole test suite.
        Check: every item under "Definition of done" in `spec.md` is true.
    

    Open tasks.md as plain text

Is it for me?

Platforms
backend, web

What does it need?

Accounts
A payment provider account, unless invoices are paid manually
Agent permissions
shell, network
Secrets it reads
DATABASE_URL PAYMENT_PROVIDER_KEY PAYMENT_WEBHOOK_SECRET INGEST_API_KEY

What changed?

  • 0.1.215 Nov 2026Names what it builds.
  • 0.1.114 Nov 2026Says "person" where it said "buyer".
  • 0.1.014 Nov 2026Moved from dwrtz/usage-billing.

For agents: start.md says how to build this spec, spec.json holds everything on this page, and bundle.tar.gz holds its files.