Inside Open Source Billing: Lago, Kill Bill and Hyperswitch

14 min read

The problem

Razorpay tells you what a subscription does. It does not show you how. You get states, webhooks and a dashboard, and the engine that decides "charge today, retry tomorrow, halt on day four" stays a black box.

That is fine until you want to build one. Then every small question turns into a real design choice. Where does a trial live? Who decides that an upgrade is billed now but a downgrade waits? How do you stop a renewal from charging someone twice when your server restarts halfway through?

The good news: people have already answered these questions in public code. This part reads three open source projects at pinned release tags and pulls out the pieces we need for our own clone in the next part.

  • Lago (lago-api, tag v1.57.0), a billing engine in Ruby on Rails. Our main reference.
  • Kill Bill (tag killbill-0.25.7), an older Java billing platform. We use it for its retry schedule and its overdue ladder.
  • Hyperswitch (tag v1.131.0), a payments switch in Rust from Juspay. We use it for mandates and signed webhooks.

What we did and what we did not

We cloned each repo at its tag and read the source. That is all. We did not build, install or run any of these servers. No Docker, no database, no test suite. So nothing below is a claim about how these systems behave at runtime. It is a claim about what the code at that commit says.

RepoTagCommitLicence
getlago/lago-apiv1.57.0af1b5856563440f4244cab0ebcdaf48710ccecf2AGPL-3.0
killbill/killbillkillbill-0.25.78e9106f92d40f5d8dc2fd9dccc4695600133be1aApache-2.0
juspay/hyperswitchv1.131.06eaaaa2f42831ffe57931a3ab175397a24afb413Apache-2.0

The licence column matters. Lago's LICENSE file is the GNU Affero General Public License, version 3. Quoting short pieces with credit to explain them is one thing. Copying the engine into our own project is another. So the clone in part 8 is written from scratch. It borrows ideas, not code.

Every excerpt below is copied verbatim from the file at that commit, with a link to the exact lines.

Lago: states first

Start with the list of states. In Lago it is one array on the model.

lago-api v1.57.0, app/models/subscription.rb L58-66

ruby
  STATUSES = [
    :pending,
    :active,
    :terminated,
    :canceled,
    :incomplete
  ].freeze

  CANCELLATION_REASONS = {payment_failed: "payment_failed", timeout: "timeout", manual: "manual"}.freeze

Five states, and none of them is called halted. That is the first lesson. Razorpay's states (created, authenticated, active, pending, halted, cancelled, completed, expired, paused) are a product decision, not a law of nature.

Here is what Lago's five mean, as far as the code shows. pending is a subscription that exists but has not started yet, such as a downgrade waiting for the next billing day. incomplete is a subscription held back by an activation rule. In app/services/subscriptions/activate_service.rb the gate_subscription method marks it incomplete and bills it first if it is payment_gated?. active is running. terminated ran and ended. canceled was stopped before it ever ran.

The cancellation reasons are a nice touch. If an activation rule runs out of time, activation_rules/expire_service.rb cancels the subscription with reason timeout. That is close to Razorpay's expired: the customer never finished the setup in time.

Each transition is a tiny method. mark_as_terminated! at L134-137 sets terminated_at ||= timestamp and flips the enum. The ||= means "only if not already set", so calling it twice does not move the date. Small, boring and safe. Good habits for a billing system.

The trial

Lago keeps the free trial on the plan, as a number of days.

lago-api v1.57.0, app/models/subscription.rb L190-194

ruby
  def trial_end_date
    return unless plan.has_trial?

    initial_started_at.to_date + plan.trial_period.days
  end

Note initial_started_at, not started_at. If you upgrade halfway through your trial, the trial does not restart. The clock is tied to the first subscription in the chain.

So who notices that the trial ended? A periodic job.

lago-api v1.57.0, app/services/subscriptions/free_trial_billing_service.rb L18-30

ruby
          if subscription.plan.pay_in_advance?
            BillSubscriptionJob.perform_later(
              [subscription],
              timestamp,
              invoicing_reason: :subscription_starting,
              skip_charges: true
            )
          end
        end

        subscription.update!(trial_ended_at: subscription.trial_end_utc_date_from_query)

        SendWebhookJob.perform_later("subscription.trial_ended", subscription)

The extra end closes a guard just above this excerpt: the job skips billing if the subscription was already billed today or on day one. Then it bills the first period (if the plan is paid in advance), stamps trial_ended_at, and sends a subscription.trial_ended webhook.

That is the "trial converts" moment from part 1. On Razorpay the same moment is the first recurring charge at start_at, after the customer authorised a small amount up front.

Lago: what to bill, and when

Every invoice line for a subscription goes through one method that picks a formula.

lago-api v1.57.0, app/services/fees/subscription_service.rb L111-123

ruby
    def compute_amount
      # NOTE: bill for the last time a subscription that was upgraded
      return terminated_amount if should_compute_terminated_amount?

      # NOTE: bill for the first time a subscription created after an upgrade
      return upgraded_amount if should_compute_upgraded_amount?

      # NOTE: bill a subscription on a full period
      return full_period_amount if should_use_full_amount?

      # NOTE: bill a subscription for the first time (or after downgrade)
      first_subscription_amount
    end

Four cases, checked in order. This is the shape you want: one place that answers "how much for this period", with each special case named.

Proration on upgrade

The upgrade case carries its own explanation in a comment, which is rare and lovely.

lago-api v1.57.0, app/services/fees/subscription_service.rb L236-244

ruby
      # NOTE: Subscription is upgraded from another plan
      #       We only bill the days between the upgrade date and the end of the period
      #       A credit note will apply automatically the amount of days from previous plan that were not consumed
      #
      #       The amount to bill is computed with:
      #       **nb_day** = number of days between upgrade and the end of the period
      #       **day_cost** = (plan amount_cents / full period duration)
      #       amount_to_bill = (nb_day * day_cost)
      number_of_day_to_bill * single_day_price(subscription)

Charge the new plan per day for the days left. Give back the unused days of the old plan as a credit note. Razorpay's update page describes the same idea: a per-day amount, the difference charged or refunded, refunds through a Credit Note. Part 6 walked through the numbers.

Upgrade now, downgrade later

How does Lago know which way you are moving?

lago-api v1.57.0, app/services/subscriptions/create_service.rb L136-148

ruby
    def upgrade?
      return false unless current_subscription
      return false if plan.id == current_subscription.plan.id

      plan.yearly_amount_cents >= current_subscription.plan.yearly_amount_cents
    end

    def downgrade?
      return false unless current_subscription
      return false if plan.id == current_subscription.plan.id

      plan.yearly_amount_cents < current_subscription.plan.yearly_amount_cents
    end

It compares the yearly price. That neatly handles "monthly Rs 499 to yearly something" without special cases. An upgrade applies right away. A downgrade waits, as the comment in plan_downgrade_service.rb L31-33 says: "When downgrading a subscription, we keep the current one active until the next billing day." The new subscription is created with status: :pending.

Razorpay exposes the same choice as a parameter, schedule_change_at, with now or cycle_end. Lago bakes the policy in. For a clone, the Lago policy is a sensible default: customers who pay more get it now, customers who pay less keep what they paid for until the period ends.

Invoices and coupons

An invoice in Lago has two separate lifecycles.

lago-api v1.57.0, app/models/invoice.rb L102-111

ruby
  INVOICE_TYPES = %i[subscription add_on credit one_off advance_charges progressive_billing contract].freeze
  PAYMENT_STATUS = %i[pending succeeded failed].freeze
  TAX_STATUSES = {
    pending: "pending",
    succeeded: "succeeded",
    failed: "failed"
  }.freeze

  VISIBLE_STATUS = {draft: 0, finalized: 1, voided: 2, failed: 4, pending: 7}.freeze
  INVISIBLE_STATUS = {generating: 3, open: 5, closed: 6, deleted: 8}.freeze

status is the document: draft, finalized, voided. payment_status is the money: pending, succeeded, failed. Keeping them apart avoids a common mess where "paid" and "sent" end up in one column. Add-ons show up here too, as the add_on and one_off invoice types, billed through app/services/invoices/create_one_off_service.rb.

Coupons are just as compact.

lago-api v1.57.0, app/services/applied_coupons/amount_service.rb L26-40

ruby
      if applied_coupon.coupon.percentage?
        discounted_value = base_amount_cents * applied_coupon.percentage_rate.fdiv(100)

        return (discounted_value >= base_amount_cents) ? base_amount_cents : discounted_value.round
      end

      if applied_coupon.recurring? || applied_coupon.forever?
        return base_amount_cents if applied_coupon.amount_cents > base_amount_cents

        applied_coupon.amount_cents
      else
        return base_amount_cents if applied_coupon.remaining_amount > base_amount_cents

        applied_coupon.remaining_amount
      end

Percentage or fixed. Recurring, forever, or once. And every branch caps the discount at the amount being billed, so an invoice never goes below zero. A one-time fixed coupon spends down a remaining_amount across invoices. That cap is the line people forget when they write their own.

Lago: webhooks that prove who sent them

Part 4 showed how Razorpay signs a webhook. Lago does the same job as the sender.

lago-api v1.57.0, app/models/webhook.rb L57-70

ruby
  def generate_headers
    signature = case webhook_endpoint.signature_algo&.to_sym
    when :jwt
      jwt_signature
    when :hmac
      hmac_signature
    end

    {
      "X-Lago-Signature" => signature,
      "X-Lago-Signature-Algorithm" => webhook_endpoint.signature_algo.to_s,
      "X-Lago-Unique-Key" => id
    }
  end

lago-api v1.57.0, app/models/webhook.rb L83-86

ruby
  def hmac_signature
    hmac = OpenSSL::HMAC.digest("sha-256", organization.hmac_key, payload.to_json)
    Base64.strict_encode64(hmac)
  end

HMAC SHA256 over the JSON body, keyed with a per-organisation secret, base64 encoded, sent as X-Lago-Signature. Razorpay uses the same algorithm with its own header, X-Razorpay-Signature. The other header, X-Lago-Unique-Key, is the webhook's own id. It plays the role of Razorpay's x-razorpay-event-id: the receiver stores it and drops repeats.

What if the receiver is down? Lago tries again, with a growing wait.

lago-api v1.57.0, app/services/webhooks/send_http_service.rb L97-101

ruby
    def wait_value
      # NOTE: This is based on the Rails Active Job wait algorithm
      executions = webhook.retries
      ((executions**4) + (Kernel.rand * (executions**4) * 0.15)) + 2
    end

The wait is the retry count to the fourth power, plus up to 15% random jitter, plus 2 seconds, in seconds. The jitter spreads retries out so a thousand failed webhooks do not all hit your server in the same second. The number of attempts comes from LAGO_WEBHOOK_ATTEMPTS, default 3 (L63-65). Razorpay's own policy is different: exponential backoff for 24 hours after the event, then the webhook gets disabled.

The receiving side, with an Indian gateway

Lago also receives webhooks from payment gateways. Its Cashfree handler is a clean example of checking a signature.

lago-api v1.57.0, app/services/payment_providers/cashfree/handle_incoming_webhook_service.rb L28-36

ruby
        secret_key = payment_provider_result.payment_provider.client_secret
        data = "#{timestamp}#{body}"
        gen_signature = Base64.strict_encode64(OpenSSL::HMAC.digest("sha256", secret_key, data))

        unless ActiveSupport::SecurityUtils.secure_compare(gen_signature, signature.to_s)
          return result.service_failure!(code: "webhook_error", message: "Invalid signature")
        end

        PaymentProviders::Cashfree::HandleEventJob.perform_later(organization:, event: body)

Three habits worth stealing. It signs the raw body (with a timestamp in front), not a re-parsed object. It compares with secure_compare, a constant-time compare, so response timing does not leak how many characters matched. And it only queues the event after the check passes, handing the real work to a background job so the endpoint answers fast. Razorpay counts no answer within 5 seconds as a failure, so that last habit is not optional.

Lago: never charge twice

Idempotency is the quiet hero of billing. Lago builds keys like this.

lago-api v1.57.0, app/services/idempotency_records/key_service.rb L19-23

ruby
    def call
      string_to_digest = key_parts.sort.map { |k, v| "#{k}#{v}" }.join(SEPARATOR)
      result.idempotency_key = Digest::SHA256.digest("#{KEY_VERSION}#{SEPARATOR}#{string_to_digest}")
      result
    end

Take the facts that make an operation unique, sort them, join them, hash them. Then insert that hash into a table with a unique index. The helper in app/support/idempotency.rb wraps this in Idempotency.transaction, so the business write and the key write commit together or not at all. If a second worker tries the same operation, the database refuses the insert. Not the app, the database. That is the only place a race can be settled for real.

Kill Bill: the retry ladder

Lago's renewal failures go through dunning campaigns with max_attempts and days_between_attempts. Kill Bill has something more direct for dunning: a list of days.

killbill-0.25.7, util/src/main/java/org/killbill/billing/util/config/definition/PaymentConfig.java L31-34

java
    @Config("org.killbill.payment.retry.days")
    @Default("8,8,8")
    @Description("Specify the number of payment retries along with the interval in days between payment retries when payment failures occur")
    List<Integer> getPaymentFailureRetryDays();

Three retries, 8 days apart, by default. A few lines down, the same file has a separate setting for gateway trouble: org.killbill.payment.failure.retry.start.sec, default 300, described as for when the "gateway is down, transient error". Two kinds of failure, two clocks. A declined card is the customer's problem and needs days. A gateway timeout is your problem and needs minutes.

Here is how the next date gets picked.

killbill-0.25.7, payment/.../invoice/InvoicePaymentControlPluginApi.java L596-609

java
        final int attemptsInState = getNumberAttemptsInState(purchasedTransactions, TransactionStatus.PAYMENT_FAILURE);
        final int retryCount = (attemptsInState - 1) >= 0 ? (attemptsInState - 1) : 0;
        if (retryCount < retryDays.size()) {
            final int retryInDays;
            final DateTime nextRetryDate = internalContext.getCreatedDate();
            try {
                retryInDays = retryDays.get(retryCount);
                result = nextRetryDate.plusDays(retryInDays);
                log.debug("Next retryDate={}, retryInDays={}, retryCount={}, now={}", result, retryInDays, retryCount, internalContext.getCreatedDate());
            } catch (final NumberFormatException ex) {
                log.error("Could not get retry day for retry count {}", retryCount);
            }
        }
        return result;

Count the failures, look up the next gap, add it. When the list runs out, result stays null and there are no more retries. That null is exactly where a Razorpay-style engine flips a subscription from pending to halted.

The retry itself is a small state machine in payment/src/main/resources/org/killbill/billing/payment/retry/RetryStates.xml: states INIT, SUCCESS, RETRIED, ABORTED, one operation OP_RETRY. Success goes to SUCCESS, failure goes to RETRIED, an exception goes to ABORTED. You could paste that table into a Python dict.

Razorpay card retries versus Kill Bill default retry days

Same idea, very different clocks. Razorpay's retries page for cards says it retries on T+1, T+2 and T+3 and then halts, and its test mode page agrees: four failures in a row and the subscription is halted. Kill Bill's default, if every attempt fails, runs out of retries around day 24. Neither is "right". It depends on how long your customers take to top up a card.

Overdue: Kill Bill's version of halted

When retries run out, Kill Bill's overdue module can cut access. It turns an overdue state into three flags.

killbill-0.25.7, overdue/.../applicator/OverdueStateApplicator.java L290-300

java
    private boolean blockChanges(final OverdueState nextOverdueState) {
        return nextOverdueState.isBlockChanges() || nextOverdueState.isDisableEntitlementAndChangesBlocked();
    }

    private boolean blockBilling(final OverdueState nextOverdueState) {
        return nextOverdueState.isDisableEntitlementAndChangesBlocked();
    }

    private boolean blockEntitlement(final OverdueState nextOverdueState) {
        return nextOverdueState.isDisableEntitlementAndChangesBlocked();
    }

Block plan changes, block billing, block access. The entitlement code then reads those flags.

killbill-0.25.7, entitlement/.../engine/core/DefaultEventsStream.java L503-508

java
            else if (entitlementEffectiveStartDateTime.compareTo(utcNow) > 0) {
                entitlementState = EntitlementState.PENDING;
            } else {
                // Gather states across all services and check if one of them is set to 'blockEntitlement'
                entitlementState = (currentStateBlockingAggregator != null && currentStateBlockingAggregator.isBlockEntitlement() ? EntitlementState.BLOCKED : EntitlementState.ACTIVE);
            }

Kill Bill does not store "the state" in one column. It works it out from events every time: not started yet is PENDING, blocked by some service is BLOCKED, otherwise ACTIVE. BLOCKED is the closest thing to Razorpay's halted.

One warning before you copy Kill Bill's webhooks. Its push notifications in PushNotificationListener.java L132-138 set only User-Agent and Content-Type headers. A search of that file for "hmac" or "signature" finds nothing. Core push notifications are not signed, so anyone who learns the callback URL could post a fake event. Lago is the better teacher here.

Hyperswitch: mandates and stronger signatures

Hyperswitch sits on the payments side. Its mandate model is the clearest of the three.

hyperswitch v1.131.0, crates/api_models/src/payments.rs L2620-2627

rust
pub enum MandateType {
    /// If the mandate should only be valid for 1 off-session use
    #[smithy(value_type = "MandateAmountData")]
    SingleUse(MandateAmountData),
    /// If the mandate should be valid for multiple debits
    #[smithy(value_type = "Option<MandateAmountData>")]
    MultiUse(Option<MandateAmountData>),
}

A mandate is single use or multi use. Its MandateAmountData (L2588 in the same file) carries amount, documented as "The maximum amount to be debited for the mandate transaction", plus currency, start_date and end_date. That is the same shape RBI asks for: a validity period and, for variable mandates, a maximum the customer sets. Hyperswitch does not encode RBI's rules (AFA, the pre-debit notice, the limits). Those come from part 2.

MandateStatus in crates/common_enums/src/enums.rs is Active, Inactive, Pending, Revoked. Revoking is a call to the connector followed by a status update, and doing it twice is refused.

hyperswitch v1.131.0, crates/router/src/core/mandate.rs L158-163

rust
        common_enums::MandateStatus::Revoked => {
            Err(errors::ApiErrorResponse::MandateValidationFailed {
                reason: "Mandate has already been revoked".to_string(),
            }
            .into())
        }

Outgoing webhooks use a bigger hash than Lago.

hyperswitch v1.131.0, crates/router/src/core/webhooks/types.rs L54-65

rust
        let signature = payment_response_hash_key
            .map(|key| {
                common_utils::crypto::HmacSha512::sign_message(
                    &common_utils::crypto::HmacSha512,
                    key.as_ref(),
                    webhook_signature_payload.as_bytes(),
                )
            })
            .transpose()
            .change_context(errors::WebhooksFlowError::OutgoingWebhookSigningFailed)
            .attach_printable("Failed to sign the message")?
            .map(hex::encode);

HMAC SHA512, hex encoded, sent in a header named X-Webhook-Signature-512 (crates/router/src/lib.rs L153). Same pattern as Lago and Razorpay, longer digest.

The honest gap: UPI AutoPay

You might hope Hyperswitch ships a ready Razorpay recurring integration. At this tag, it does not.

hyperswitch v1.131.0, crates/hyperswitch_connectors/src/connectors/razorpay.rs L802-811

rust
        razorpay_supported_payment_methods.add(
            enums::PaymentMethod::Upi,
            enums::PaymentMethodType::UpiCollect,
            PaymentMethodDetails{
                mandates: common_enums::FeatureStatus::NotSupported,
                refunds: common_enums::FeatureStatus::Supported,
                supported_capture_methods,
                specific_features: None,
            },
        );

UPI Collect only, mandates: NotSupported. The connector info at L821 sets integration_status to ConnectorIntegrationStatus::Sandbox, and its incoming webhook methods (L772-794) return WebhooksNotImplemented. A case-insensitive search for "autopay" across the Rust crates found two files: a PayNearMe connector comment saying mandates and autopay are out of scope, and an unrelated payout retry config. Neither is a UPI AutoPay mandate flow. So Hyperswitch teaches the general mandate model, not UPI AutoPay itself.

Putting the states side by side

Every project names its states differently. This table is our own mapping, built from reading the code. None of these projects claims to match Razorpay, and several rows are "closest match", not equal.

Razorpay stateLagoKill BillHyperswitch
createdincomplete (held by an activation rule)PENDING (start in future)SubscriptionStatus::Created; mandate Pending
authenticated (trial running)active with in_trial_period? trueACTIVE in a TRIAL phaseSubscriptionStatus::Trial; mandate Active
activeactiveACTIVEActive
pending (charge failed, retrying)active, invoice payment_status failed, dunning runningACTIVE, payment retry in RETRIEDUnpaid (closest name)
haltedactive with payment_overdue invoices after dunning_campaign.finishedBLOCKED via overduerevenue recovery Terminated
cancelledterminated (or canceled if it never ran)CANCELLEDCancelled
completedterminated at its end dateEXPIREDno direct match
expiredcanceled with reason timeoutno direct matchno direct match
pausedno statusBLOCKED via a blocking statePaused

Two things jump out. Lago has no halted state at all; it keeps the subscription active and marks invoices overdue, then leaves the next step to you. And Kill Bill computes state instead of storing it. For a small clone, storing it with an explicit list of allowed moves is easier to test. Hyperswitch's SubscriptionStatus lives in crates/common_enums/src/enums.rs, and its subscriptions crate hands billing to an external processor, so treat that column as vocabulary.

Here is the state machine our clone will implement, with the project that inspired each move.

stateDiagram-v2
    [*] --> created: create subscription
    created --> authenticated: mandate approved (Hyperswitch MandateStatus)
    authenticated --> active: trial ends, first charge (Lago FreeTrialBillingService)
    active --> active: renewal paid
    active --> pending: renewal charge fails
    pending --> active: retry succeeds (Kill Bill RETRIED to SUCCESS)
    pending --> halted: retry list used up (Kill Bill returns null)
    halted --> active: customer pays or changes method
    active --> paused: pause (Kill Bill blocking state)
    paused --> active: resume
    active --> cancelled: cancel now or at cycle end (Lago TerminateService)
    halted --> cancelled: cancel
    active --> completed: last cycle paid
    created --> expired: never authorised in time (Lago reason timeout)
    cancelled --> [*]
    completed --> [*]
    expired --> [*]

One renewal, end to end

Put the pieces in order and you get one renewal day. Each step names the code that does the same job.

sequenceDiagram
    participant S as Scheduler
    participant B as Billing engine
    participant G as Gateway
    participant W as Webhook sender
    participant M as Merchant server
    S->>B: subscription due today
    B->>B: invoice lines, proration, coupon (Lago Fees and AppliedCoupons)
    B->>B: claim key sub_id plus cycle (Lago IdempotencyRecords)
    B->>G: charge against mandate (Hyperswitch MandateId)
    alt declined
        G-->>B: failure
        B->>B: next retry date, or halt if none (Kill Bill retry days)
        B->>W: subscription.pending or subscription.halted
    else paid
        G-->>B: success
        B->>W: invoice.paid
    end
    W->>W: HMAC SHA256 over raw body (Lago hmac_signature)
    W->>M: POST body, signature, unique event id
    M->>M: recompute, constant time compare (Lago Cashfree secure_compare)
    M->>M: drop if event id already seen
    M-->>W: 2xx, or retry later with jitter (Lago wait_value)

The event names on the right of that diagram (subscription.pending, subscription.halted, invoice.paid) are Razorpay's, from its webhook events list. Our clone will use the same names so the code in part 8 reads like the Razorpay docs.

What we take into the clone

From Lago: an explicit list of states, a trial stored as days on the plan, one function that decides how much to bill, "upgrade now, downgrade at period end", invoices with separate document and payment status, coupons capped at the bill, HMAC SHA256 signed webhooks with a unique id, jittered retries, and idempotency enforced by a unique index.

From Kill Bill: a retry schedule as a plain list of days, where running off the end of the list means halted. Separate handling for "card declined" and "gateway down". Access blocking as a flag, not a deleted row.

From Hyperswitch: a mandate with a maximum amount, a start and end date, and a revoke that cannot happen twice.

And from all three: none of them is Razorpay, and none of them gives us UPI AutoPay for free.

What's next

Reading is not running. In part 8 we write our own small clone from scratch and actually run it: a trial converts, a renewal fails, retries, then halts, and a replayed webhook gets rejected, with the real output pasted in.

Sources