Termii vs Twilio for Nigerian B2B SaaS: Building a Dynamic Cost-Aware Notification Router in Node.js
Nigerian SaaS products selling to local SMEs face a delicate balance: local SMS routes like Termii are cheap but occasionally unstable, while global options like Twilio offer uptime at high dollar-denominated prices. Here is how we engineered a dynamic notification engine in Node.js that routes traffic based on urgency, health checks, and profit margins.
The ₦3.80 vs $0.065 SMS Dilemma: How Fixed SME SaaS Pricing Destroys Margins
Last year, a local B2B logistics client using our engineering services expanded their SME user base from 120 companies to over 1,400 active merchants. They offered an flat-rate subscription of ₦35,000 per month, which included transactional SMS updates for delivery tracking and buyer OTP verification. Their initial architecture relied solely on Twilio for global reliability.
When the Naira depreciated sharply against the US Dollar, their transactional messaging bill skyrocketed. Sending a single verification SMS via international routes shot up to $0.065 (roughly ₦100 per message at parallel rates). An SME doing 500 orders a month was costing ₦50,000 in messaging fees alone while paying only ₦35,000 for the platform subscription. The client was literally losing money on every active customer.
To save the unit economics, their product team immediately switched the entire system to a local aggregator—Termii—reducing message costs to roughly ₦3.80 per unit. Margins instantly recovered, but a new failure mode emerged. During peak hours on MTN and Airtel networks, local DND (Do Not Disturb) filters and telecommunication route congestion caused OTP delivery delays of up to 8 minutes. Merchants were locked out of their dashboards, checkout conversions dropped by 28%, and customer support was overwhelmed.
The core problem was treating transactional messaging as a binary build-vs-buy architectural decision. Naively picking a single supplier forces you to choose between bankrupting dollar-denominated bills or poor local delivery rates. The real solution is building an intelligent, dynamic notification router in-house that evaluates message urgency, channel costs, carrier health, and customer margins in real time.

Architecture of a Cost-Aware Notification Router
A resilient notification engine requires three architectural components:
- Priority Tiers: Differentiating between time-critical payloads (OTPs, password resets) and delayed notifications (daily sales summaries, promotional alerts).
- Channel Cost Optimization: Preferring low-cost local channels (Termii Direct Route, WhatsApp Business API) over high-cost international fallbacks (Twilio SMS).
- Real-time Health Monitoring: Using Redis to track carrier delivery status and automatically degrading or upgrading routes when delivery latencies breach safe thresholds.
If you have already implemented an FX-capped billing engine as described in our guide on Indexing Naira SaaS Billing to USD: Building a Rate-Capped FX Engine in Node.js, you know that operational costs must be bounded dynamically. The notification router applies that exact principle to outbound communications.
Below is the system state flow for dispatching a transaction message:
- Check Message Priority: Is this an OTP or a daily digest?
- Check Vendor Health: Is Termii responding within <3.5 seconds with success webhooks?
- Check Tier & Margin: Is this account on a Free, Growth, or Enterprise SME plan?
- Execute Route: Primary local SMS -> WhatsApp Business API -> Fallback Twilio SMS.
Implementing the Dynamic Router in TypeScript
Let's implement the core dynamic notification router using Node.js, TypeScript, and Redis for route state management. This worker handles multi-tier provider dispatching with automatic health degradation.
import axios from 'axios';
import Redis from 'ioredis';
interface MessagePayload {
to: string; // E.164 phone format: +234...
body: string;
type: 'OTP' | 'TRANSACTIONAL' | 'MARKETING';
tenantId: string;
}
interface ProviderConfig {
name: 'termii_direct' | 'termii_dnd' | 'whatsapp_baileys' | 'twilio';
costPerUnitNaira: number;
maxLatencyMs: number;
}
export class NotificationRouter {
private redis: Redis;
private termiiApiKey: string;
private twilioAccountSid: string;
private twilioAuthToken: string;
constructor() {
this.redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379');
this.termiiApiKey = process.env.TERMII_API_KEY || '';
this.twilioAccountSid = process.env.TWILIO_ACCOUNT_SID || '';
this.twilioAuthToken = process.env.TWILIO_AUTH_TOKEN || '';
}
async dispatch(payload: MessagePayload): Promise<{ provider: string; success: boolean; costNaira: number }> {
// 1. Determine priority route based on message type
const providers = this.getProviderPriorityList(payload.type);
for (const provider of providers) {
const isHealthy = await this.checkProviderHealth(provider.name);
if (!isHealthy) {
console.warn(`[Router] Skipping ${provider.name} due to health check degradation.`);
continue;
}
try {
const startTime = Date.now();
let success = false;
if (provider.name === 'termii_direct') {
success = await this.sendViaTermii(payload, 'dnd');
} else if (provider.name === 'termii_dnd') {
success = await this.sendViaTermii(payload, 'generic');
} else if (provider.name === 'twilio') {
success = await this.sendViaTwilio(payload);
}
const duration = Date.now() - startTime;
if (success) {
await this.recordSuccess(provider.name, duration);
return { provider: provider.name, success: true, costNaira: provider.costPerUnitNaira };
} else {
await this.recordFailure(provider.name);
}
} catch (err) {
await this.recordFailure(provider.name);
console.error(`[Router] Error with ${provider.name}:`, (err as Error).message);
}
}
throw new Error(`[Router] All dispatch providers exhausted for recipient ${payload.to}`);
}
private getProviderPriorityList(type: 'OTP' | 'TRANSACTIONAL' | 'MARKETING'): ProviderConfig[] {
if (type === 'OTP') {
// OTP priority: Direct Termii Route -> Twilio (Immediate delivery over cost)
return [
{ name: 'termii_direct', costPerUnitNaira: 4.5, maxLatencyMs: 3000 },
{ name: 'twilio', costPerUnitNaira: 98.0, maxLatencyMs: 2000 },
];
}
// Standard Transactional priority: Direct Local -> Generic Local -> Skip expensive USD routes
return [
{ name: 'termii_direct', costPerUnitNaira: 4.5, maxLatencyMs: 5000 },
{ name: 'termii_dnd', costPerUnitNaira: 3.8, maxLatencyMs: 8000 },
];
}
private async checkProviderHealth(providerName: string): Promise<boolean> {
const failureCount = await this.redis.get(`health:failures:${providerName}`);
if (failureCount && parseInt(failureCount, 10) >= 5) {
return false; // Circuit breaker open
}
return true;
}
private async recordSuccess(providerName: string, durationMs: number): Promise<void> {
await this.redis.del(`health:failures:${providerName}`);
await this.redis.lpush(`health:latency:${providerName}`, durationMs);
await this.redis.ltrim(`health:latency:${providerName}`, 0, 99);
}
private async recordFailure(providerName: string): Promise<void> {
const key = `health:failures:${providerName}`;
const failures = await this.redis.incr(key);
if (failures === 1) {
await this.redis.expire(key, 300); // 5 minute failure window
}
}
private async sendViaTermii(payload: MessagePayload, channel: 'dnd' | 'generic'): Promise<boolean> {
const response = await axios.post('https://api.ng.termii.com/api/sms/send', {
to: payload.to,
from: 'N-ALERT',
sms: payload.body,
type: 'plain',
channel: channel,
api_key: this.termiiApiKey,
}, { timeout: 4000 });
return response.status === 200 && response.data?.code === 'ok';
}
private async sendViaTwilio(payload: MessagePayload): Promise<boolean> {
const auth = Buffer.from(`${this.twilioAccountSid}:${this.twilioAuthToken}`).toString('base64');
const params = new URLSearchParams();
params.append('To', payload.to);
params.append('From', process.env.TWILIO_PHONE_NUMBER || '');
params.append('Body', payload.body);
const response = await axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${this.twilioAccountSid}/Messages.json`,
params,
{
headers: {
'Authorization': `Basic ${auth}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
timeout: 4000,
}
);
return response.status === 201;
}
}
Comparing Provider Strategy Options for West Africa
When designing your product's communications layer, select channels based on message criticality and cost ceilings:
| Vendor Channel | Cost Per Unit (NGN) | Delivery Rate (Local Telcos) | Typical Latency | Best Used For | | :--- | :--- | :--- | :--- | :--- | | Termii Generic Route | ₦3.80 | 72% - 84% | 5 - 45 sec | Marketing, non-urgent summaries | | Termii Direct / DND Route | ₦4.50 - ₦5.50 | 91% - 96% | 2 - 8 sec | OTPs, login verifications | | WhatsApp Business API | ₦8.50 - ₦14.00 | 98% | 1 - 3 sec | High-value order updates, invoices | | Twilio International SMS | ₦95.00 - ₦115.00 | 99.2% | 1 - 3 sec | Hard fallback for critical enterprise OTPs |
Common Pitfalls When Implementing Fallback Routing
1. Naive Retries Creating Duplicate Messages
If a provider HTTP call times out at 4000ms, it does not mean the message wasn't submitted to the telco. Retrying immediately via a secondary provider can result in users receiving two separate OTPs within seconds. Ensure your frontend handles verification code windows gracefully and use idempotency tokens across provider dispatches, similar to the reconciliation techniques detailed in Monnify and Paystack Webhook Silent Drops: Building a Poll-and-Lock Reconciliation Engine in Go.
2. Ignoring WhatsApp API Template Approval Latency
WhatsApp is significantly cheaper than international SMS while boasting higher delivery rates than traditional telco SMS. However, meta rules require using pre-approved message templates for business-initiated conversations. Attempting to fall back to WhatsApp on dynamic, unapproved string bodies will cause immediate execution failures.
3. Failing to Hard-Cap Dollar Costs on Lower SME Tiers
Allowing low-tier or trial SME accounts to fall back to Twilio SMS can expose your platform to SMS pumping fraud. A malicious actor can script requests to your registration endpoint, causing your system to dispatch thousands of Twilio SMS messages billed in USD. Enforce strict rate limits per IP and prohibit high-cost international fallback routes for unverified or free-tier organizations.
Frequently Asked Questions
Should we use WhatsApp webhooks or SMS for core OTP verification?
SMS remains the most frictionless default because it requires no active internet connection on the user's mobile device. However, providing a secondary "Send via WhatsApp" button on your login screen after a 30-second delay reduces international SMS costs by up to 70% while improving user conversion.
How do we handle DND (Do Not Disturb) blocking on Nigerian networks?
In Nigeria, users registered on the NCC DND database block promotional Sender IDs. To bypass this legally for transactional alerts (like OTPs and debit notifications), use Termii's hosted Sender ID with explicit dnd route flag setting or utilize a registered dynamic WhatsApp template.
Why not use AWS SNS for local Nigerian SMS dispatch?
AWS Simple Notification Service (SNS) routes West African destination numbers through international aggregators by default, resulting in pricing similar to Twilio ($0.05 - $0.07 per message). Unless you have contracted negotiated local enterprise routes with AWS, local aggregators remain far more cost-effective for domestic traffic.
Actionable Summary
Building an SME SaaS in emerging markets requires managing third-party vendor unit economics as strictly as core code. Do not rely on a single vendor for critical infrastructure. Segment notification payloads by urgency, measure real-time provider latencies with Redis circuit breakers, and enforce provider cost limits by customer tier.
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.