Partner Portal Architecture: The Ledger Under the Login
A partner portal is a ledger with a login on top. The schema invariants, attribution rules and refund math that decide whether your program pays right.
Search for how to build a partner portal and you get portal design. Onboarding flows, a resource library, tiered partner badges, an integration diagram with nine boxes in it. That is the easy half. The part that decides whether your program survives its first refund is one table with about twenty columns, and almost nobody draws it.
This is that table. By the end you will have the invariants that decide whether the right partner gets the right amount exactly once, plus an honest test for whether you should write any of it yourself. For most readers that test comes out as no, and the last two sections explain why in dollars.
A partner portal is four kinds of state, and only one of them is money
We shipped a partner program on this site in September 2026. The public offer
lives at /partner/join, the schema lives in supabase/affiliate-tables.sql,
and it comes to nine tables, fifteen route handlers and roughly 2,600 lines of
TypeScript. Worth saying plainly before anything else: that program belongs to
this marketing site, not to the directory boilerplate we sell. Nothing below
is a product feature. It is the architecture we had to get right to pay people.
Those nine tables collapse into four kinds of state, and they are not equally dangerous:
- Identity. Partners, their referral codes, their sessions. A code must be globally unique across every partner and every retired alias, otherwise a recycled code silently pays the wrong person.
- Traffic. Clicks and checkout sessions. This is analytics. Lose a row and you lose a number on a chart.
- The ledger. One row per attributed order, carrying what accrued, what was clawed back, and what has been paid. Lose a row here and you lose trust.
- Payouts. Batches, per-partner lines, the paper trail.
Almost all published advice about partner portals is about the first two. The third is where programs actually break, because it is the only place where two systems you do not control — a payment provider and a human with a grievance — meet inside your database.
Attribution is a binding problem, not a tracking problem
The tracking part is a solved afternoon. Capture ?ref=CODE on any page, accept
a couple of aliases (via, aff) so links shared in other formats still
resolve, drop a first-party cookie, forward the code into the checkout as
metadata so the resulting order is self-describing.
Binding is the hard part. Once a sale has been attributed to a partner, it must never be re-attributed. Not by a retried webhook, not by a second event carrying a different code, not by two deliveries arriving at the same millisecond.
Application code cannot promise that. A database constraint can:
-- The single most important line in the schema. It does two jobs.
--
-- 1. Webhook idempotency. The provider retries. The accrual path INSERTs
-- unconditionally and treats SQLSTATE 23505 as success. There is
-- deliberately NO prior SELECT: two concurrent deliveries would both pass
-- a check-then-insert and both write a row.
--
-- 2. First-bind-wins attribution. A later event carrying a DIFFERENT referral
-- code for the same order collides on the same index and is rejected.
create unique index if not exists uq_partner_commissions_polar_order
on partner_commissions(polar_order_id);That is the whole mechanism. Insert blind, catch the duplicate-key error, call
it a success. The SELECT you were about to write is the bug: check-then-insert
is not atomic, and webhook deliveries are exactly the workload that finds it.
We wrote up the wider version of this failure in
why the payment lands but the row doesn't,
and the same rule applies here with money attached.
Stripe's own webhook documentation is blunt about the ordering guarantee you do not get: it does not guarantee delivery of events in the order they are generated. Build as if every event will arrive twice, out of order, weeks apart.
Freeze the number the moment it accrues
The tempting design stores inputs and recomputes the commission on read. Rate, price, order id, multiply on demand. It is smaller, it normalises nicely, and it will eventually pay somebody the wrong amount.
Store the computed result. Store the inputs too, frozen: the order's net amount, the rate in basis points at the moment of accrual, the currency. Then a rate change next quarter, a price change next year, or a change to your rounding rule cannot retroactively alter what already accrued — and a refund fourteen months later reverses exactly what was granted.
Three decisions inside that number are worth arguing about before you write it.
Which amount is the base. We commission on the provider's net amount, which is subtotal minus discount, pre-tax. Commissioning on the total would hand partners a share of VAT that you remit to a tax authority, and on an EU sale that is twenty-something percent of the base given away for nothing.
How you round. Integer cents, always; no float ever represents money. We round half-up, applied exactly once at the end. Not banker's rounding, because it makes the half-cent case depend on the parity of the preceding digit and you cannot explain that to a partner disputing a payout. Not truncation, because it underpays across thousands of orders in one direction.
What happens on an unknown product. Nothing gets a default rate. An unrecognised product id quarantines the row for review with a commission of zero, excluded from every money aggregate. Guessing a rate is how a new pricing tier silently pays wrong for six months.
One structural trick is worth stealing. Put the arithmetic in a pure module with no imports, no clock, no I/O — then call it from both the accrual path and the "you'll earn X per sale" preview in the partner dashboard. Showing one number and paying another is the bug that ends programs. Sharing the function makes the two impossible to diverge, rather than merely tested for.
Refunds: set the reversal, never add to it
Here is the design decision that saves the most pain, and it is one line of API shape. A refund handler should compute an absolute total that the caller SETs on the row. Never a delta to add.
/**
* How much of a commission must be clawed back, given the order's CUMULATIVE
* refunded amount as reported by the provider. Returns an absolute total.
*/
export function computeReversalCents({
commissionCents,
refundedCents,
orderNetCents,
}: ReversalInput): number {
if (commissionCents <= 0 || refundedCents <= 0) return 0
if (orderNetCents <= 0) return commissionCents
// Full refund short-circuits to the stored commission rather than relying on
// the ratio landing on 1.0, so a refunded sale nets to EXACTLY zero.
if (refundedCents >= orderNetCents) return commissionCents
const raw = divRoundHalfUp(commissionCents * refundedCents, orderNetCents)
return Math.min(Math.max(raw, 0), commissionCents)
}Three properties fall out of SET rather than increment, and each one removes a class of bug you would otherwise chase in production:
- Retries are free. The provider redelivering the same refund five times computes the same number five times. This matters more than usual because two different event types may fire for a single refund; with SET that double notification is a harmless no-op, with an increment it charges the partner twice.
- Partial refunds compose without coordination. Refund $20 of $100, then $30 more. The second event carries the cumulative $50 and recomputes to fifty percent, without needing to know the first one ever happened.
- Out-of-order delivery self-corrects, because a cumulative refunded amount only ever goes up.
Then let the database do the accounting. A generated column
(commission_cents - reversed_cents - paid_cents) that is allowed to go
negative gives you clawback for free: a refund landing after the money was paid
out produces a negative row that sums into the partner's next payable balance.
No clawback table. No reconciliation job.
Who is allowed to read this row?
Most partner portals are built on service-role database access with no row-level security, because they start as an afternoon's admin page and grow. Ours is one of them. That means the database will not protect you, and every authorisation decision has to be made explicitly in the route handler.
Three rules carried the whole thing:
- Scope every query by the partner id derived from their session cookie, never from a request body or a query parameter.
- Expose a projection, not table rows. A partner has no business seeing the email address or order id of the person they referred.
- The client may send an intent ("pay me out"). It may never send an amount. Anything that determines money is computed server-side from data the client cannot influence.
Now the mirror image, because buying has an authorisation story too, and it is
rarely read out loud. Polar's own documentation for connecting the Affonso
affiliate platform tells you to create an API token, set expiration to
No expiration, and
enable ten scopes including customers:write. That is a defensible trade — the
integration breaks silently if the token lapses — but it is a standing
credential that can modify your customer records, sitting in a third party's
database forever. Know which risk you picked.
Payouts are the line item nobody budgets
The accrual side is engineering. The payout side is policy, tax and banking, and it is where build estimates go wrong.
Start with the hold period. A commission should not become payable until your refund window has closed; ours holds for 30 days and derives payability from a timestamp column, so no cron job is required. Add a minimum balance before a partner enters a payout run, because a $6 bank transfer costs more in fees and attention than it moves. Then pick rails, and accept that no single automated rail reaches everyone — we ended up offering four, run manually.
Tax is the part that ambushes people. The IRS lists four conditions for reporting a payment as nonemployee compensation, and the fourth is that reportable payments total the threshold amount or greater during the year. Two details on that page matter more than the threshold itself. Filing volume has a cliff: "Employers who file 10 or more information returns, Form 1099 series, Form 1042-S, and Form W-2, are required to file them electronically." And affiliates are global by nature, so you will hit the sentence that starts "Nonemployee compensation paid to nonresident aliens is reported on Form 1042-S" — a different form, with the note that "withholding may be required on these payments."
This is not tax advice, and the specific answer depends on where you and your partners sit. The architectural point holds anyway: collecting W-8 and W-9 forms is a feature. Affonso sells it from its Growth plan and marks it not included on the entry tier; Tolt bundles W-9/W-8 collection and 1099 filing from Growth upward. If you build, that work is yours, and it arrives in January.
Our payouts are manual across four rails. A partner in a country none of them reaches waits for a human to solve it, and the program collects no tax forms at all — that stayed a policy decision rather than a feature. A $29/month vendor would have handled both on day one. We accepted it because our payment provider forced the choice, not because it is better.
The arithmetic that should stop you
Affiliate platforms price on revenue attributed to affiliates, not on the number of partners or sales. So the plan you need depends entirely on your order value. Here is what the entry tiers buy, translated into sales of a $249 product. Prices read off each vendor's own pricing page on 12 September 2026.
| Vendor / plan | Price | Cap on affiliate revenue | That's how many $249 sales |
|---|---|---|---|
| Affonso Launch | $15/mo (yearly billing; $19 monthly) | $1,000/mo | 4 |
| Affonso Growth | $29/mo | $10,000/mo | 40 |
| Affonso Elite | $79/mo | $30,000/mo | 120 |
| Rewardful Starter | $49/mo | $7,500/mo | 30 |
| Rewardful Growth | $99/mo | $15,000/mo | 60 |
| Tolt Basic | $69/mo | $10,000/mo | 40 |
| Tolt Growth | $99/mo | $20,000/mo | 80 |
Now put that next to what the program already costs you. Our rate is 30% of the net, which on the $249 tier is $74.70 a sale. At 40 sales a month you owe partners $2,988 in commissions. Affonso's Growth plan at $29 is under one percent of that figure. Rewardful's Growth plan at $99 is a bit over three percent.
Software is the rounding error. The build is not.
Buy it, unless one of three things is true
That table is the honest case against everything above. Affonso, Rewardful and Tolt all do more than our 2,600 lines do: they pay the affiliates, they run self-referral and fraud detection, they collect tax forms, and two of them will go looking for affiliates on your behalf. On cost alone, buying wins at every volume we modelled.
Build only if one of these actually applies to you:
- Your payment provider isn't supported. This is the real fork, and it is binary. Rewardful's FAQ says "We currently support only Stripe or Paddle." Tolt's says "at the moment you can only integrate Tolt if your SaaS/app is using either Stripe or Paddle." Affonso lists Stripe, Paddle Billing, Polar, Creem and Dodo — which, for anyone on Polar, largely dissolves the build case that existed a year ago.
- You cannot issue that standing credential. If a never-expiring token with write access to customer records fails your security review, the decision is made for you.
- Your commission rule isn't a percentage of an order. Per-lead payouts, payouts contingent on a listing staying live, tiered rates that depend on something only your database knows — these bend vendor models badly.
Cost per sale is not the number that decides it. The wider version of that argument, with a three-year table, is in build vs buy for internal catalogs, and the method for turning "we'll build it" into hours before you commit is in estimating engineering hours for a directory MVP.
What to do before you write a line of it
- Open your payment provider's integration page and each vendor's. If one supports you, the rest of this list is optional.
- Write the commission rate, hold period and payout minimum as code constants. Values that determine what people are owed should need a code review and a deploy, not a dashboard toggle.
- Decide your commission base — pre-tax net or gross total — and put the reason in a comment above it. Someone will change it otherwise.
- Create the unique index on the provider's order id before you write the handler that inserts into it.
- Set the hold period from your actual refund window, not from a round number.
- Ask your accountant which form a partner outside your country generates, then decide whether you are willing to own that in January.
Build the ledger first and the portal second. The dashboard is a week of React over a schema that is either correct or quietly wrong, and partners forgive a plain interface far longer than they forgive one wrong payment.