Bulk SMS

MessageBird Bulk SMS Tutorial: Build Broadcasting System with Node.js & Express

Build a scalable bulk SMS system with MessageBird API, Express.js, and PostgreSQL. Handle 50-recipient batches, retries, and job tracking. Production-ready tutorial.

JH
Jacky Hossein
β€’ Principal Telecommunications Architect β€’ Published Nov 2, 2026 β€’ 13 min read

Developer Quick-Start: Build a scalable bulk SMS system with MessageBird API, Express.js, and PostgreSQL. Handle 50-recipient batches, retries, and job tracking. Production-ready tutorial. Want to skip 10DLC vetting queues, carrier surcharges, and multi-step SDK boilerplate? You can send the same SMS directly via SMSRoute's REST API with instant no-KYC provisioning.

Build a production-ready bulk SMS broadcasting system using the MessageBird API with Node.js and Express.js. This tutorial shows you how to create a scalable SMS API that handles thousands of recipients, implements batch processing (50 recipients per batch), includes retry logic, and tracks delivery status with PostgreSQL.

You'll implement a complete bulk SMS solution with job tracking, webhook integration, error handling, and status monitoring – solving the challenge of reliably notifying large user groups without overwhelming your infrastructure or the MessageBird API.

Technologies Used:

  • Node.js: JavaScript runtime for server-side applications
  • Express.js: Minimal web application framework for Node.js
  • MessageBird: Communication platform API for SMS, Voice, and WhatsApp (using SMS API and Node.js SDK)
  • PostgreSQL: Open-source relational database for tracking jobs and recipient status
  • Prisma: Modern database toolkit simplifying database access and migrations
  • dotenv: Environment variable loader
  • winston: Structured logging library
  • async-retry: Retry logic implementation
  • express-rate-limit: API rate limiting middleware
  • helmet: Security headers middleware
  • express-validator: Input validation middleware

System Architecture:

graph LR
    A[Client/User] -- API Request (POST /api/broadcast/sms) --> B(Express API Server);
    B -- Validate Request & Create Job --> C{Database (PostgreSQL)};
    B -- Batch Recipients & Send (Async) --> D(Messaging Service);
    D -- Uses MessageBird SDK --> E[MessageBird API];
    E -- Sends SMS --> F((Recipients));
    E -- Sends Status Webhook --> B;
    B -- Updates Job/Recipient Status --> C;
    G[Monitoring/Logging] -- Observes --> B;
    G -- Observes --> C;

(Note: Mermaid diagram rendering depends on the platform displaying this article.)

How It Works:

  1. Your client sends a POST request to /api/broadcast/sms with recipients and message content
  2. The Express API validates the request and creates a job in PostgreSQL
  3. The Messaging Service splits recipients into 50-person batches
  4. Each batch is sent to MessageBird API with exponential backoff retry logic
  5. MessageBird sends the SMS to recipients and returns delivery status
  6. Webhooks notify your server of delivery events
  7. The database updates job and recipient statuses
  8. Winston logs all operations for monitoring and debugging

Prerequisites:

Before starting, ensure you have:

  • Node.js 14+ and npm (or yarn) installed on your system
  • A MessageBird account with an API Access Key (get your key here)
  • PostgreSQL 12+ database access
  • Basic familiarity with Node.js, Express, and REST APIs
  • Docker installed (optional, for easier database setup)

What You'll Build:

  1. A functional Express.js application with proper structure
  2. An API endpoint (/api/broadcast/sms) for triggering bulk SMS campaigns
  3. MessageBird integration sending SMS efficiently in 50-recipient batches
  4. Database persistence tracking broadcast jobs and recipient statuses
  5. Security measures including API key authentication, rate limiting, and input validation
  6. Robust error handling with exponential backoff retry logic
  7. Structured logging with Winston for monitoring and debugging
  8. Deployment-ready configuration with graceful shutdown

Time Estimate: 2–3 hours | Skill Level: Intermediate


Set Up Your Bulk SMS Broadcasting Project

Initialize your Node.js project and configure the basic structure and dependencies. By the end of this section, you'll have a complete project skeleton with all required dependencies and a running Express server.

  1. Create Project Directory:
   mkdir node-messagebird-bulk-sms
   cd node-messagebird-bulk-sms
  1. Initialize Node.js Project:
   npm init -y
  1. Install Core Dependencies:
   npm install express dotenv messagebird @prisma/client winston async-retry express-rate-limit helmet express-validator
  • express: Web framework
  • dotenv: Environment variable loader
  • messagebird: Official MessageBird Node.js SDK
  • @prisma/client: Prisma database client
  • winston: Structured logging
  • async-retry: Retry mechanism
  • express-rate-limit: API rate limiting
  • helmet: Security headers
  • express-validator: Input validation
  1. Install Development Dependencies:
   npm install -D nodemon prisma jest supertest nock
  • nodemon: Auto-restart server during development
  • prisma: Prisma CLI tool
  • jest, supertest, nock: Testing tools for unit, integration, and E2E tests
  1. Set up Project Structure: Create the following directories and files:
   node-messagebird-bulk-sms/
   β”œβ”€β”€ prisma/
   β”‚   └── schema.prisma
   β”œβ”€β”€ src/
   β”‚   β”œβ”€β”€ controllers/
   β”‚   β”‚   β”œβ”€β”€ broadcastController.js
   β”‚   β”‚   └── webhookController.js
   β”‚   β”œβ”€β”€ routes/
   β”‚   β”‚   β”œβ”€β”€ broadcastRoutes.js
   β”‚   β”‚   └── webhookRoutes.js
   β”‚   β”œβ”€β”€ services/
   β”‚   β”‚   └── messagingService.js
   β”‚   β”œβ”€β”€ middleware/
   β”‚   β”‚   β”œβ”€β”€ authMiddleware.js
   β”‚   β”‚   β”œβ”€β”€ errorMiddleware.js
   β”‚   β”‚   └── webhookVerificationMiddleware.js # Placeholder
   β”‚   β”œβ”€β”€ utils/
   β”‚   β”‚   β”œβ”€β”€ logger.js
   β”‚   β”‚   └── prismaClient.js
   β”‚   └── app.js
   β”œβ”€β”€ tests/ # Optional
   β”‚   └── services/
   β”‚       └── messagingService.test.js
   β”œβ”€β”€ .env
   β”œβ”€β”€ .gitignore
   β”œβ”€β”€ Dockerfile # Optional
   β”œβ”€β”€ package.json
   └── server.js

File Responsibilities:

Directory/File Purpose
prisma/schema.prisma Database schema definition and migrations
src/controllers/ Request handling and validation logic
src/routes/ API endpoint definitions and routing
src/services/ Business logic for SMS sending and batch processing
src/middleware/ Authentication, error handling, and webhook verification
src/utils/ Logging and database client configuration
server.js Application entry point with graceful shutdown
src/app.js Express configuration and middleware setup
  1. Configure nodemon and Scripts: Update the scripts section in your package.json:
   {

     "scripts": {
       "start": "node server.js",
       "dev": "nodemon server.js",
       "test": "jest",
       "prisma:dev": "prisma migrate dev",
       "prisma:deploy": "prisma migrate deploy",
       "prisma:studio": "prisma studio",
       "prisma:generate": "prisma generate"
     }

   }
  1. Create .gitignore:
   # .gitignore
   node_modules/
   .env
   dist/
   npm-debug.log*
   yarn-debug.log*
   yarn-error.log*
   coverage/
   prisma/migrations/*.sql # Exclude generated SQL if desired
  1. Set up Basic Express Server (server.js):
   require('dotenv').config();
   const http = require('http');
   const app = require('./src/app');
   const logger = require('./src/utils/logger');
   const prisma = require('./src/utils/prismaClient');

   const PORT = process.env.PORT || 3000;

   const server = http.createServer(app);

   server.listen(PORT, () => {
     console.log(`Server running on port ${PORT}`);
   });

   const signals = {
     'SIGHUP': 1, 'SIGINT': 2, 'SIGTERM': 15
   };

   Object.keys(signals).forEach((signal) => {
     process.on(signal, () => {
       logger.info(`Received ${signal}, closing HTTP server...`);
       server.close(() => {
         logger.info('HTTP server closed.');
         prisma.$disconnect().then(() => {
             logger.info('Database connection closed.');
             process.exit(128 + signals[signal]);
         }).catch(err => {
             logger.error('Error disconnecting database:', err);
             process.exit(1);
         });
       });
     });
   });
  1. Configure Express Application (src/app.js):
   const express = require('express');
   const helmet = require('helmet');
   const broadcastRoutes = require('./routes/broadcastRoutes');
   const webhookRoutes = require('./routes/webhookRoutes');
   const { errorMiddleware } = require('./middleware/errorMiddleware');
   const logger = require('./utils/logger');
   const prisma = require('./utils/prismaClient');

   const app = express();

   app.use(helmet());

   app.use(express.json({ limit: '1mb' }));
   app.use(express.urlencoded({ extended: true }));

   app.use((req, res, next) => {
     logger.info(`${req.method} ${req.originalUrl}`, { ip: req.ip });
     res.on('finish', () => {
       logger.info(`${res.statusCode} ${res.statusMessage}; ${res.get('Content-Length') || 0}b sent`, { url: req.originalUrl });
     });
     next();
   });

   app.get('/health', async (req, res) => {
     try {

       await prisma.$queryRaw`SELECT 1`;
       res.status(200).json({ status: 'UP', timestamp: new Date().toISOString(), database: 'connected' });
     } catch (dbError) {
       logger.error('Health check failed - database connection error:', dbError);
       res.status(503).json({ status: 'DOWN', timestamp: new Date().toISOString(), database: 'disconnected', error: dbError.message });
     }
   });

   app.use('/api/broadcast', broadcastRoutes);
   app.use('/webhooks', webhookRoutes);

   app.use(errorMiddleware);

   module.exports = app;
  1. Environment Variables (.env):

Create a .env file in the root directory. Add .env to .gitignore to protect sensitive credentials. .env

    # .env

    # Server Configuration
    PORT=3000
    NODE_ENV=development # development, production
    LOG_LEVEL=info # debug, info, warn, error

    # MessageBird Configuration
    MESSAGEBIRD_API_KEY=YOUR_LIVE_MESSAGEBIRD_API_KEY
    MESSAGEBIRD_ORIGINATOR=YourSenderID
    MESSAGEBIRD_WEBHOOK_SIGNING_KEY=YOUR_MESSAGEBIRD_WEBHOOK_SECRET # For webhook verification

    # Database Configuration (Prisma standard)
    DATABASE_URL="postgresql://user:password@localhost:5432/bulk_sms?schema=public"

    # Security
    INTERNAL_API_KEY=a_very_secret_key_for_internal_use

How to Get Your MessageBird Credentials:

  1. Sign up at MessageBird Dashboard
  2. Navigate to Developers β†’ API Access
  3. Copy your Live API Key (starts with live\_)
  4. Configure your sender ID (alphanumeric, max 11 characters, or phone number)
  5. Generate a webhook signing key for webhook verification

Security Notes:

  • Never commit .env to version control
  • Use different API keys for development and production
  • Rotate API keys regularly
  • Use environment-specific secrets management in production (AWS Secrets Manager, HashiCorp Vault)
  1. Setup Logging (src/utils/logger.js):
    const winston = require('winston');

    const logger = winston.createLogger({
      level: process.env.LOG_LEVEL || 'info',
      format: winston.format.combine(
        winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        winston.format.errors({ stack: true }),
        winston.format.splat(),
        winston.format.json()
      ),
      defaultMeta: { service: 'bulk-sms-service' },
      transports: [



      ],

       exceptionHandlers: [
         new winston.transports.Console({
             format: winston.format.combine(winston.format.colorize(), winston.format.simple())
         }),

       ],
       rejectionHandlers: [
          new winston.transports.Console({
             format: winston.format.combine(winston.format.colorize(), winston.format.simple())
         }),

       ]
    });

    if (process.env.NODE_ENV !== 'production') {
      logger.add(new winston.transports.Console({
        format: winston.format.combine(
          winston.format.colorize(),
          winston.format.printf(({ level, message, timestamp, stack, ...metadata }) => {
             let msg = `${timestamp} ${level}: ${message}`;
             if (stack) {
                 msg += `\n${stack}`;
             }
             if (Object.keys(metadata).length > 0) {

                 const filteredMeta = Object.keys(metadata)
                    .filter(key => key !== 'service')
                    .reduce((obj, key) => { obj[key] = metadata[key]; return obj; }, {});
                 if (Object.keys(filteredMeta).length > 0) {
                    msg += ` ${JSON.stringify(filteredMeta)}`;
                 }
             }
             return msg;
         })
        )
      }));
    }

    module.exports = logger;

Log Levels:

  • error – System failures requiring immediate attention
  • warn – Issues that don't stop execution but need review
  • info – General application events (default)
  • debug – Detailed diagnostic information

Production Logging: Integrate with CloudWatch, DataDog, or LogDNA by adding Winston transports for your chosen service.

  1. Setup Prisma Client (src/utils/prismaClient.js):
    const { PrismaClient } = require('@prisma/client');
    const logger = require('./logger');

    const prisma = new PrismaClient({
        log: [
            { emit: 'event', level: 'query' },
            { emit: 'stdout', level: 'info' },
            { emit: 'stdout', level: 'warn' },
            { emit: 'stdout', level: 'error' },
        ],
    });

    prisma.$on('query', (e) => {
      logger.debug(`Query: ${e.query}`, { params: e.params, duration: e.duration });
    });

    module.exports = prisma;

Implement the Bulk SMS Sending Service

This service handles the core SMS sending logic with batch processing, retry mechanisms, and database updates. The design splits large recipient lists into 50-person batches to comply with MessageBird API limits and implements exponential backoff for transient failures.

  1. Create Messaging Service (src/services/messagingService.js):
   const { initClient } = require('messagebird');
   const retry = require('async-retry');
   const prisma = require('../utils/prismaClient');
   const logger = require('../utils/logger');

   let messagebird;
   try {
       if (!process.env.MESSAGEBIRD_API_KEY) {
           throw new Error('MESSAGEBIRD_API_KEY environment variable not set.');
       }
       messagebird = initClient(process.env.MESSAGEBIRD_API_KEY);
       logger.info('MessageBird client initialized successfully.');
   } catch (error) {
       logger.error('Failed to initialize MessageBird client:', error);


       throw error;
   }

   const BATCH_SIZE = 50;

   async function sendBatch(batchRecipients, messageBody, originator) {
       const params = {
           originator: originator,
           recipients: batchRecipients,
           body: messageBody,


       };

       return new Promise((resolve, reject) => {
           if (!messagebird) {

                return reject(new Error('MessageBird client not initialized.'));
           }
           messagebird.messages.create(params, (err, response) => {
               if (err) {
                   logger.error('MessageBird API Error:', { code: err.code, message: err.message, errors: err.errors });

                   err.recipients = batchRecipients;
                   return reject(err);
               }


               logger.info(`Batch sent successfully via MessageBird. Batch Response ID: ${response?.id}`);
               resolve(response);
           });
       });
   }

   async function sendBulkSms(broadcastJobId, recipients, messageBody, originator) {
        logger.info(`Starting bulk SMS send for job ID: ${broadcastJobId}. Total recipients: ${recipients.length}`, { jobId: broadcastJobId });

       let successfulBatches = 0;
       let failedBatches = 0;

       for (let i = 0; i < recipients.length; i += BATCH_SIZE) {
           const batch = recipients.slice(i, i + BATCH_SIZE);
           const batchIndex = Math.floor(i / BATCH_SIZE) + 1;
            logger.info(`Processing batch ${batchIndex} with ${batch.length} recipients.`, { jobId: broadcastJobId, batch: batchIndex });

           try {
                await retry(
                   async (bail, attemptNumber) => {
                        logger.info(`Attempt ${attemptNumber} for batch ${batchIndex}`, { jobId: broadcastJobId, batch: batchIndex, attempt: attemptNumber });
                        try {
                           const response = await sendBatch(batch, messageBody, originator);


                           if (response && response.recipients && response.recipients.items) {
                               const updates = response.recipients.items.map(item => ({
                                   where: {
                                       broadcastJobId_phoneNumber: {
                                           broadcastJobId: broadcastJobId,
                                           phoneNumber: String(item.recipient)
                                       }
                                   },
                                   data: {
                                       initialStatus: item.status,
                                       statusTimestamp: item.statusDatetime ? new Date(item.statusDatetime) : new Date(),
                                       messageId: response.id
                                   }
                               }));

                               if (updates.length > 0) {

                                   const result = await prisma.$transaction(
                                      updates.map(update => prisma.recipientStatus.update(update))
                                   );
                                   logger.info(`Successfully processed batch ${batchIndex}. Updated initial status for ${result.length} recipients.`, { jobId: broadcastJobId, batch: batchIndex, count: result.length });
                               } else {
                                    logger.warn(`No recipient status updates to perform for batch ${batchIndex}.`, { jobId: broadcastJobId, batch: batchIndex });
                               }

                           } else {
                                logger.warn(`No recipient status details found in MessageBird response for batch ${batchIndex}.`, { jobId: broadcastJobId, batch: batchIndex, response });
                           }


                        } catch (error) {
                            logger.warn(`Error sending batch ${batchIndex} on attempt ${attemptNumber}: ${error.message}`, { jobId: broadcastJobId, batch: batchIndex, attempt: attemptNumber, error });


                            const isRetryable = !error.statusCode || error.statusCode >= 500 || (error.code && ['ETIMEDOUT', 'ECONNRESET', 'ECONNREFUSED'].includes(error.code));

                            if (!isRetryable) {
                                logger.error(`Unrecoverable error for batch ${batchIndex}. Stopping retries.`, { jobId: broadcastJobId, batch: batchIndex, error });

                                try {
                                    await prisma.recipientStatus.updateMany({
                                         where: { broadcastJobId: broadcastJobId, phoneNumber: { in: batch.map(String) }},
                                         data: { initialStatus: 'failed', statusTimestamp: new Date(), errorMessage: `Non-retryable error: ${error.message}` }
                                    });
                                    logger.info(`Marked ${batch.length} recipients as failed due to non-retryable error in batch ${batchIndex}.`, { jobId: broadcastJobId, batch: batchIndex });
                                } catch (dbError) {
                                    logger.error('Database error updating status for non-retryable batch failure:', { jobId: broadcastJobId, batch: batchIndex, dbError });
                                }
                                bail(error);
                                return;
                            }
                            throw error;
                        }
                   },
                   {
                       retries: 3,
                       factor: 2,
                       minTimeout: 1000,
                       maxTimeout: 5000,
                       onRetry: (error, attemptNumber) => {
                            logger.warn(`Retrying batch ${batchIndex} (Attempt ${attemptNumber}) due to error: ${error.message}`, { jobId: broadcastJobId, batch: batchIndex, attempt: attemptNumber });
                       }
                   }
               );
               successfulBatches++;

           } catch (error) {

                logger.error(`Failed to send batch ${batchIndex} after multiple retries: ${error.message}`, { jobId: broadcastJobId, batch: batchIndex, error });
                failedBatches++;

                 try {
                    await prisma.recipientStatus.updateMany({
                        where: { broadcastJobId: broadcastJobId, phoneNumber: { in: batch.map(String) }},
                        data: { initialStatus: 'failed', statusTimestamp: new Date(), errorMessage: `Failed after retries: ${error.message}` }
                    });
                     logger.warn(`Marked ${batch.length} recipients as failed for batch ${batchIndex} after retries.`, { jobId: broadcastJobId, batch: batchIndex, count: batch.length });
                 } catch (dbError) {
                      logger.error('Database error during final batch failure update:', { jobId: broadcastJobId, batch: batchIndex, dbError });
                 }


           }


       }

        logger.info(`Finished processing all batches for job ID: ${broadcastJobId}. Successful: ${successfulBatches}, Failed: ${failedBatches}`, { jobId: broadcastJobId });


        let finalJobStatus = 'processing_complete';
        if (failedBatches > 0 && successfulBatches === 0) {
            finalJobStatus = 'failed';
        } else if (failedBatches > 0) {
            finalJobStatus = 'partially_failed';
        }


        try {
            await prisma.broadcastJob.update({
                where: { id: broadcastJobId },
                data: { status: finalJobStatus, completedAt: new Date() }
            });
            logger.info(`Updated final job status for job ${broadcastJobId} to '${finalJobStatus}'`, { jobId: broadcastJobId, status: finalJobStatus });
        } catch (dbError) {
             logger.error(`Failed to update final job status for job ${broadcastJobId}:`, { jobId: broadcastJobId, dbError });
        }
   }

   module.exports = {
       sendBulkSms,
   };

Retry Configuration Explained:

Parameter Value Why
retries 3 Allows up to 4 total attempts (1 initial + 3 retries)
factor 2 Exponential backoff: 1s β†’ 2s β†’ 4s delays
minTimeout 1000 ms Initial delay before first retry
maxTimeout 5000 ms Cap on delay to prevent excessive waits

Error Classification:

  • Retryable (5xx, network errors): Temporary failures, retry with backoff
  • Non-retryable (4xx): Invalid phone numbers, authentication issues – fail immediately

Throughput: With 50-recipient batches and 3-second average API response, expect ~1,000 messages/minute. Adjust batch delays if you hit MessageBird rate limits.


Build the API Layer

Create RESTful endpoints for triggering SMS broadcasts and checking job status. The API follows standard REST conventions: POST for creating jobs, GET for retrieving status.

  1. Create Authentication Middleware (src/middleware/authMiddleware.js):
   const logger = require('../utils/logger');

   function apiKeyAuth(req, res, next) {
       const apiKey = req.headers['x-api-key'];
       const expectedApiKey = process.env.INTERNAL_API_KEY;

       if (!expectedApiKey) {
            logger.error('INTERNAL_API_KEY is not set in environment variables. API is insecure.');

            return res.status(500).json({ message: 'Internal Server Error' });
       }

       if (!apiKey || apiKey !== expectedApiKey) {
           logger.warn('Unauthorized API access attempt denied.', { ip: req.ip, keyProvided: !!apiKey });
           return res.status(401).json({ message: 'Unauthorized' });
       }

       next();
   }

   module.exports = { apiKeyAuth };

Why API Key Authentication? This tutorial uses simple API key authentication for clarity. For production systems handling sensitive data, consider JWT tokens or OAuth 2.0. Add rate limiting with express-rate-limit to prevent abuse:

const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100
});

app.use('/api/broadcast', limiter);
  1. Create Broadcast Controller (src/controllers/broadcastController.js):
   const { validationResult, body } = require('express-validator');
   const { sendBulkSms } = require('../services/messagingService');
   const prisma = require('../utils/prismaClient');
   const logger = require('../utils/logger');

   const validateBroadcastRequest = [
       body('recipients').isArray({ min: 1 }).withMessage('Recipients must be a non-empty array.'),

       body('recipients.*')
          .isString().withMessage('Each recipient must be a string.')
          .trim()
          .matches(/^\+[1-9]\d{1,14}$/).withMessage('Invalid phone number. Use E.164 format (e.g., +14155552671).'),
       body('messageBody').isString().trim().notEmpty().withMessage('Message body cannot be empty.'),
       body('originator').optional().isString().trim().notEmpty().isLength({ max: 11 }).withMessage('Originator must be a non-empty string up to 11 characters if provided.')
   ];

   async function handleSendBulkSms(req, res, next) {
       const errors = validationResult(req);
       if (!errors.isEmpty()) {
           logger.warn('Broadcast request validation failed.', { errors: errors.array() });
           return res.status(400).json({ errors: errors.array() });
       }

       const { recipients, messageBody } = req.body;

       const originator = req.body.originator || process.env.MESSAGEBIRD_ORIGINATOR;

       if (!originator) {
            logger.error('Originator is missing. Configure MESSAGEBIRD_ORIGINATOR env var or provide in request.');
            return res.status(400).json({ message: 'Originator must be provided either in the request body or as MESSAGEBIRD_ORIGINATOR environment variable.' });
       }


       const uniqueRecipients = [...new Set(recipients.map(r => r.trim()))];
       if (uniqueRecipients.length !== recipients.length) {
           logger.info(`Duplicate recipients removed. Original: ${recipients.length}, Unique: ${uniqueRecipients.length}`);
       }

       let broadcastJob;
       try {

            broadcastJob = await prisma.broadcastJob.create({
               data: {
                   messageBody: messageBody,
                   originator: originator,
                   status: 'pending',
                   totalRecipients: uniqueRecipients.length,
                   recipients: {
                       create: uniqueRecipients.map(phone => ({
                           phoneNumber: String(phone),
                           initialStatus: 'pending'
                        }))
                   }
               },

           });

           logger.info(`Created broadcast job ${broadcastJob.id} with ${uniqueRecipients.length} unique recipients.`, { jobId: broadcastJob.id });



           setImmediate(() => {
               sendBulkSms(broadcastJob.id, uniqueRecipients, messageBody, originator)
                   .catch(error => {

                       logger.error(`Background processing initiation failed for job ${broadcastJob.id}:`, { jobId: broadcastJob.id, error });

                       prisma.broadcastJob.update({
                           where: { id: broadcastJob.id },
                           data: { status: 'failed_to_start', errorMessage: error.message || 'Unknown error during async start' }
                       }).catch(dbError => logger.error('DB error updating job status on async start failure:', { jobId: broadcastJob.id, dbError }));
                   });
           });


           res.status(202).json({
               message: 'Broadcast job accepted and is being processed.',
               jobId: broadcastJob.id,
               status: 'pending',
               recipientCount: uniqueRecipients.length
           });

       } catch (error) {
           logger.error('Error creating broadcast job or initiating send:', { error });

            if (broadcastJob && broadcastJob.id) {

                try {
                    await prisma.broadcastJob.update({
                       where: { id: broadcastJob.id },
                       data: { status: 'failed', errorMessage: 'Failed during job creation/initiation: ' + error.message }
                    });
                } catch (dbUpdateError) {
                    logger.error('DB error updating job status after initial creation failure:', { jobId: broadcastJob.id, dbUpdateError });
                }
            }
           next(error);
       }
   }


   async function handleGetJobStatus(req, res, next) {
       const jobId = parseInt(req.params.jobId, 10);
       if (isNaN(jobId)) {
           return res.status(400).json({ message: 'Invalid Job ID format.' });
       }

       try {
           const job = await prisma.broadcastJob.findUnique({
               where: { id: jobId },
               include: {

                   _count: {
                       select: { recipients: true }
                   },




               }
           });

           if (!job) {
               logger.warn(`Job status requested for non-existent job ID: ${jobId}`);
               return res.status(404).json({ message: `Job with ID ${jobId} not found.` });
           }











           res.status(200).json({
               jobId: job.id,
               status: job.status,
               totalRecipients: job.totalRecipients,
               createdAt: job.createdAt,
               completedAt: job.completedAt,

               recipientCount: job._count?.recipients,
               errorMessage: job.errorMessage
           });

       } catch (error) {
           logger.error(`Error fetching status for job ID ${jobId}:`, { jobId, error });
           next(error);
       }
   }

   module.exports = {
       validateBroadcastRequest,
       handleSendBulkSms,
       handleGetJobStatus
   };

Async Processing vs. Message Queues:

This tutorial uses setImmediate() for simplicity. For production systems with high volume:

  • Use Bull or BullMQ with Redis for durable job queues
  • Separate worker processes for better fault isolation
  • Add job prioritization for urgent messages
  • Implement dead letter queues for failed jobs

Pagination for Large Jobs: For jobs with 10,000+ recipients, implement pagination on the status endpoint:

const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 100;
const skip = (page - 1) * limit;

const recipients = await prisma.recipientStatus.findMany({
  where: { broadcastJobId: jobId },
  skip,
  take: limit
});

Simpler Alternative: Send the Same SMS With SMSRoute (No-KYC, Direct Routes)

If you want to replace legacy aggregator SDK boilerplate, multi-week compliance queues, and opaque carrier surcharges with a single HTTP request, SMSRoute delivers global SMS over direct Tier-1 carrier interconnects with instant API access and transparent per-country pricing.

curl -X POST https://api.sendsmsnokyc.com/messages \
  -H "x-api-key: $SMSROUTE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": ["+14155551234"],
    "channel": ["sms"],
    "body": "Your verification code is 482910"
  }'
  • Instant onboarding: No KYC paperwork or sales queues β€” grab an API key and fund with crypto (BTC/USDT) or card.
  • Direct Tier-1 routes: Verify real handset delivery, DLR latency, and Sender ID preservation before launch via SMSRoute Live Carrier Testing.
  • Transparent global pricing: Compare exact per-country termination rates on our live pricing page.

Ship Global SMS in One API Call

Skip legacy SDK sprawl and carrier bottlenecks. Send OTPs, alerts, and bulk campaigns across 190+ countries with SMSRoute.

Explore SMSRoute Developers β†’