Indexing Naira SaaS Billing to USD: Building a Rate-Capped FX Engine in Node.js
Fixing currency volatility in African B2B SaaS requires more than charging in USD. Learn how we built a rate-indexed, Naira-denominated billing engine with FX collars in Node.js to protect infrastructure margins without triggering customer churn.
In mid-2023, a Lagos-based logistics client running on our infrastructure stack hit a wall. They had 140 active SME clients paying a flat subscription of ₦50,000 per month for multi-warehouse tracking. Behind the scenes, the platform's infrastructure—hosted on AWS, using OpenAI for address parsing and Twilio for driver SMS notifications—cost roughly $38 per tenant per month.
When the NAFEM FX window unified and the exchange rate jumped from ₦460/$ to over ₦1,400/$, their monthly revenue of ₦7,000,000 remained static at roughly $5,000. Meanwhile, their AWS and vendor bill soared from ₦2.4 million to ₦7.9 million. Overnight, gross margins inverted from +65% to -12%. The company was effectively paying its customers to use the platform.
Their immediate reaction was to switch all billing to USD via Stripe. The result was catastrophic: a 62% customer churn within 30 days. Most Nigerian SME debit cards rejected foreign currency transactions due to Central Bank limits on international card spending (often capped at $20/month or disabled entirely).
Direct USD charging killed conversion, while fixed Naira charging killed margins. The solution was a hybrid pricing architecture: USD-indexed base prices calculated, capped, and charged in Naira at the point of billing renewal. Here is how to build that billing engine.
The Product Strategy: FX Collars and Transparency
Blindly passing 100% of daily FX swings onto B2B customers causes billing fatigue and unexpected card charge failures. If a customer is debited ₦50,000 in January and ₦85,000 in February without warning, your support queue will explode.
To balance unit economics with SME retention, we designed an FX Collar Pricing Strategy:
- USD Base Pricing: Internal plans are defined in USD (e.g., $50/month base plan).
- Daily FX Fetching: The system fetches the prevailing bank settlement rate every 24 hours.
- Volatility Smoothing (FX Collar): Monthly renewal price adjustments are capped at a maximum jump of +15% per cycle, even if the currency devalues by 40% in that period. The unbilled gap is absorbed temporarily or caught up over subsequent steady cycles.
- Pre-Debit FX Lock Notification: 72 hours before invoice generation, the engine locks the exchange rate, calculates the exact Naira amount, and sends an automated SMS/email notice to the account owner.
This approach gives business owners predictable invoice bounds while ensuring software providers do not get eaten alive by currency depreciation.

Designing the Engine: Step-by-Step Implementation
Let's implement a complete TypeScript solution using Node.js, PostgreSQL (Prisma), the Open Exchange Rates API, and Paystack Subscriptions API.
1. Database Schema for Dynamic FX Billing
First, define a schema that tracks USD base plans, historical FX rates, customer subscriptions, and billing collars.
model Plan {
id String @id @default(uuid())
name String
usdPrice Decimal @db.Decimal(10, 2)
maxFxDriftPct Decimal @default(15.00) @db.Decimal(5, 2) // Max % increase per billing cycle
subscriptions Subscription[]
}
model FxRate {
id String @id @default(uuid())
currencyPair String @default("USD_NGN")
rate Decimal @db.Decimal(10, 4)
fetchedAt DateTime @default(now())
}
model Subscription {
id String @id @default(uuid())
customerId String
planId String
plan Plan @relation(fields: [planId], references: [id])
paystackCustomerCode String
paystackPlanCode String?
paystackEmailToken String?
lastBilledRate Decimal @db.Decimal(10, 4)
nextBillingDate DateTime
status String @default("ACTIVE")
createdAt DateTime @default(now())
}
2. The Core Rate Calculation Logic with Collars
Now, implement the pricing algorithm. This service fetches the latest FX rate, compares it with the rate applied during the customer's previous billing cycle, and applies the FX collar ceiling.
import { PrismaClient, Prisma } from '@prisma/client';
import axios from 'axios';
const prisma = new PrismaClient();
interface CalculatedInvoice {
usdAmount: number;
effectiveRate: number;
ngnAmountKobo: number;
isCapped: boolean;
}
export class FxEngineService {
/**
* Calculates the Naira invoice amount for a subscription renewal,
* applying max percent increase caps to avoid billing shock.
*/
public calculateRenewalPrice(
usdBasePrice: number,
lastBilledRate: number,
currentMarketRate: number,
maxFxDriftPct: number
): CalculatedInvoice {
// Calculate raw target rate
let effectiveRate = currentMarketRate;
if (lastBilledRate > 0) {
const maxAllowedRate = lastBilledRate * (1 + maxFxDriftPct / 100);
if (currentMarketRate > maxAllowedRate) {
effectiveRate = maxAllowedRate;
}
}
const ngnAmountTotal = usdBasePrice * effectiveRate;
// Paystack processes payments in Kobo (1 NGN = 100 Kobo)
const ngnAmountKobo = Math.round(ngnAmountTotal * 100);
return {
usdAmount: usdBasePrice,
effectiveRate: Number(effectiveRate.toFixed(4)),
ngnAmountKobo,
isCapped: effectiveRate < currentMarketRate,
};
}
/**
* Fetch live rate from Open Exchange Rates or fallback to last known DB rate
*/
public async getLatestUsdNgnRate(): Promise<number> {
try {
const response = await axios.get(
`https://openexchangerates.org/api/latest.json?app_id=${process.env.OPEN_EXCHANGE_RATES_KEY}&symbols=NGN`
);
const rate = response.data.rates.NGN;
await prisma.fxRate.create({
data: { currencyPair: 'USD_NGN', rate: new Prisma.Decimal(rate) },
});
return rate;
} catch (error) {
console.error('Failed to fetch live FX rate, falling back to DB:', error);
const lastKnown = await prisma.fxRate.findFirst({
orderBy: { fetchedAt: 'desc' },
});
if (!lastKnown) throw new Error('No FX rate available');
return Number(lastKnown.rate);
}
}
}
3. Dynamically Syncing Rates with Paystack Plans
Paystack Subscriptions rely on a plan_code. Because static plans break when rates fluctuate, we must generate or assign dynamic plans prior to billing execution, or issue explicit charge requests.
Similar to how we handled job retries for third-party payment providers in our deep-dive on BullMQ vs Temporal vs AWS Step Functions, we isolate our billing updates inside a queue worker to guarantee execution stability.
import axios from 'axios';
export class PaystackBillingSync {
private paystackSecret = process.env.PAYSTACK_SECRET_KEY;
/**
* Creates a dedicated Paystack plan for the specific dynamic amount
* or updates subscription parameters 72 hours before charge execution.
*/
public async prepareNextBillingCycle(
subscriptionId: string,
engine: FxEngineService
) {
const sub = await prisma.subscription.findUnique({
where: { id: subscriptionId },
include: { plan: true },
});
if (!sub) throw new Error('Subscription not found');
const currentRate = await engine.getLatestUsdNgnRate();
const invoice = engine.calculateRenewalPrice(
Number(sub.plan.usdPrice),
Number(sub.lastBilledRate),
currentRate,
Number(sub.plan.maxFxDriftPct)
);
// Create a dynamic plan code on Paystack for this specific billed cohort
const planResponse = await axios.post(
'https://api.paystack.co/plan',
{
name: `${sub.plan.name} - FX Adjusted Rate ${invoice.effectiveRate}`,
interval: 'monthly',
amount: invoice.ngnAmountKobo,
currency: 'NGN',
},
{
headers: { Authorization: `Bearer ${this.paystackSecret}` },
}
);
const paystackPlanCode = planResponse.data.data.plan_code;
// Save state pending the renewal charge date
await prisma.subscription.update({
where: { id: subscriptionId },
data: {
paystackPlanCode,
lastBilledRate: new Prisma.Decimal(invoice.effectiveRate),
},
});
// Trigger Pre-debit SMS/Email notification to client
await this.sendPreBillingNotification(
sub.customerId,
invoice.ngnAmountKobo / 100,
invoice.effectiveRate
);
}
private async sendPreBillingNotification(
customerId: string,
ngnAmount: number,
rateUsed: number
) {
// Business logic to send email/SMS notification to account admin
console.log(
`Notified client ${customerId}: Next cycle billed at ₦${ngnAmount} (Rate: ₦${rateUsed}/$)`
);
}
}
Evaluating build-vs-buy decisions for foundational integrations—much like the trade-offs explored when analyzing our Custom WhatsApp Engine vs Meta's Cloud API—proves that leveraging native payment primitives like Paystack's plan API saves months of custom ledger development.
Common Pitfalls in Dynamic FX Billing
When deploying FX-indexed software billing in African markets, technical teams routinely hit three major operational traps:
1. The Official vs. Parallel FX Gap
Official central bank exchange rates often do not reflect the actual cost of purchasing foreign currency to clear cloud infrastructure liabilities. If the official rate is ₦1,300/$ but your corporate card provider clears AWS invoices at a parallel bank settlement rate of ₦1,550/$, relying on official public APIs will still leave you with a 15-20% margin deficit.
Fix: Configure your FX engine to pull directly from commercial bank settlement feeds or add an internal operational spread (e.g., +5%) to raw API rates.
2. Sudden Authorization Declines due to Amount Volatility
Nigerian banks employ fraud detection models that flag recurring card charges when the billing amount changes substantially from month to month. If a customer's recurring debit changes from ₦30,000 to ₦48,000, automated card authorization rates drop by as much as 30%.
Fix: Enforce strict FX collars (e.g., maximum 10-15% drift per cycle). For changes larger than 20%, switch the billing cycle to issue an invoice requiring manual web authorization (3D Secure) rather than relying on headless charge retries.
3. Floating-Point Rounding Errors in Currency Conversion
Converting USD floating points directly to Naira integers can produce subtle calculation drift across thousands of customers. Standard JavaScript double-precision numbers will yield artifacts like 50 * 1412.33 = 70616.49999999999.
Fix: Always compute currency calculations using scaled integers or arbitrary-precision libraries like decimal.js or Prisma’s native Decimal type before sending values to payment processors.
| Billing Method | Infrastructure Margin Stability | SME Conversion Rate | Technical Complexity | | :--- | :--- | :--- | :--- | | Pure USD (Stripe/Wise) | High (100% hedge) | Very Low (~35%) | Low | | Fixed NGN Pricing | Very Low (Degrades monthly) | High (~90%) | Very Low | | FX-Indexed NGN + Collar | High (Targeted within +/-5%) | Medium-High (~82%) | Moderate |
Frequently Asked Questions
Should I price my SaaS directly in USD or index it to Naira?
For Nigerian SMEs, always display and charge the final invoice in Naira. Direct USD charges face card decline rates upwards of 60% due to local banking limits on foreign transactions. Indexing base rates in USD while collecting charges in Naira provides margin stability while preserving checkout completion rates.
How frequently should exchange rates be updated in our billing system?
Do not recalculate charges in real-time at the exact second of charge execution without notifying the customer. Fetch exchange rates daily for internal accounting, but lock the specific exchange rate for a customer's renewal invoice 72 hours prior to the billing date. This satisfies NDPR transparency guidelines and prevents customer support chargebacks.
How do we handle customers who insist on multi-year fixed contracts?
For enterprise clients requesting annual upfront billing in Naira, incorporate a calculated FX inflation buffer (e.g., +25% over spot rate) into the annual contract or include an explicit re-baselining clause that triggers if official FX rates move beyond a 20% band during the contract term.
By building an FX-indexed pricing architecture into your core backend, you insulate your company's balance sheet against currency shocks without locking out the local customer base driving your growth.
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.
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.