To send SMS from Go at volume, run a fixed pool of goroutines that read messages from a channel, gate every request through a golang.org/x/time/rate limiter, give each call a context deadline, and retry with jitter using the same idempotency key. That keeps you under the provider's limits and stops a retry from texting someone twice.

We make Ready, so the code calls our REST API and uses only the request shape we document. The structure works with any provider. It assumes Go 1.21 or later and the golang.org/x/time module. If you haven't sent a single text from Go yet, start with how to send SMS in Go and come back.

The shape of the pool

Three pieces do the work. A buffered channel holds pending messages. N worker goroutines pull from it. One shared rate.Limiter makes every worker wait its turn before it touches the network.

The pool size and the rate limit are separate knobs, and mixing them up is a common mistake. Workers bound how many requests are in flight, which matters when the API is slow. The limiter bounds how many requests start per second, which matters when the API is fast. You need both.

The message and the sender

Give each message a stable id from your own database. It becomes the idempotency key, so a retry, a crash and a restart all send the same value for the same message.

package sms

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

const baseURL = "https://api.tryready.com"

type Message struct {
	ID   string // your own row id, used as the idempotency key
	To   string
	Body string
}

type sendRequest struct {
	To              string `json:"to"`
	Body            string `json:"body"`
	ConsentAttested bool   `json:"consent_attested"`
}

var client = &http.Client{Timeout: 20 * time.Second}

type result struct {
	status     int
	retryAfter time.Duration
	err        error
}

func send(ctx context.Context, m Message) result {
	payload, err := json.Marshal(sendRequest{To: m.To, Body: m.Body, ConsentAttested: true})
	if err != nil {
		return result{err: err}
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost,
		baseURL+"/v1/messages", bytes.NewReader(payload))
	if err != nil {
		return result{err: err}
	}
	req.Header.Set("X-API-Key", os.Getenv("READY_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Idempotency-Key", m.ID)

	resp, err := client.Do(req)
	if err != nil {
		return result{err: err}
	}
	defer resp.Body.Close()
	io.Copy(io.Discard, resp.Body) // drain so the connection can be reused

	var wait time.Duration
	if s := resp.Header.Get("Retry-After"); s != "" {
		var secs int
		if _, err := fmt.Sscanf(s, "%d", &secs); err == nil {
			wait = time.Duration(secs) * time.Second
		}
	}
	return result{status: resp.StatusCode, retryAfter: wait}
}

consent_attested: true is your statement that the recipient agreed to receive texts. In real code, set it from the consent record you keep for that contact, and don't send at all when you can't back it up.

Retry with jitter and a deadline

The retry loop has to answer one question for each outcome: is another try useful? A network error, a timeout, a 429 and a 5xx might succeed next time. Any other 4xx won't, because the request itself is wrong.

import (
	"errors"
	"math/rand"
)

func retryable(r result) bool {
	if r.err != nil {
		return !errors.Is(r.err, context.Canceled)
	}
	return r.status == 408 || r.status == 429 || r.status >= 500
}

func backoff(attempt int, floor time.Duration) time.Duration {
	base := 500 * time.Millisecond << attempt // 500ms, 1s, 2s, 4s
	d := time.Duration(rand.Int63n(int64(base))) // full jitter
	if d < floor {
		d = floor
	}
	return d
}

func sendWithRetry(ctx context.Context, lim *rate.Limiter, m Message) result {
	var r result
	for attempt := 0; attempt < 5; attempt++ {
		if err := lim.Wait(ctx); err != nil {
			return result{err: err}
		}
		callCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
		r = send(callCtx, m)
		cancel()

		if r.err == nil && r.status >= 200 && r.status < 300 {
			return r
		}
		if !retryable(r) {
			return r
		}
		select {
		case <-time.After(backoff(attempt, r.retryAfter)):
		case <-ctx.Done():
			return result{err: ctx.Err()}
		}
	}
	return r
}

Full jitter, a random wait between zero and the current ceiling, spreads retries out. Without it, a provider blip makes every worker retry at the same instant, and the burst can trigger the next 429. When the server sends Retry-After, the code treats it as a minimum.

Note the two timeouts. The http.Client timeout is a backstop, and the per-call context.WithTimeout bounds each attempt. The outer ctx bounds the whole job, including the waits, so a shutdown cancels everything cleanly.

The limiter and the pool

import (
	"sync"

	"golang.org/x/time/rate"
)

func Run(ctx context.Context, msgs <-chan Message, workers int, perSecond float64, burst int) {
	lim := rate.NewLimiter(rate.Limit(perSecond), burst)

	var wg sync.WaitGroup
	for i := 0; i < workers; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for m := range msgs {
				r := sendWithRetry(ctx, lim, m)
				record(m, r)
			}
		}()
	}
	wg.Wait()
}

rate.NewLimiter(10, 10) allows ten requests per second with a burst of ten. lim.Wait(ctx) blocks until a token is free or the context ends, and the limiter is safe to share between goroutines. Take the actual numbers from your provider's documented limits, then start well under them.

A few sizing notes:

  • Set workers near perSecond times your typical request latency in seconds. At 10 requests a second and 300 ms latency, about 3 to 5 workers keep the limiter busy.
  • Keep burst small. A big burst lets a cold start fire a pile of requests at once.
  • Close the msgs channel when you're done producing, and Run returns after the workers drain it.

Idempotency per message

Here's the case the key exists for. The API accepts your request, starts delivery, and the response gets lost to a timeout. Your code sees an error and retries. If the second request carries the same Idempotency-Key, it doesn't send a second text.

That's why Message.ID comes from storage and not from uuid.New() inside the retry loop. A key generated per attempt does nothing, since every attempt looks like a new message. Generate it once, when you create the row, and persist it before the first send. Then a process crash and restart sends the same key for the same row.

Pair it with a status column. Mark a message sending before the call and sent or failed after, so a restart only re-queues rows that never reached a final state.

If several customers share one pool, a single limiter lets one big sender starve the rest. Our notes on SMS queue design for platforms cover per-tenant fairness.

What to record and what to give up on

record should store the final status code, the attempt count and the response body for any failure. Four outcomes need different handling:

OutcomeAction
2xxStore the returned message id, mark sent
Non-retryable 4xxMark failed with the body, don't re-queue
Retries exhaustedMark failed, keep for a later sweep
409 QUIET_HOURS_BLOCKSchedule for the window, or send with hold_until_allowed: true

Read the error body, not just the status. The errors reference lists the codes. A quiet-hours refusal is a policy answer, so retrying it every few seconds just burns attempts.

Test it before you trust it

Run the pool against a test key first. A test key simulates sends, so you can check the limiter, the retry timing and a forced restart without real texts going out. Details are in the API quickstart.

Then break it on purpose. Point the base URL at a local httptest server that returns 429 with a Retry-After, then 500, then 200. Assert that the same Idempotency-Key arrives on all three requests and that the gaps between them are at least the stated delay. That one test covers the two behaviors that cause real incidents.