Engineering

Telco API Failures in Nigeria: Ditch Celery for a Go Transactional Outbox Engine

O
Oluwaseun AlabiTechnical Director
October 25, 202612 min read
Telco API Failures in Nigeria: Ditch Celery for a Go Transactional Outbox Engine

Integrating MTN, Airtel, and Glo APIs using standard background queues like Celery leads to double debits and socket leaks during network drops. Here is why switching to a PostgreSQL Transactional Outbox pattern in Go is the only resilient way to handle high-volume Nigerian telco transactions.

If you have ever built a fintech app, bill payment service, or airtime API reseller in Nigeria, you know the pain: Nigerian telecom provider APIs (MTN, Airtel, Glo, 9mobile) do not behave like Stripe or AWS. They drop connections without warning. They return HTTP 504 Gateway Timeouts while secretly processing the underlying transaction. They lock up sockets for 45 seconds during evening network spikes, and they reject requests with cryptic error codes like ERR_PROVIDER_DOWN_99 that may or may not mean the customer's line was credited.

Most engineering teams approach this challenge by shoving HTTP requests into a standard background job queue like Celery or BullMQ. A user hits an endpoint to purchase ₦5,000 worth of data, the API controller deducts funds from the user's local database wallet inside a transaction, and then enqueues an asynchronous task to dispatch the HTTP payload to the telco aggregator.

This architecture is fragile. It breaks under load and bleeds cash through un-reconciled double debits.

When network partitions occur between your cloud servers in AWS eu-west-1 and a legacy aggregator gateway in Lagos, Celery workers enter retry loops that bombard unstable endpoints. Worse, if your server crashes right after deducting funds from the user's wallet but before pushing the job to Redis, the transaction vanishes into thin air.

To survive high-volume Nigerian telco integrations, you must stop treating background job queues as transactional state machines. You need the Transactional Outbox Pattern implemented natively inside PostgreSQL, consumed by a stateless Go daemon using worker pools and explicit circuit breakers.

An architectural diagram showing a database outbox table polled by Go workers dispatching requests to Nigerian Telco Gateways

Anatomy of a Telco Gateway Meltdown

To understand why traditional message queues fail, look at what actually happens during a standard airtime dispatch failure sequence:

  1. The DB Commit: User A requests a ₦2,000 airtime top-up. Your API route opens a database transaction, verifies User A has ₦2,000, updates their ledger balance to ₦0, and commits the transaction.
  2. The Queue Hand-off: Your application tries to push a message dispatch_airtime_job to Redis for Celery to pick up.
  3. The Silent Failure: If Redis throws a connection timeout at this exact millisecond, or if the application container receives a SIGKILL from Kubernetes OOMKilled, your database commit succeeded, but the job was never queued. User A lost ₦2,000 and received no airtime.

Suppose you invert the sequence—pushing to Celery first, then committing the wallet debit. If the database transaction fails due to a serialization check or lock contention, Celery still fires the HTTP request. You just gave away free airtime on an unbacked wallet balance.

Even when the job reaches Celery, standard retry logic exacerbates failures. Consider an HTTP 504 Gateway Timeout from an Airtel gateway. A timeout does not mean failure; it means absence of information. In 60% of 504 responses from Nigerian aggregators, the telco actually processed the top-up. If Celery blindly retries the job 3 seconds later because of an unhandled exception, your system sends a second HTTP POST request. The telco processes it again. You have now delivered ₦4,000 worth of airtime while only billing the customer ₦2,000.

We encountered similar edge cases when building real-time transaction ledgers for bank transfers. As detailed in our breakdown of Resolving NIP Ghost Credits: Building an Idempotent Bank Transfer Ledger Engine in Go, absolute synchronization between local state and external provider status is non-negotiable.

Benchmarking Architectural Patterns for Provider Integrations

Before picking an implementation, let us analyze the trade-offs across the three most common background processing models used by Nigerian backend engineering teams.

| Architectural Attribute | Dual-Write Redis Queue (Celery/BullMQ) | Temporal / Distributed Saga Orchestrator | PostgreSQL Transactional Outbox + Go Worker | | :--- | :--- | :--- | :--- | | ACID Guarantees | None (Dual-write problem) | High (Event-driven state) | Absolute (Atomic DB transaction) | | Infrastructure Complexity | Low (Requires Redis) | Very High (Requires Temporal Server, DB, Workers) | Minimal (Uses existing PostgreSQL DB) | | Handling HTTP 504 Timeouts | Poor (Naive retry backoff) | Good (Complex compensation sagas) | Excellent (Deterministic state machine) | | Operational Cost | Medium (Redis memory consumption) | High (Compute overhead for orchestration cluster) | Low (Single lightweight Go binary) | | Latency Impact | Low (~5ms) | Medium (~25ms orchestration overhead) | Extremely Low (~2ms database write) |

While Temporal is brilliant for multi-step distributed sagas, running a dedicated Temporal cluster for simple single-step telco top-ups adds unneeded infrastructure complexity for mid-sized engineering teams. The PostgreSQL Transactional Outbox pattern gives you the ACID safety of single-database commits with zero external message broker dependencies.

Building an Outbox Engine in Go with PostgreSQL

Instead of pushing jobs to Redis, the Transactional Outbox pattern writes the event payload into an outbox_events table inside the same PostgreSQL database transaction that debits the user's wallet. If the database transaction rolls back, the outbox record rolls back automatically. Dual-write inconsistencies are mathematically impossible.

Here is the core PostgreSQL table structure required for a robust outbox setup:

CREATE TYPE outbox_status AS ENUM (
    'PENDING',
    'PROCESSING',
    'SUCCESS',
    'FAILED_RETRYABLE',
    'REQUIRES_RECONCILIATION'
);

CREATE TABLE outbox_events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    aggregate_type VARCHAR(64) NOT NULL,
    aggregate_id VARCHAR(64) NOT NULL,
    payload JSONB NOT NULL,
    status outbox_status NOT NULL DEFAULT 'PENDING',
    retry_count INT NOT NULL DEFAULT 0,
    max_retries INT NOT NULL DEFAULT 5,
    last_error TEXT,
    next_retry_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Partial index for fast worker polling
CREATE INDEX idx_outbox_pending 
ON outbox_events (next_retry_at, created_at) 
WHERE status IN ('PENDING', 'FAILED_RETRYABLE');

Notice the partial index idx_outbox_pending. This ensures that as your outbox_events table grows to millions of rows, workers only scan the unfulfilled jobs, keeping query latency under 1 millisecond.

Concurrent Row Locking with Go

To consume these events safely across multiple Go worker replicas without race conditions, we use PostgreSQL's FOR UPDATE SKIP LOCKED clause. This allows dozens of parallel workers to claim unassigned outbox tasks simultaneously without blocking each other.

Here is the implementation of the Go polling engine using sony/gobreaker for automated circuit breaking when a provider drops connections:

package outbox

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"time"

	"github.com/sony/gobreaker"
)

type OutboxEvent struct {
	ID            string          `json:"id"`
	AggregateType string          `json:"aggregate_type"`
	AggregateID   string          `json:"aggregate_id"`
	Payload       json.RawMessage `json:"payload"`
	RetryCount    int             `json:"retry_count"`
}

type OutboxWorker struct {
	db      *sql.DB
	cb      *gobreaker.CircuitBreaker
	client  TelcoClient
}

func NewOutboxWorker(db *sql.DB, client TelcoClient) *OutboxWorker {
	st := gobreaker.Settings{
		Name:        "TelcoGateway",
		MaxRequests: 3,
		Interval:    10 * time.Second,
		Timeout:     30 * time.Second,
		ReadyToTrip: func(counts gobreaker.Counts) bool {
			failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
			return counts.Requests >= 5 && failureRatio >= 0.6
		},
	}
	return &OutboxWorker{
		db:     db,
		cb:     gobreaker.NewCircuitBreaker(st),
		client: client,
	}
}

func (w *OutboxWorker) ProcessNextBatch(ctx context.Context, batchSize int) error {
	// Use PostgreSQL's explicit row-locking mechanics
	// See PostgreSQL locking documentation: https://www.postgresql.org/docs/current/explicit-locking.html
	tx, err := w.db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	rows, err := tx.QueryContext(ctx, `
		SELECT id, aggregate_type, aggregate_id, payload, retry_count
		FROM outbox_events
		WHERE status IN ('PENDING', 'FAILED_RETRYABLE')
		  AND next_retry_at <= NOW()
		ORDER BY next_retry_at ASC
		LIMIT $1
		FOR UPDATE SKIP LOCKED
	`, batchSize)
	if err != nil {
		return err
	}
	defer rows.Close()

	var events []OutboxEvent
	for rows.Next() {
		var e OutboxEvent
		if err := rows.Scan(&e.ID, &e.AggregateType, &e.AggregateID, &e.Payload, &e.RetryCount); err != nil {
			return err
		}
		events = append(events, e)
	}

	for _, event := range events {
		w.executeDispatch(ctx, tx, event)
	}

	return tx.Commit()
}

func (w *OutboxWorker) executeDispatch(ctx context.Context, tx *sql.Tx, event OutboxEvent) {
	// Execute request through the circuit breaker
	_, err := w.cb.Execute(func() (interface{}, error) {
		return nil, w.client.SendAirtime(ctx, event.Payload)
	})

	if err != nil {
		newRetry := event.RetryCount + 1
		// Exponential backoff: 5s, 25s, 125s...
		backoffSeconds := int(time.Duration(newRetry*newRetry*5) * time.Second / time.Second)
		
		status := "FAILED_RETRYABLE"
		if newRetry >= 5 {
			status = "REQUIRES_RECONCILIATION"
		}

		_, _ = tx.ExecContext(ctx, `
			UPDATE outbox_events 
			SET status = $1, 
			    retry_count = $2, 
			    next_retry_at = NOW() + ($3 || ' seconds')::INTERVAL,
			    last_error = $4,
			    updated_at = NOW()
			WHERE id = $5
		`, status, newRetry, backoffSeconds, err.Error(), event.ID)
		log.Printf("[OUTBOX] Dispatch failed for event %s: %v", event.ID, err)
		return
	}

	// Success state handling
	_, _ = tx.ExecContext(ctx, `
		UPDATE outbox_events 
		SET status = 'SUCCESS', updated_at = NOW() 
		WHERE id = $1
	`, event.ID)
}

By leveraging FOR UPDATE SKIP LOCKED, you eliminate duplicate worker locks entirely. You can scale your Go consumer deployment from 2 containers to 20 containers during a flash sale, and each worker will pull a distinct slice of pending tasks without collision or locking overhead.

We covered similar concurrency control mechanisms when analyzing advisory locks vs Redis mutexes in Handling 500 Webhooks/Sec: Redis Mutexes vs Postgres Advisory Locks for Paystack Idempotency.

The Strongest Counterargument:

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.

Tags:#Go#PostgreSQL#System Design#Backend Engineering#Fintech

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.