Product

Dual-Currency SaaS Billing in Go: Multi-Tenant Pricing with Dynamic FX Indexing

C
Chidi OkekeVP of Frontend Engineering
October 24, 202611 min read
Dual-Currency SaaS Billing in Go: Multi-Tenant Pricing with Dynamic FX Indexing

When the Nigerian Naira devalued by over 100% in 12 months, SaaS companies quoting fixed Naira prices saw their USD margins evaporate, while those charging raw USD suffered 60% churn. Here is how we built a dynamic FX-indexed billing engine in Go that protects margins without alienating local subscribers.

In June 2023, a Lagos-based B2B logistics client running on our custom platform infrastructure hit a financial wall. Their monthly recurring revenue (MRR) stood at ₦45,000,000. Twelve months prior, that equaled roughly $97,000. Their infrastructure bills—AWS EC2 instances, Datadog observability, and OpenAI API calls—amounted to roughly $28,000 per month. They were wildly profitable.

Then the Central Bank of Nigeria unified the FX windows, and the Naira collapsed from ₦460/$ to over ₦1,400/$. Overnight, their ₦45,000,000 MRR shrank to $32,000. After paying AWS and Datadog, their gross margin plummeted from 71% to under 12%. Payroll was in Naira, but inflation was pushing engineering salaries up by 40%.

The founders attempted a panic migration: they converted all subscription plans directly to USD using Stripe Billing. Within 45 days, churn spiked to 62%.

Why? Nigerian commercial banks had imposed strict $20 to $100 monthly international spending limits on local Mastercard and Visa debit cards. Local corporate cards were rejected at the gateway level by offshore merchant processors. The company couldn't collect money from willing enterprise customers simply because the payment pipe broke.

Defaulting to pure USD billing in West Africa is product suicide for mid-market B2B software. Flat Naira pricing is company suicide during hyper-devaluation. The only viable middle ground is Dynamic FX Indexing: denominating base plan value in a stable baseline currency (USD), settling in local fiat (NGN) via local rails like Paystack, and applying an anti-volatility buffer so customers aren't hit with wild intra-month billing shocks.

Here is how we designed, implemented, and deployed an FX-indexed multi-tenant billing engine in Go.

Pricing Architecture Matrix: Dollars vs. Naira vs. Indexed Rails

Before writing code, product leaders must understand the operational trade-offs of each pricing strategy for African SaaS companies:

| Pricing Strategy | Customer Friction | Currency Risk | Card Processing Success Rate | Margin Predictability | | :--- | :--- | :--- | :--- | :--- | | Flat Naira (NGN) | Very Low | Severe (Uncapped downside) | 94% - 98% (Paystack/Flutterwave) | Terrible (Infrastructure costs in USD) | | Pure USD (Stripe) | Extreme (Bank card blocks) | Zero | 25% - 40% (High decline rates) | High | | Dynamic FX-Indexed NGN | Moderate | Mitigated (Capped risk) | 92% - 96% (Local NGN processing) | High |

Dynamic FX Indexing operates on three core principles:

  1. USD Anchor Baseline: The product price is pegged to USD (e.g., $100/month per seat) inside the application ledger.
  2. 30-Day Trailing FX Window: To prevent customer outrage caused by sudden daily currency fluctuations, invoices calculate the charge rate using a 30-day simple moving average (SMA) of the official interbank rate.
  3. Monthly Price Ceiling (+/- 15% Cap): The maximum price jump between two consecutive billing cycles is capped at 15%. If the currency drops 30% in a single week, the platform absorbs the delta over two billing cycles rather than passing a shock bill to the customer.

Building the FX-Indexed Ledger Engine in Go

Let's construct the billing engine. We need a service that handles exchange rate ingestion, calculates the dynamically indexed rate with smoothing caps, and interfaces with the Paystack Transaction API for local tokenized debiting.

package billing

import (
	"context"
	"fmt"
	"math"
	"time"
)

type Currency string

const (
	USD Currency = "USD"
	NGN Currency = "NGN"
)

type Plan struct {
	ID            string
	Name          string
	BasePriceUSD  float64 // Anchor price in USD cents (e.g. 10000 = $100.00)
	MaxCycleCap   float64 // Max allowable percentage change per cycle (e.g. 0.15 for 15%)
}

type Subscription struct {
	ID               string
	TenantID         string
	PlanID           string
	PaystackAuthCode string // Tokenized card authorization
	LastChargedRate  float64 // FX rate (NGN per 1 USD) used in the previous cycle
}

type FXRateRepository interface {
	GetTrailingSMA(ctx context.Context, days int) (float64, error)
}

type InvoiceCalculator struct {
	fxRepo FXRateRepository
}

func NewInvoiceCalculator(fxRepo FXRateRepository) *InvoiceCalculator {
	return &InvoiceCalculator{fxRepo: fxRepo}
}

// CalculateCyclePrice calculates the exact NGN amount to debit for the upcoming cycle.
func (ic *InvoiceCalculator) CalculateCyclePrice(
	ctx context.Context,
	plan Plan,
	sub Subscription,
) (int64, float64, error) {
	// Fetch 30-day Trailing Simple Moving Average for NGN/USD
	smaRate, err := ic.fxRepo.GetTrailingSMA(ctx, 30)
	if err != nil {
		return 0, 0, fmt.Errorf("failed to fetch FX moving average: %w", err)
	}

	effectiveRate := smaRate

	// Apply rate bump caps if a previous charge rate exists
	if sub.LastChargedRate > 0 {
		maxAllowedRate := sub.LastChargedRate * (1.0 + plan.MaxCycleCap)
		minAllowedRate := sub.LastChargedRate * (1.0 - plan.MaxCycleCap)

		if effectiveRate > maxAllowedRate {
			effectiveRate = maxAllowedRate
		} else if effectiveRate < minAllowedRate {
			effectiveRate = minAllowedRate
		}
	}

	// BasePriceUSD is stored in cents ($100 = 10000 cents)
	// Calculate total NGN amount in Kobo (1 NGN = 100 Kobo for Paystack)
	priceInUSD := plan.BasePriceUSD / 100.0
	totalNaira := priceInUSD * effectiveRate
	totalKobo := int64(math.Round(totalNaira * 100.0))

	return totalKobo, effectiveRate, nil
}

Invoicing and Tokenized Recurrent Debits

Once the dynamic rate is calculated, we charge the saved card authorization via Paystack. We maintain idempotency using unique invoice keys, similar to how we isolate state mutations in our guide on handling 500 webhooks/sec with Redis and Postgres advisory locks.

package billing

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

type PaystackChargeRequest struct {
	Amount            int64  `json:"amount"` // Amount in Kobo
	Email             string `json:"email"`
	AuthorizationCode string `json:"authorization_code"`
	Currency          string `json:"currency"` // "NGN"
	Reference         string `json:"reference"` // Idempotency reference key
}

type PaystackChargeResponse struct {
	Status  bool   `json:"status"`
	Message string `json:"message"`
	Data    struct {
		Status          string `json:"status"`
		TransactionDate string `json:"paid_at"`
		Reference       string `json:"reference"`
	} `json:"data"`
}

type PaystackClient struct {
	apiKey     string
	httpClient *http.Client
}

func NewPaystackClient(apiKey string) *PaystackClient {
	return &PaystackClient{
		apiKey:     apiKey,
		httpClient: &http.Client{Timeout: 10 * time.Second},
	}
}

func (pc *PaystackClient) ChargeAuthorization(
	ctx context.Context,
	req PaystackChargeRequest,
) (*PaystackChargeResponse, error) {
	body, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}

	httpReq, err := http.NewRequestWithContext(ctx, "POST", "https://api.paystack.co/transaction/charge_authorization", bytes.NewBuffer(body))
	if err != nil {
		return nil, err
	}

	httpReq.Header.Set("Authorization", "Bearer "+pc.apiKey)
	httpReq.Header.Set("Content-Type", "application/json")

	resp, err := pc.httpClient.Do(httpReq)
	if err != nil {
		return nil, fmt.Errorf("paystack API transport error: %w", err)
	}
	defer resp.Body.Close()

	var res PaystackChargeResponse
	if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
		return nil, fmt.Errorf("failed to decode paystack response: %w", err)
	}

	if !res.Status || res.Data.Status != "success" {
		return &res, fmt.Errorf("charge failed: %s", res.Message)
	}

	return &res, nil
}

When choosing whether to build custom FX-indexing billing middleware or buy off-the-shelf software like Chargebee, many African engineering teams stumble into the $40k build-vs-buy mistake. Most Western billing platforms simply do not support trailing SMA exchange rate caps or native Paystack multi-currency authorization tokens natively.

Common Pitfalls

1. The Intra-Month Invoice Shock

Calculating exchange rates based on the instantaneous spot rate at the minute of invoice generation creates massive support queue bottlenecks. If the Naira drops 8% on the 29th of the month due to local liquidity constraints, a customer whose billing date falls on the 30th gets billed significantly more than a peer billed on the 28th. Always use a 30-day trailing SMA to smooth out spot market anomalies.

2. Token Authorization Expiry on Local Cards

Nigerian debit cards expire quickly, and local banks frequently rotate PANs due to fraud mitigation rules. Paystack authorization_code strings can suddenly fail with 400 Bad Request or return insufficient_funds. You must build an automated pre-billing ping 3 days prior to renewal: calculate the estimated NGN debit, email the tenant account admin, and check card validity.

3. Reporting Revenue Under NDPR and Local Tax Frameworks

Even if your internal reporting counts baseline MRR in USD, your statutory invoicing in Nigeria must explicitly state the total NGN collected, the applied exchange rate, and the 7.5% Value Added Tax (VAT) calculated on the finalized Naira amount. Failure to render statutory NGN VAT line items on enterprise invoices exposes your business to severe audit penalties from the Federal Inland Revenue Service (FIRS).

Frequently Asked Questions

How do you handle enterprise customers who demand static quarterly or annual invoices?

For enterprise accounts purchasing annual plans, offer a fixed Naira invoice with a 15% pre-factored FX volatility premium, or require upfront payment in USD via direct domiciliary bank wire transfer (NIBSS or SWIFT). Do not offer static Naira pricing on monthly recurring billing cycles under any circumstances.

Should we default to Stripe or Paystack for multi-currency subscriptions?

If more than 70% of your buyer persona resides in Sub-Saharan Africa, use Paystack as primary and Stripe as fallback. Nigerian debit cards fail systematically on Stripe due to local bank international spend bans. Stripe should only be triggered if the customer explicitly selects a foreign credit card or resides outside Africa.

How do you communicate FX-indexed price updates to subscribers without triggering cancellations?

Transparency must be embedded into the checkout flow. Include a explicit line item during onboarding: "Plans are anchored at $X USD and billed monthly in NGN using a 30-day moving average exchange rate capped at 15% cycle adjustments." Send an automated email preview 72 hours before debiting showing the exact exchange rate calculation and final NGN total.

Neobot Engineering Standard

Every system deployed by Neobot Tech incorporates enterprise baseline practices. We continuously audit our database topologies, REST API query paths, and frontend modular bundles to prevent latency spikes and ensure top-tier security posture.

Tags:#Product Strategy#Go#Fintech#Paystack#Stripe#SaaS Pricing

Discussion

Comments Coming Soon

We are currently migrating our discussion engine to a new real-time database schema. Check back shortly to join the conversation.