Skip to content
← All posts
· Delta1 Labs KeyrightLicensingBilling

Refund proration that counts days exactly

A partial refund arrives mid-term and you have to shorten the license to match. The dangerous part is not the money — it is the day count. Use an exclusive day span, or forget that a term covers both its endpoints, and the proration is off by one: the customer is credited for a day they used, or docked a day they paid for. This post builds Keyright's term-refund proration on DateOnly and decimal — the inclusive day count, the effective date pinned to a UTC calendar day, a credit rounded one consistent way, and an idempotency key on the refund id so a retried webhook cannot claw back twice.

A partial refund is a licensing event wearing a billing costume. The money moves in your payment processor, but the obligation it changes lives in Keyright: a customer paid for a year, used four months, and got the rest refunded — so the license has to stop being valid at the right moment, and “the right moment” is a day-count problem that is deceptively easy to get wrong by exactly one day.

The money is the easy half. Your processor already knows how much to return. The hard half is translating “they are getting 8 months back” into a new expiry date and a credit figure that agree with each other, survive a webhook retry, and do not quietly hand the customer a free day. Get the arithmetic wrong and nobody notices until an auditor or an annoyed customer does the subtraction themselves.

The off-by-one that gives away a day

A software term covers both of its endpoints. A license dated January 1 through December 31 is valid for the whole of the first day and the whole of the last day — 365 covered days. The instinct is to get the term length by subtracting the dates:

int termDays = (termEnd.ToDateTime(default) - termStart.ToDateTime(default)).Days; // 364 — WRONG

That is 364. It is a span, the distance between two points, not a count of the days inside the term. Used as the denominator of a per-day price it makes each day slightly too expensive, and — far worse — it collides with how you count the used and refunded portions. If you compute “days used” and “days refunded” inclusively (the natural way: the used portion also covers both of its ends), the two portions share the boundary day, they sum to 366, and the customer is credited for a day they actually consumed. One license, one free day; across a refund batch, a real number.

The cure is to count every quantity the same way. DateOnly.DayNumber is the proleptic Gregorian day index, so an endpoint-inclusive count is one subtraction and a + 1:

int totalDays = termEnd.DayNumber - termStart.DayNumber + 1;   // Jan 1..Dec 31 -> 365

Where coverage actually ends

The refund has an effective date — the calendar day from which the customer no longer paid for coverage. The last day they keep is the day before that. So the new expiry is effectiveDate.AddDays(-1), and every other quantity falls out of it:

termStartfirst covered dayeffectiveDaterefund takes effecttermEndlast paid dayusedDays — keptrefundedDays — creditednewExpiry = effectiveDate.AddDays(-1) — the boundary day is used, not refunded
The effective date splits the term; the day before it is the last kept day, so used and refunded days never overlap.

Now the whole proration is a handful of exact integer and decimal operations. Money is decimal throughout — a yearly price divided by 365 has no finite binary representation, so computing the per-day rate in double and multiplying it back by a day count drifts a cent either way, non-deterministically:

public readonly record struct Proration(int RefundedDays, decimal Credit, DateOnly NewExpiry);

public static Proration ProrateTermRefund(
    DateOnly termStart,      // first covered day, inclusive
    DateOnly termEnd,        // last covered day, inclusive
    DateOnly effectiveDate,  // refund effective calendar day (UTC)
    decimal termPrice)
{
    int totalDays = termEnd.DayNumber - termStart.DayNumber + 1;   // both endpoints count

    DateOnly newExpiry = effectiveDate.AddDays(-1);
    if (newExpiry > termEnd) newExpiry = termEnd;                  // refund after term ended: nothing left
    if (newExpiry < termStart) newExpiry = termStart.AddDays(-1);  // whole term refunded: zero kept

    int usedDays = Math.Max(0, newExpiry.DayNumber - termStart.DayNumber + 1);
    int refundedDays = totalDays - usedDays;                       // the two halves sum to totalDays, exactly

    decimal perDay = termPrice / totalDays;                        // decimal division, exact enough
    decimal credit = decimal.Round(perDay * refundedDays, 2, MidpointRounding.ToEven);

    return new Proration(refundedDays, credit, newExpiry);
}

The invariant to check in a test is usedDays + refundedDays == totalDays, with no + 2 and no - 0 hiding a boundary error. Because newExpiry is derived from effectiveDate and usedDays is derived from newExpiry, the two portions are guaranteed to partition the term — there is no day that is both used and refunded, and none that is neither.

Re-issuing without letting the old key linger

Computing the new expiry is not the operation; applying it is. The license the customer holds is a signed document, and shortening its term means the issuing service signs a new license with the shorter termEnd — the old one does not mutate in place. The client picks up the re-issued license on its next refresh. The one thing you must prevent is the customer replaying the cached copy of the longer license they were legitimately holding a minute ago. That is what the license epoch is for: bump it on re-issue and the client’s anti-rollback high-water mark refuses any license whose epoch is below the highest it has seen.

And because a payment processor will deliver the same refund webhook more than once, the whole thing has to be idempotent — keyed on the processor’s refund id, so a retry is a no-op rather than a second clawback:

public async Task<Proration> ApplyRefundAsync(RefundEvent e, CancellationToken ct)
{
    // A retried webhook finds the refund id already applied and returns the stored result.
    if (await _store.TryGetAppliedAsync(e.RefundId, ct) is { } prior)
        return prior;

    Grant grant = await _store.GetGrantAsync(e.LicenseId, ct);

    // The refund is effective at the processor's instant, NOT at wall-clock "now".
    DateOnly effective = DateOnly.FromDateTime(e.EffectiveUtc);
    Proration p = ProrateTermRefund(grant.TermStart, grant.TermEnd, effective, grant.TermPrice);

    Grant reissued = grant with
    {
        TermEnd = p.NewExpiry,
        Epoch   = grant.Epoch + 1,   // supersede the longer cached license
    };

    // Sign + persist the shortened grant and record the proration against the refund id, atomically.
    await _store.CommitRefundAsync(e.RefundId, reissued, p, ct);
    return p;
}

Two details are load-bearing. The effective date comes from the refund event, not DateTime.UtcNow — a webhook that arrives two days late must still prorate as of when the refund actually happened, or the customer loses two days they were owed. And DateOnly.FromDateTime(e.EffectiveUtc) pins the day to UTC; if you let the server’s local zone decide the calendar day, a refund issued near midnight lands on different days for different servers, and the proration becomes non-reproducible.

Partial seats instead of partial term

The same arithmetic prorates a seat refund — a customer returns 2 of 5 seats mid-term — by swapping the dimension. Instead of shortening termEnd, reduce the seat count and credit the returned seats over the remaining days: perDay = (termPrice / seatCount) / totalDays, times refundedDays, times the returned seat count. The day-count discipline is identical; only the thing being multiplied changes. If the customer is already using more seats than the new cap, you do not yank active seats mid-session — you let them drain down to the new limit as sessions end.

Where it breaks

The honest limits are worth stating. Proration is day-granular; if your terms need sub-day precision you prorate on instants and carry the time component, but most software terms bill by the day and DateOnly is the right grain. A non-refundable setup fee or a minimum term is a policy that runs before proration — subtract it from the refundable base, do not try to encode it in the day count. Already-consumed metered credits are not on the table: proration only touches calendar days still ahead of the effective date, so a customer who burned their quota and then refunded keeps nothing to claw back, which is the correct and defensible outcome. And the rounding direction is a policy you must choose once and apply everywhere — MidpointRounding.ToEven is a reasonable default, but whichever you pick, your credit figure and your term shortening have to be computed from the same day count or they will disagree and someone will notice.

The takeaway

A mid-term refund is not a money problem with a licensing footnote; it is a day-count problem with a money footnote. Count the term endpoint-inclusive, derive the new expiry as the day before the effective date, keep every figure in decimal, pin the effective day to UTC, and make the whole operation idempotent on the refund id so a retried webhook changes nothing twice. Do that and the credit the customer sees, the expiry the SDK enforces, and the entry in your ledger all describe the same number of days — which is the only state in which a refund is actually finished.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.