codebaobab
Python workspace

All problemsData & Systems

Subscription Billing Engine

Build the invoice engine for a SaaS billing system from a one-page spec.

Python60 minutesData & Systems

Challenge brief

Read before you begin

Your mission · Build from a spec

Build the invoice engine that renews plans, prorates plan changes in whole cents, and keeps credit.

Mossgate's two-person finance team bills from a spreadsheet and prorates every plan change by hand. October brought 64 billing disputes and $18,400 in credits written off. On January 12 clinics can change plans in the app themselves, and finance needs an engine that bills those changes correctly.

  • Target · All public checks
  • Mode · Build from a spec
Skip to round setup

Your assignment

  1. Read docs/spec.md and choose the data model.
  2. Renew every period an advance passes.
  3. Add proration, plan changes, credit and cancels.
  4. Handle the new requirement when it arrives.
  5. Write the model and next steps in NOTES.md.

The problem

Plan changes prorated by hand

Finance works out each upgrade and downgrade in a spreadsheet.

Impact: Clinics were billed a few dollars wrong, and 64 disputed it in October.

Downgrade credit gets lost

A downgrade refund is noted in a comment and often never applied.

Impact: Clinics paid in full the next month and asked for their money back.

Renewals and changes are stubs

Every advance and change fails with NotImplementedError.

Impact: Self-serve plan changes cannot launch on January 12.

Context

Disputes in October
64
Credits written off
$18,400
Self-serve changes
Jan 12

Requirements

  • One advance renews every period it passes.
  • Invoices in day order, then account order.
  • Unused and remaining lines rounded on their own.
  • An exact half cent rounds up.
  • A new interval starts a new period that day.
  • A negative invoice becomes credit.
  • A cancel ends at the period end.
  • Bad input raises ValueError naming the field.

System overview

Edit the components marked “Your work”. The other components show where your changes fit.

Clinic admin appPlan changes by clinics
Nightly schedulerMoves the billing day
Invoice engine(Your work)Writes invoices, keeps credit
Plan catalogPrices and intervals
Payment processorCharges what is due
Invoice ledgerInvoices and credit
Read the connections
  • Clinic admin app → Invoice engine: plan events
  • Nightly scheduler → Invoice engine: advance
  • Plan catalog → Invoice engine: plans
  • Invoice engine → Payment processor: amount due
  • Invoice engine → Invoice ledger: invoices
  • Clinic admin app: Where a clinic subscribes, changes plan or cancels.
  • Nightly scheduler: Sends one advance a day at 00:05 UTC, or a longer one after an outage.
  • Invoice engine: replay(config, events) in billing/engine.py; the Billing class in billing/services/ledger.py.
  • Plan catalog: Plan names, prices in cents and intervals, owned by finance.
  • Payment processor: Charges the card on file for the amount due on each invoice.
  • Invoice ledger: Every invoice and credit balance, kept seven years for tax.

Details

Full requirements

Functional

  1. replay(config, events) runs the events in order on a new ledger and returns one result per event. config is the plan catalog: price in whole cents and interval month (30 days) or year (365 days). The clock starts at day 0 and every event happens on the current day.
  2. subscribe starts a period today and returns its invoice. advance moves the clock and renews every period that ends on or before the new day, on the day it ends, as many times as needed. Invoices come in day order, then account order, because finance reconciles them in that order against the processor.
  3. change bills the plan change today. Within one interval the period keeps its end, and the invoice credits the unused part of the old plan and charges the remaining part of the new one. Each line is rounded to whole cents on its own, with an exact half rounded up, so the lines on the invoice add up to what was charged. A change to another interval credits the unused part and starts a new full period today.
  4. An invoice whose lines add up to less than zero is due 0 and becomes credit. Credit pays later invoices first and stays with the account after the subscription ends, because finance owes it to the clinic.
  5. cancel stops renewal: the subscription ends on its period end with no invoice, and the clinic keeps what it paid for until then.
  6. Bad input raises ValueError naming the problem: already, same, cancel, not subscribed, plan, account, price, interval, plans, days, op.

Non-functional

  • Scale: about 2,300 subscriptions, 70 to 90 renewals and 15 plan changes on a normal day, and 400 changes expected in the first week of self-serve.
  • Catch-up: after an outage the scheduler sends one advance for all the days it missed, up to 31. One long advance must give exactly the same invoices as the same days one at a time.
  • Money: whole cents only. Floats and Python round() are not allowed in the money path, because round() rounds an exact half to the even number.
  • Determinism: replaying the event log must reproduce every invoice exactly, to the cent, for tax audits.
  • Cost of a wrong answer: an overcharge becomes a dispute that costs finance about 25 minutes and often a goodwill credit; an undercharge is revenue lost for good.

Out of scope

  • Calendar months, time zones and the billing day of the month. Periods are 30 or 365 days.
  • Taxes, currencies other than US dollars, payment failures and retries.
  • Refunds to the card. Credit is only applied to later invoices.
  • The admin app, the payment processor and the HTTP layer in practice_api/.
Data model

Plan

FieldTypeNotes
priceinteger >= 0Cents for one full period. 4900 is $49.00.
interval"month" | "year"A month is 30 days, a year 365.

Invoice

FieldTypeNotes
accountstringThe clinic, for example "clinic-0412".
dayintegerThe day the invoice is dated.
lines{kind, plan, amount}[]kind is period, unused (negative) or remaining.
dueintegerCents the processor charges, never below 0.
creditintegerThe account's credit after this invoice.

Advance result

FieldTypeNotes
dayintegerThe new day.
invoicesInvoice[]Every renewal, by day and then account.
ended{account, day}[]Cancelled subscriptions that reached their period end.
Files you are given · 5
  • config/plan-catalog.json The live catalog: Solo and Clinic, monthly and yearly, prices in cents. Arguments for Preview.
    {
      "plans": {
        "solo": {
          "price": 4900,
          "interval": "month"
        },
        "clinic": {
          "price": 12900,
          "interval": "month"
        },
        "solo-annual": {
          "price": 49000,
          "interval": "year"
        },
        "clinic-annual": {
          "price": 129000,
          "interval": "year"
        }
      }
    }
  • samples/three-clinics.json Three clinics over 90 days: an upgrade, a downgrade that leaves credit, a cancel, and a yearly plan moved to monthly.
    [
      {
        "plans": {
          "solo": {
            "price": 4900,
            "interval": "month"
          },
          "clinic": {
            "price": 12900,
            "interval": "month"
          },
          "solo-annual": {
            "price": 49000,
            "interval": "year"
          },
          "clinic-annual": {
            "price": 129000,
            "interval": "year"
          }
        }
      },
      [
        {
          "op": "subscribe",
          "account": "clinic-0412",
          "plan": "solo"
        },
        {
          "op": "subscribe",
          "account": "clinic-0577",
          "plan": "clinic"
        },
        {
          "op": "subscribe",
          "account": "clinic-0903",
          "plan": "solo-annual"
        },
        {
          "op": "advance",
          "days": 12
        },
        {
          "op": "change",
          "account": "clinic-0412",
          "plan": "clinic"
        },
        {
          "op": "change",
          "account": "clinic-0577",
          "plan": "solo"
        },
        {
          "op": "advance",
          "days": 18
        },
        {
          "op": "cancel",
          "account": "clinic-0577"
        },
        {
          "op": "change",
          "account": "clinic-0903",
          "plan": "clinic"
        },
        {
          "op": "advance",
          "days": 60
        }
      ]
    ]
  • samples/three-clinics-expected.json What the spec says those events return. clinic-0903's unused year pays for its next months.
    [
      {"account": "clinic-0412", "day": 0, "lines": [{"kind": "period", "plan": "solo", "amount": 4900}], "due": 4900, "credit": 0},
      {"account": "clinic-0577", "day": 0, "lines": [{"kind": "period", "plan": "clinic", "amount": 12900}], "due": 12900, "credit": 0},
      {"account": "clinic-0903", "day": 0, "lines": [{"kind": "period", "plan": "solo-annual", "amount": 49000}], "due": 49000, "credit": 0},
      {"day": 12, "invoices": [], "ended": []},
      {"account": "clinic-0412", "day": 12, "lines": [{"kind": "unused", "plan": "solo", "amount": -2940}, {"kind": "remaining", "plan": "clinic", "amount": 7740}], "due": 4800, "credit": 0},
      {"account": "clinic-0577", "day": 12, "lines": [{"kind": "unused", "plan": "clinic", "amount": -7740}, {"kind": "remaining", "plan": "solo", "amount": 2940}], "due": 0, "credit": 4800},
      {"day": 30, "invoices": [{"account": "clinic-0412", "day": 30, "lines": [{"kind": "period", "plan": "clinic", "amount": 12900}], "due": 12900, "credit": 0}, {"account": "clinic-0577", "day": 30, "lines": [{"kind": "period", "plan": "solo", "amount": 4900}], "due": 100, "credit": 0}], "ended": []},
      {"account": "clinic-0577", "state": "cancelling", "ends": 60},
      {"account": "clinic-0903", "day": 30, "lines": [{"kind": "unused", "plan": "solo-annual", "amount": -44973}, {"kind": "period", "plan": "clinic", "amount": 12900}], "due": 0, "credit": 32073},
      {"day": 90, "invoices": [{"account": "clinic-0412", "day": 60, "lines": [{"kind": "period", "plan": "clinic", "amount": 12900}], "due": 12900, "credit": 0}, {"account": "clinic-0903", "day": 60, "lines": [{"kind": "period", "plan": "clinic", "amount": 12900}], "due": 0, "credit": 19173}, {"account": "clinic-0412", "day": 90, "lines": [{"kind": "period", "plan": "clinic", "amount": 12900}], "due": 12900, "credit": 0}, {"account": "clinic-0903", "day": 90, "lines": [{"kind": "period", "plan": "clinic", "amount": 12900}], "due": 0, "credit": 6273}], "ended": [{"account": "clinic-0577", "day": 60}]}
    ]
  • logs/billing-disputes-2026-10.log October disputes from support: full-month charges on upgrades, lost credit, renewals on the wrong day.
    2026-10-03T14:12:40Z support dispute account=clinic-0218 reason="upgraded mid-month, charged a full month of Clinic" amount_usd=58.47
    2026-10-09T09:31:05Z support dispute account=clinic-1170 reason="downgrade credit never applied" amount_usd=53.33
    2026-10-14T16:02:19Z support dispute account=clinic-0663 reason="renewed on the 1st, plan started on the 17th" amount_usd=129.00
    2026-10-21T11:47:52Z support dispute account=clinic-0412 reason="proration off by one cent on two lines" amount_usd=0.01
    2026-10-28T08:20:11Z support dispute account=clinic-0981 reason="cancelled, still billed next month" amount_usd=49.00
  • metrics/billing-disputes-2026.csv Invoices, plan changes, disputes and credits written off per month since June.
    month,invoices,plan_changes,disputes,credits_written_off_usd
    2026-06,2104,118,21,4260
    2026-07,2151,131,27,6105
    2026-08,2199,147,33,8890
    2026-09,2246,162,45,12740
    2026-10,2290,184,64,18400
Tickets · 4
  • TASK-201 Read docs/spec.md and decide what the ledger stores Reported by Imani (billing)

    Expected NOTES.md says what is stored for each account and subscription, and why credit lives apart from the subscription.

    Actual Billing has a clock, subscriptions and credit, but nothing writes down what a renewal or a change does, and that code is a stub.

  • TASK-202 Renewals: advance the clock and invoice every period that ends Reported by Imani (billing)

    Expected Three renewal invoices, on days 30, 60 and 90.

    Actual The advance fails with NotImplementedError: "Implement Billing.advance using the request contract".

  • TASK-203 Then proration and plan changes, then credit, then cancels Reported by Rafael (finance)

    Expected Every result matches the expected file to the cent, clinic-0577 ends on day 60, and the short advances give the same invoices as the long one.

    Actual The first change fails with NotImplementedError: "Implement Billing.change using the request contract".

  • TASK-204 Write down anything you chose to leave out or would do next Reported by Rafael (finance)

    Expected A short list of what the engine does not handle yet and what you would build next, with a reason for each.

    Actual NOTES.md has no entry.

What you hand in
  • Every public check passing, including the new requirement when it arrives.
  • NOTES.md: the data model in a few lines, the order you built it in, the rounding rule in your own words, and what you left out or would do next.
  • Your answer to the interviewer's follow-up and the debrief questions.
How the work is judged
Breaking down the work
States the data model before asking for code, then builds renewals, proration and changes, credit and cancels in that order, with the checks run after each.
Directing the assistant
Hands the assistant one method at a time with the spec rule it must follow, including the rounding rule written in integers, and a hand-worked case.
Checking the work
Works small event lists in cents first, checks the three-clinic sample against its expected file, tries an exact half cent, and compares one long advance with short ones.
Judging the assistant
Rejects round() or float money, a single renewal per advance, a net proration line, or a downgrade clamped to zero.
Correct result
All checks pass, including renewal order, rounding of each line, interval changes, credit carried across invoices, cancels, and the usage add-on.
Explaining the work
Explains the data model, the renewal loop and the rounding rule in a few sentences finance could follow, and names what was left out.
Trade-offs to discuss
  • Fixed 30 and 365 day periods versus calendar months anchored to a billing day, and what each does to proration.
  • Prorating by day versus by second, and whether finance can explain the result to a clinic.
  • Applying credit to the next invoice versus refunding it to the card at once.
  • Billing usage in arrears at renewal versus charging it as it happens, and what a plan change does to each.
How you are graded
  • Decomposition 25%
  • Prompting the assistant 15%
  • Verification 20%
  • Judgment about AI output 10%
  • Correctness 20%
  • Communication 10%

Scores use evidence from your session. A short or incomplete session may not provide enough evidence for every skill. See a sample scorecard

Interview guidance

Build the invoice engine for a SaaS company that sells monthly and yearly plans. Plans renew, clinics change plan in the middle of a period, and some cancel. The spec is one page and money is in whole cents. Start with renewals and grow it. Use the AI assistant however you like, and tell me your data model before you ask it for code.

  • AI is allowed and expected: your own Claude, OpenAI or Gemini key, or the free in-browser model.
  • You are graded on how you drive and check the AI, not on how much you prompt.
  • Run the checks; read what fails.
  • A new requirement will arrive partway through.
  • Too little AI use is reported as “not enough to grade”, never as a fail.
Debrief · 8 questions
  • What did you delegate to the AI, and why?
  • Name one AI suggestion you rejected or changed, and why.
  • Choose one block the AI helped write. Explain what each line does and which test verifies it.
  • What is still risky, and what would you test or ship next?
  • What was your first working step, and how long did it take to get its first check passing?
  • What is your data model, and what did you decide yourself before asking the assistant?
  • Which edge case did you test that the assistant's first version got wrong?
  • What did you leave out, and what would you build next?