Skip to content
    Automation Guide

    Building an SMS Notification Systemwith API: Complete Guide

    Build a robust, scalable SMS notification system using the NotifyTech AI API. Covers webhooks, retries, delivery tracking, and multi-provider fallback.

    99.9%

    Uptime

    < 3s

    OTP Delivery

    3×

    Auto Retries

    NotifyTech AI Team Jan 12, 2024 11 min read Automation
    Overview

    Why You Need a Proper Notification System

    Calling the SMS API directly on every event works for prototypes — but breaks at scale. Without a queue, retries, and fallback logic, a single provider outage or traffic spike means thousands of lost OTPs, missed order alerts, and angry customers. A properly architected notification system handles all of this automatically.

    This guide walks you through building a production-grade SMS notification system: from event triggers and message queues to delivery tracking and monitoring — with working code in Node.js, Python, and TypeScript.

    Notification Types

    What Your System Needs to Handle

    Different notification types have very different latency and volume requirements

    OTP / Verification

    · Login OTP· Payment verification· Account activation

    Volume

    Very High

    Latency

    < 3s

    Category

    Transactional

    Order Alerts

    · Order confirmed· Shipped· Out for delivery

    Volume

    High

    Latency

    < 10s

    Category

    Transactional

    Payment Updates

    · Payment received· Refund processed· Invoice

    Volume

    High

    Latency

    < 5s

    Category

    Transactional

    Appointment Reminders

    · Doctor appointment· Demo scheduled· Delivery slot

    Volume

    Medium

    Latency

    < 1m

    Category

    Service

    Bulk Campaigns

    · Flash sale· Newsletter· Re-engagement

    Volume

    Very High

    Latency

    Scheduled

    Category

    Promotional

    Architecture

    System Architecture Components

    Six layers that make your notification system production-ready, scalable, and resilient

    Event Trigger Layer

    Detects events from your application (new order, payment, OTP request) and dispatches them to the notification queue.

    • REST API or event bus integration
    • Supports webhooks and polling
    • De-duplication to prevent double sends

    Message Queue

    Buffers notifications during traffic spikes. Uses Redis or SQS to ensure zero message loss even under 10,000+ req/min load.

    • FIFO ordering guaranteed
    • Configurable concurrency limits
    • Dead-letter queue for failed jobs

    SMS API Gateway

    Routes messages through the NotifyTech AI API with automatic DLT compliance, rate limiting, and provider selection.

    • Auto DLT template matching
    • Per-sender rate limiting
    • Multi-provider routing logic

    Retry & Fallback Engine

    Handles delivery failures gracefully with exponential backoff retries and automatic failover to secondary providers.

    • Exponential backoff (1s → 30s → 5m)
    • Provider failover in < 2 seconds
    • Max 3 retries before dead letter

    Delivery Tracking

    Real-time delivery receipts via webhooks. Tracks sent → delivered → read status for every message.

    • Webhook delivery confirmations
    • Per-message status history
    • Delivery rate dashboard

    Analytics & Alerts

    Monitors delivery rates, latency, and errors. Triggers Slack/email alerts when delivery drops below threshold.

    • Real-time delivery rate monitoring
    • Anomaly detection & alerting
    • Cost tracking per campaign
    Code Examples

    Production-Ready Code

    Copy-paste snippets for queue setup, retry logic, fallback handling, and delivery webhooks

    Webhook Handler + Queue
    Node.js
    const express = require('express');
    const Queue   = require('bull');
    
    const smsQueue = new Queue('sms', { redis: { host: 'localhost' } });
    
    // Trigger SMS on order event
    app.post('/webhooks/order-placed', async (req, res) => {
      const { phone, orderId, amount } = req.body;
    
      await smsQueue.add({
        to: phone,
        message: `Order #${orderId} confirmed! Amount: ₹${amount}. Track: https://mystore.in/track/${orderId}`,
        templateId: 'ORDER_CONFIRM_001',
      }, { attempts: 3, backoff: { type: 'exponential', delay: 1000 } });
    
      res.json({ queued: true });
    });
    
    // Queue worker
    smsQueue.process(async (job) => {
      const { to, message, templateId } = job.data;
      await sendSMS({ to, message, templateId });
    });
    Delivery Tracking + Retry Logic
    Python
    import time, requests
    from celery import Celery
    
    app = Celery('sms', broker='redis://localhost/0')
    
    @app.task(bind=True, max_retries=3)
    def send_notification(self, phone, message, template_id):
        try:
            r = requests.post('https://api.notifytechai.com/v1/sms/send',
                json={'to': phone, 'message': message, 'template_id': template_id},
                headers={'Authorization': f'Bearer {API_KEY}'}, timeout=10)
            r.raise_for_status()
    
            msg_id = r.json()['message_id']
            track_delivery(msg_id)  # async delivery check
            return {'success': True, 'id': msg_id}
    
        except Exception as exc:
            delay = 2 ** self.request.retries  # 1s, 2s, 4s
            raise self.retry(exc=exc, countdown=delay)
    
    def track_delivery(message_id, poll_interval=5, max_attempts=12):
        for _ in range(max_attempts):
            r = requests.get(f'.../status/{message_id}', ...)
            status = r.json().get('status')
            if status in ('DELIVERED', 'FAILED'): return status
            time.sleep(poll_interval)
    Multi-Provider Fallback
    TypeScript
    interface SMSProvider { name: string; send: (payload: SMSPayload) => Promise<string>; }
    
    const providers: SMSProvider[] = [
      { name: 'NotifyTech AI', send: notifytechSend },
      { name: 'Fallback-1',  send: fallback1Send  },
    ];
    
    async function sendWithFallback(payload: SMSPayload): Promise<string> {
      for (const provider of providers) {
        try {
          const msgId = await provider.send(payload);
          console.log(`[SMS] Sent via ${provider.name}: ${msgId}`);
          return msgId;
        } catch (err) {
          console.warn(`[SMS] ${provider.name} failed, trying next...`, err);
        }
      }
      throw new Error('All SMS providers failed — message dead-lettered');
    }
    
    // Webhook receiver for delivery status
    app.post('/webhooks/sms-delivery', (req, res) => {
      const { messageId, status, timestamp } = req.body;
      updateDeliveryStatus(messageId, status, timestamp);
      res.sendStatus(200);
    });
    Build Order

    6-Step Build Plan

    The right order to build each component — skip steps and you'll regret it at 3 AM

    01

    Design Your Event Schema

    1 day

    Map every user action that should trigger a notification. Define payload structure, priority levels, and channel routing rules.

    02

    Set Up Message Queue

    2–4h

    Deploy Redis + Bull (Node) or Celery (Python). Configure concurrency, retry policies, and dead-letter queues before writing any SMS code.

    03

    Integrate NotifyTech AI API

    1–2h

    Add the API client, map events to pre-approved DLT templates, and wire up the queue worker to call the send endpoint.

    04

    Implement Retry & Fallback

    2–4h

    Add exponential backoff, provider fallback logic, and dead-letter handling. Test failure scenarios with a mock failure endpoint.

    05

    Wire Up Delivery Webhooks

    1–2h

    Register your webhook URL with NotifyTech AI to receive real-time delivery status. Store status in DB and expose it to your frontend.

    06

    Add Monitoring & Alerts

    2–4h

    Hook delivery rate metrics into Grafana or Datadog. Set alerts for < 95% delivery rate. Log all failures with context for debugging.

    Ready to build?

    Start Building Today with Free API Access

    Get your API keys, explore the sandbox, and send your first notification in under 5 minutes. Full documentation included.

    We use cookies to improve your experience.

    By accepting, you agree to our cookie policy and analytics tracking.