Expertise technical

Manage withdrawals and SMS line in case of failure to send (architecture and code)

Retry queue sms fail to send: technical guide with code examples for developers in Morocco.

Manage withdrawals and SMS line in case of failure to send (architecture and code)
Table of Contents
  1. In software development, one often tends to consider that if an API call returns an error, it is enough to restart it.In the field of telecom messaging, and for SMS routing in Morocco, this naive approach is destructive.
  2. Why a naive retry can make the problem worse
  3. Distinguish Temporary and Permanent Errors
  4. The Exponential Backoff Strategy
  5. Example of implementation with Laravel Horizon / BullMQ

In software development, one often tends to consider that if an API call returns an error, it is enough to restart it.In the field of telecom messaging, and for SMS routing in Morocco, this naive approach is destructive.

Restarting a backlog SMS after a failure without analyzing the cause can result in massive overload (sending the same message to the customer 15 times), blocking your account by the [spam mechanism of the gateway] (/fr/blog/throttling-sms-au-maroc-a-qual-speed-can-you-really/), or flooding an already saturated network.

Here’s how to architect smart SMS failure management in a production environment, with resilient queues.

Why a naive retry can make the problem worse

Imagine that Maroc Telecom (IAM) is undergoing a micro-cutting network of 2 minutes. Your system is trying to send 1000 urgent transaction alerts. The API returns a timeout or a server error HTTP 503. If your code makes a simple while(failed) {retry(); }, you will bombard the API with 1000 additional requests every second. As soon as the network is restored, the waiting row of the gateway will receive 50 000 requests at a time, which will likely cause it to collapse again.

Distinguish Temporary and Permanent Errors

Before considering a Retry, your code must read the HTTP error code or the DLR status of the API.

Never repeat (Permanent Error): - HTTP 400: The destination number is incorrectly formatted. - HTTP 401 / 403: Your API key has expired or the Sender ID is blocked. - DLR Failed: The operator confirms that the number does not exist.

When to reset (Temporary Error): - HTTP 429: You hit the speed limit (Rate Limit). - HTTP 500 / 502 / 503: The SMS gateway or Moroccan network connection is temporarily unavailable.

The Exponential Backoff Strategy

The Exponential Backoff is an algorithm that spaces the time between each reset attempt. Instead of trying every second, you try again after 2 seconds, then 4, then 8, then 16. A "Jitter" (a random variation) is added to it to prevent all your server processes from performing the reset at exactly the same microsecond (causing a new peak).

Example of implementation with Laravel Horizon / BullMQ

In modern architectures, retry is not managed in the HTTP controller. The message is pushed into a Message Broker (such as Redis) and a Worker is left to handle it.

In PHP (Laravel Queues) Laravel elegantly manages the exponential backoff directly in the properties of your "Jobs".

php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendSmsNotification implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $phoneNumber;
    public $message;

    // Nombre maximal de tentatives (ex: abandonner après 5 essais)
    public $tries = 5;

    // Algorithme de recul : réessayer après 2s, 10s, 30s, 60s
    public function backoff()
    {
        return [2, 10, 30, 60];
    }

    public function handle()
    {
        $response = EnvoiSmsApi::send($this->phoneNumber, $this->message);

        // Si l'API renvoie un 400 (erreur permanente), on abandonne tout de suite
        if ($response->status === 400) {
            $this->fail(new \Exception('Numéro invalide, abandon.'));
            return;
        }

        // Si c'est une erreur 503, la fonction va naturellement throw une exception
        // et Laravel replacera le Job dans la file d'attente avec le backoff prévu.
        if (!$response->successful()) {
            throw new \Exception('Erreur temporaire API.');
        }
    }
}

The OTP expiration rule If you manage sending codes OTP for 2FA authentication, a retry can be dangerous. If the SMS ends up arriving 15 minutes later after 4 network retreats, the code generated in your database will already expire, generating customer frustration. For critical OTPs, limit the tries to a maximum of 2, and if this fails, instead implement a business Fallback (propose a voice call or [send WhatsApp]/fr/blog/whatsapp-pot-vs-sm-s-maroc/)) directly on the user interface, rather than re-send the SMS silently.

Why choose EnvoiSMS for your business?

Carrier Delivery

Local routes to IAM, Orange and Inwi, with automatic failover between routes and delivery status sent by webhook.

Cost Optimization

WhatsApp Business API from 0.65 MAD per message with optimal ROI.

Sovereign Data (CNDP)

Full compliance with Moroccan personal data protection regulations (CNDP).

How do I track routing on the IAM, Inwi and Orange networks?
Our local routes to Maroc Telecom (IAM), Orange and inwi, with automatic failover between routes, return a carrier delivery status for every message, by webhook. Delivery time depends on the recipient's carrier and network.
How does the platform manage the format of Moroccan numbers?
EnvoiSMS automatically normalizes the numbers entered (06..., 07..., 00212...) to the E.164 standard (+212) to avoid any delivery failure.

Suggested Articles

SMS Formatting in Morocco: Line Breaks, GSM-7 vs UCS-2 Encoding and Cost Optimization
technical

SMS Formatting in Morocco: Line Breaks, GSM-7 vs UCS-2 Encoding and Cost Optimization

WhatsApp Business Formatting in Morocco: Enriched Text, Emojis and Interactive Buttons
technical

WhatsApp Business Formatting in Morocco: Enriched Text, Emojis and Interactive Buttons

One-Tap Autofill & 1-Click WhatsApp OTP Authentication in Morocco
technical

One-Tap Autofill & 1-Click WhatsApp OTP Authentication in Morocco