Pricing B2B SaaS in Naira Under 100% FX Volatility: Building an FX-Pegged Billing Engine in Node.js
When Naira devaluation shrinks software margins, switching directly to USD pricing causes local card failures. Here is how we engineered an FX-pegged billing engine in Node.js and PostgreSQL to solve both problems.
In mid-2023, a logistics SaaS client approached us at Neobot Tech with a severe revenue leakage problem. They billed local enterprise accounts ₦150,000 monthly for a fleet telemetry platform. In early 2022, that subscription generated roughly $325 per customer—plenty of margin to cover AWS infrastructure, Twilio dispatch SMS, and Google Maps API fees. Fast forward to early 2024: with the Naira devaluing past ₦1,400/$1, that same ₦150,000 yielded less than $105.
Their infrastructure bills, priced in USD by AWS and Datadog, did not drop. The company was losing money on every active customer account.
The obvious reaction was to change plan prices directly to USD ($300/month). It backfired within 48 hours. Local corporate debit cards failed outright because Nigerian banks had capped or outright removed international dollar spending limits on Naira cards. Enterprise clients willing to pay in foreign currency insisted on manual domiciliary bank transfers, replacing an automated billing pipeline with a manual 45-day accounts receivable chase.
To fix this without destroying conversion, we engineered a dual-currency billing engine. Contract values are denominated in USD to protect unit economics, but invoice amounts are dynamically generated and charged in NGN at execution time using a buffered spot rate.
Here is how we designed and implemented the architecture in Node.js and PostgreSQL.
The Product Strategy: USD Base, NGN Execution
SaaS pricing in volatile markets comes down to a structural dilemma: who absorbs foreign exchange risk? If you price strictly in fixed local currency, your SaaS absorbs the FX risk. If you price strictly in USD and charge in USD, your customer absorbs both FX risk and payment rail frictions.
To balance this, our strategy relies on four business mechanics:
- USD Base Tiering: Every SaaS tier has a canonical base price in USD (e.g.,
$250/month). - Spot Rate Ingestion with Variance Buffer: The system periodically ingests official market rates (via exchange sources like FMDQ Group) and adds a configurable risk buffer (e.g., 3.5%) to absorb intraday liquidity spikes.
- Billing Date Rate Locking: When an invoice is generated (3 days prior to charge date), the effective NGN conversion rate is frozen for that invoice line item.
- Local Payment Gateway Execution: The final charge is sent to local gateways like Paystack in NGN, ensuring high authorization rates on domestic bank cards.
This pattern mirrors how local infrastructure costs are structured. Similar to how Why Western Identity Tools Destroy SME SaaS Margins: Building a Custom Postgres Session Engine in Node.js addresses gross margin erosion from third-party vendor APIs, this billing pattern prevents external macro shifts from turning profitable customers into net-negative operational liabilities.
Database Schema: Decoupling Contracts from Currency Execution
To support dynamic multi-currency calculations without breaking financial auditability, your schema must separate the contract price unit from the finalized invoice transaction currency.
Here is the PostgreSQL schema using DDL:
-- Enum for support currencies
CREATE TYPE currency_code AS ENUM ('USD', 'NGN');
CREATE TYPE invoice_status AS ENUM ('DRAFT', 'ISSUED', 'PAID', 'FAILED', 'VOID');
-- Base Subscription Plans (Canonical USD values)
CREATE TABLE subscription_plans (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(100) NOT NULL,
base_price_usd NUMERIC(12, 2) NOT NULL,
billing_interval VARCHAR(20) NOT NULL CHECK (billing_interval IN ('monthly', 'yearly')),
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Daily FX Rate Snapshots
CREATE TABLE fx_rates (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
base_currency currency_code NOT NULL DEFAULT 'USD',
target_currency currency_code NOT NULL DEFAULT 'NGN',
spot_rate NUMERIC(12, 4) NOT NULL,
buffered_rate NUMERIC(12, 4) NOT NULL,
provider VARCHAR(50) NOT NULL,
captured_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_fx_rates_captured ON fx_rates(target_currency, captured_at DESC);
-- Customer Subscriptions
CREATE TABLE customer_subscriptions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
customer_id UUID NOT NULL,
plan_id UUID REFERENCES subscription_plans(id),
status VARCHAR(20) NOT NULL DEFAULT 'active',
current_period_start TIMESTAMPTZ NOT NULL,
current_period_end TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Immutable Invoices (Locks rate at issue time)
CREATE TABLE invoices (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
subscription_id UUID REFERENCES customer_subscriptions(id),
base_amount_usd NUMERIC(12, 2) NOT NULL,
fx_rate_used NUMERIC(12, 4) NOT NULL,
final_amount_ngn NUMERIC(14, 2) NOT NULL,
status invoice_status NOT NULL DEFAULT 'DRAFT',
due_date TIMESTAMPTZ NOT NULL,
paystack_reference VARCHAR(100) UNIQUE,
paid_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW()
);
Never store only the final_amount_ngn on an invoice table. If an auditor asks why Customer A paid ₦300,000 in January and ₦420,000 in March for the exact same plan, you must demonstrate that base_amount_usd remained $250 while fx_rate_used shifted from ₦1,200 to ₦1,680.
Step-by-Step Implementation: The FX Billing Engine
Now, let's write the TypeScript service that ingests rates, calculates invoice line items with risk buffers, and initiates charges via Paystack.
Step 1: FX Rate Ingestion and Buffer Calculation
We fetch rates from an official API source (such as ExchangeRate-API or Open Exchange Rates) and apply a buffer before storing the snapshot.
import axios from 'axios';
import { Pool } from 'pg';
const db = new Pool({ connectionString: process.env.DATABASE_URL });
const FX_BUFFER_PERCENT = 0.035; // 3.5% liquidity buffer
interface RateFetchResult {
spotRate: number;
bufferedRate: number;
}
export async function syncFxRates(): Promise<RateFetchResult> {
try {
// Fetching USD to NGN rate
const response = await axios.get(`https://open.er-api.com/v6/latest/USD`);
const spotRate = response.data.rates.NGN;
if (!spotRate || typeof spotRate !== 'number') {
throw new Error('Invalid rate returned from provider');
}
// Calculate rate with risk buffer to cushion intraday slippage
const bufferedRate = Number((spotRate * (1 + FX_BUFFER_PERCENT)).toFixed(4));
await db.query(
`INSERT INTO fx_rates (base_currency, target_currency, spot_rate, buffered_rate, provider)
VALUES ('USD', 'NGN', $1, $2, 'open_er_api')`,
[spotRate, bufferedRate]
);
return { spotRate, bufferedRate };
} catch (error) {
console.error('Failed to sync FX rates:', error);
throw error;
}
}
Step 2: Invoice Generation and Rate Locking Engine
When standard subscription billing triggers, we pull the latest buffered exchange rate, lock it into a new invoice record, and store the calculated NGN total.
interface InvoiceResult {
invoiceId: string;
amountInKobo: number;
exchangeRate: number;
}
export async function createSubscriptionInvoice(subscriptionId: string): Promise<InvoiceResult> {
const client = await db.connect();
try {
await client.query('BEGIN');
// 1. Fetch active subscription & USD plan details
const subRes = await client.query(
`SELECT s.id, p.base_price_usd
FROM customer_subscriptions s
JOIN subscription_plans p ON s.plan_id = p.id
WHERE s.id = $1 AND s.status = 'active'`,
[subscriptionId]
);
if (subRes.rows.length === 0) {
throw new Error('Active subscription not found');
}
const { base_price_usd } = subRes.rows[0];
// 2. Fetch latest buffered FX rate
const fxRes = await client.query(
`SELECT buffered_rate
FROM fx_rates
WHERE target_currency = 'NGN'
ORDER BY captured_at DESC LIMIT 1`
);
if (fxRes.rows.length === 0) {
throw new Error('No FX rate available for conversion');
}
const fxRate = parseFloat(fxRes.rows[0].buffered_rate);
// 3. Compute final NGN amount (rounded to 2 decimal places)
const finalAmountNgn = Number((parseFloat(base_price_usd) * fxRate).toFixed(2));
// Paystack expects amount in Kobo (integer, 1 NGN = 100 Kobo)
const amountInKobo = Math.round(finalAmountNgn * 100);
// 4. Create immutable draft invoice
const invoiceRes = await client.query(
`INSERT INTO invoices
(subscription_id, base_amount_usd, fx_rate_used, final_amount_ngn, status, due_date)
VALUES ($1, $2, $3, $4, 'DRAFT', NOW() + INTERVAL '3 days')
RETURNING id`,
[subscriptionId, base_price_usd, fxRate, finalAmountNgn]
);
const invoiceId = invoiceRes.rows[0].id;
await client.query('COMMIT');
return {
invoiceId,
amountInKobo,
exchangeRate: fxRate
};
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
Step 3: Executing Charge via Paystack API
With invoice figures calculated, we call the payment gateway API using the saved authorization token of the customer's card.
import crypto from 'crypto';
export async function chargeSubscriptionInvoice(
invoiceId: string,
customerEmail: string,
authorizationCode: string,
amountInKobo: number
) {
const reference = `INV_${invoiceId.slice(0, 8)}_${Date.now()}`;
// Update invoice status to ISSUED with generated reference
await db.query(
`UPDATE invoices SET status = 'ISSUED', paystack_reference = $1 WHERE id = $2`,
[reference, invoiceId]
);
// Execute Paystack recurrent charge
const response = await axios.post(
'https://api.paystack.co/transaction/charge_authorization',
{
email: customerEmail,
amount: amountInKobo,
authorization_code: authorizationCode,
reference: reference,
currency: 'NGN'
},
{
headers: {
Authorization: `Bearer ${process.env.PAYSTACK_SECRET_KEY}`,
'Content-Type': 'application/json'
}
}
);
return response.data;
}
Because network drops occur during billing cycles, ensure your payment webhooks handle retries cleanly. For a detailed breakdown of Redis lock race conditions during payment webhooks, refer to our analysis on Paystack Webhook Retries: Why Redis Idempotency Keys Drop Payments Under Network Flaps.
Architectural Comparison: Pricing Models in High-Devaluation Markets
The table below compares common pricing architectures evaluated during our B2B SaaS client engagement:
| Architecture Strategy | Unit Margin Protection | Card Authorization Success | Customer Churn Impact | Engineering Complexity | | :--- | :--- | :--- | :--- | :--- | | Pure NGN (Fixed) | Low (Eroded by inflation) | High (92-96%) | Low | Very Low | | Pure USD (Direct) | High (100% stable) | Terrible (<15% on local cards) | High (Mass churn) | Low | | FX-Pegged Dynamic NGN | High (Bounded by buffer) | High (90-95%) | Moderate (Requires communication) | Moderate | | Dual-Plan Parallel Tiers | Medium | High | High (Arbing & confusion) | High |
Common Pitfalls
1. Fetching Live FX Rates Inside Checkout Requests
Never query an external FX API synchronously inside an active HTTP checkout handler or CRON billing loop. If the FX provider endpoint times out or drops packets, your automated billing worker stalls. Always decouple ingestion using a background worker (e.g., BullMQ) that runs every 6 to 12 hours, writing to the fx_rates database table. Read exclusively from the latest database snapshot during billing runs.
2. Failing to Send Pre-Billing Rate Notifications
If a customer signed up when their $200 plan cost ₦160,000, and six months later your automated system charges ₦320,000 because of market shifts, they will initiate chargebacks. Implement an automated email trigger three days before charging. The notification must explicitly display the locked rate for the upcoming cycle: "Your upcoming cycle is $200. Converted at ₦1,620/$1 (including FX buffer), your card will be charged ₦324,000 on June 1st."
3. Calculating Refunds at Current Spot Rates Instead of Locked Historical Rates
If a customer pays an invoice converted at ₦1,400/$1 and requests a refund three weeks later when the market rate hits ₦1,600/$1, refunding using the new rate causes an unearned financial loss for your company. Refunds must strictly reference the historical final_amount_ngn recorded directly on the invoices table record, not a recalculated current valuation.
FAQ
How do we handle Value Added Tax (VAT) with dynamic FX pricing in Nigeria?
In Nigeria, statutory 7.5% VAT applies to the final settled NGN invoice value, not the base USD value. Calculate your tax line item after converting the USD base price to NGN: vat_amount_ngn = final_amount_ngn * 0.075. Record vat_amount_ngn explicitly on the invoice for regulatory tax reporting.
Should we let enterprise customers pay in USD via domiciliary transfers?
Yes. Build your billing logic to support dual payment rails. For accounts spending over $1,000/month, provide an offline wire option where they deposit directly into your USD domiciliary bank account. For these accounts, flag payment_rail = 'DOM_TRANSFER' and skip the dynamic NGN billing calculation entirely.
What FX buffer percentage should we use?
For the Nigerian market, a buffer between 3% and 5% above official interbank rates is typical. This margin accounts for gateway settlement delays (T+1 or T+2 settlement windows) and bank liquidity spread differences.
How does this affect revenue recognition in financial reporting?
Your primary accounting currency determines how revenue is booked. If your corporate entity is registered in Delaware or the UK, book revenue in USD using the static base_amount_usd. If reporting locally in Nigeria, book revenue in NGN based on the actual settled amount deposited into your bank account.
Structuring your product for volatile FX markets is fundamentally an exercise in risk distribution. Denominating contract value in USD protects your software margins, while executing card charges dynamically in NGN protects your local acquisition funnel.
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.