WhatsApp· 5 min read

Build a WhatsApp send queue that respects Meta's limits


Put every outbound message through one asyncio queue per business number. Each send takes a token from a bucket set below the number’s throughput and reserves a 6-second slot for its recipient. Retry 131056 after 4^X seconds, and pause the bucket on 130429. Meta documents no idempotency key for /messages, so duplicate protection is client-side. The key store in the code below is our own design. The script runs on Python 3.9 or later with a simulated sender, so you can watch it work without a token.

The limits the queue enforces

The rate limits post covers the numbers in full, and Meta’s pages still gave them on 2026-11-04. The queue enforces four rules.

Limit Meta’s rule Error Queue action (our design)
Throughput per number up to 80 mps by default, inbound included 130429 pause the number’s bucket, retry
Pair rate 1 message every 6 seconds to the same user, bursts borrow quota 131056 delay only that recipient by 4^X seconds
Maintenance mode the account is in maintenance mode, for example during a throughput upgrade 131057 short pause, retry
Permanent errors 131026, 131047, 131048, 131049, template errors as listed fail fast, no automatic retry

Meta’s fix for 130429 is to “Try again later or reduce the frequency with which the app sends messages”, with no schedule (Meta error codes, accessed 2026-11-04). The one backoff schedule Meta gives for sends is the 4^X rule in its platform overview, tied to pair-rate throttling (Meta platform overview, accessed 2026-11-04). For 131056, Meta adds that “You can still send messages to a different phone number without waiting.” That is why the delay applies to one recipient and the bucket keeps going.

131048 is different: it restricts the whole number, but the script above fails only that one message. On 131048, pause the number and check quality in WhatsApp Manager.

Read the number’s level with GET /<PHONE_NUMBER_ID>?fields=throughput (Meta throughput, accessed 2026-11-04). The only value Meta’s samples show is "level": "STANDARD", and no page maps it to 80 mps in so many words. The code treats STANDARD and any unknown value as 80, which is our assumption. It then sends at 75% of that, because “Throughput is inclusive of inbound and outbound messages and all message types.”

The messaging limit per business portfolio is a separate cap on unique users over a moving 24 hours. A rate limiter doesn’t enforce it; the messaging limits post shows how to read it.

Idempotency is your job

Meta’s send response “only indicates that the API successfully accepted your request” and “does not indicate successful delivery of your message” (Meta send messages, accessed 2026-11-04). The page mentions no idempotency key, dedupe header or request ID. If your code retries a send whose response was lost, the user can get the message twice.

The queue below gives each logical send a key you choose, such as an order ID plus the template name. Before sending, it checks the key against a store. After a success, it stores the wamid from messages[0].id. A second job with the same key is skipped, whether the first is still in flight or finished. Build the key from your own data, never from the attempt’s timestamp, or every retry gets a fresh key.

A timeout or network error is the hard case. The request may have reached Meta, so the queue records the key as unknown and doesn’t resend. Check the status webhooks for that recipient before you clear the key by hand.

Template pacing adds one more state. A marketing or utility template can come back with message_status set to held_for_quality_assessment (Meta template pacing, accessed 2026-11-04). Meta releases held messages on good feedback, or drops them with 132015 if the template is paused. The queue treats a held message as accepted and never resends it.

Webhooks have their own duplicates. Meta’s retries “can result in duplicate webhook notifications”, handled in the webhook queue post.

The send queue in Python

The script uses only the standard library. Without arguments it runs a demo against FakeSender, a simulation that returns 130429 above 5 accepted messages per second and 131056 once for a busy recipient. With --live, it reads the number’s throughput and sends one template through Meta’s /messages endpoint, as in the Python send guide.

# send_queue.py. Python 3.9 or later, standard library only.
# Demo, no token needed:  python3 send_queue.py
# Live:  PHONE_NUMBER_ID=... ACCESS_TOKEN=... python3 send_queue.py --live 15551234567 TEMPLATE_NAME en_US
import asyncio
import json
import os
import sys
import time
import urllib.error
import urllib.request

GRAPH = "https://graph.facebook.com/v26.0"
PAIR_GAP = 6.0  # Meta: 1 message every 6 seconds to the same WhatsApp user
MAX_ATTEMPTS = 5
PAUSE_CODES = {130429, 131057}           # throughput reached, upgrade in progress
TRANSIENT = {2, 131000, 131016}          # Meta: try again; our backoff is 2^X seconds
PERMANENT = {131026, 131047, 131048, 131049,
             132000, 132001, 132005, 132007, 132012, 132015, 132016}


class SendError(Exception):
    def __init__(self, code, body=None):
        super().__init__(f"Meta error {code}")
        self.code = code
        self.body = body


def mps_from_level(level):
    # Our assumption: Meta documents only "STANDARD" and an 80 mps default.
    return {"STANDARD": 80}.get(level, 80)


class TokenBucket:
    def __init__(self, rate):
        self.rate = rate
        self.tokens = float(rate)
        self.last = time.monotonic()
        self.paused_until = 0.0
        self.lock = asyncio.Lock()

    def pause(self, seconds):
        self.paused_until = max(self.paused_until, time.monotonic() + seconds)

    async def take(self):
        async with self.lock:
            while True:
                now = time.monotonic()
                if now < self.paused_until:
                    await asyncio.sleep(self.paused_until - now)
                    continue
                self.tokens = min(self.rate, self.tokens + (now - self.last) * self.rate)
                self.last = now
                if self.tokens >= 1:
                    self.tokens -= 1
                    return
                await asyncio.sleep((1 - self.tokens) / self.rate)


class SendQueue:
    def __init__(self, sender, mps, workers=4, timeout=20.0):
        self.sender = sender
        self.bucket = TokenBucket(mps)
        self.queue = asyncio.Queue(maxsize=10000)
        self.workers = workers
        self.timeout = timeout
        self.next_slot = {}    # recipient -> earliest monotonic time for the next send
        self.results = {}      # idempotency key -> outcome (our client-side store)
        self.in_flight = set()

    def reserve(self, to, extra=0.0):
        # Runs before any await, so two jobs for one user get slots 6 s apart.
        now = time.monotonic()
        slot = max(now, self.next_slot.get(to, 0.0)) + extra
        self.next_slot[to] = slot + PAIR_GAP
        return slot - now

    async def attempt(self, key, payload):
        to, extra = payload["to"], 0.0
        for x in range(MAX_ATTEMPTS):
            await asyncio.sleep(self.reserve(to, extra))
            await self.bucket.take()
            try:
                resp = await asyncio.wait_for(self.sender.send(payload), self.timeout)
            except (asyncio.TimeoutError, OSError):
                return {"state": "unknown"}  # may have reached Meta: do not resend
            except SendError as err:
                print(f"{key}: attempt {x + 1} returned {err.code}")
                if err.code == 131056:
                    extra = 4.0 ** x  # Meta: retry after 4^X seconds
                elif err.code in PAUSE_CODES:
                    extra = 0.0
                    self.bucket.pause(1.0)
                elif err.code in TRANSIENT:
                    extra = 2.0 ** x
                else:
                    state = "failed" if err.code in PERMANENT else "error"
                    return {"state": state, "code": err.code}
                continue
            msg = resp["messages"][0]
            # held_for_quality_assessment is template pacing: accepted, never resend.
            return {"state": msg.get("message_status", "accepted"), "wamid": msg["id"]}
        return {"state": "gave_up"}

    async def handle(self, key, payload):
        if key in self.results or key in self.in_flight:
            print(f"{key}: duplicate key, not sent again")
            return
        self.in_flight.add(key)
        try:
            self.results[key] = await self.attempt(key, payload)
        finally:
            self.in_flight.discard(key)
        print(f"{key}: {self.results[key]}")

    async def worker(self):
        while True:
            key, payload = await self.queue.get()
            try:
                await self.handle(key, payload)
            except Exception as exc:  # keep the worker alive; record the failure
                self.results[key] = {"state": "error", "detail": repr(exc)}
            finally:
                self.queue.task_done()

    async def run(self, jobs):
        tasks = [asyncio.create_task(self.worker()) for _ in range(self.workers)]
        for job in jobs:
            await self.queue.put(job)
        await self.queue.join()
        for task in tasks:
            task.cancel()
        await asyncio.gather(*tasks, return_exceptions=True)
        return self.results


class FakeSender:
    """Simulation only: mimics 130429 and 131056 so the demo runs without a token."""

    def __init__(self, mps_limit, busy=(), held=(), hang=(), outside_window=()):
        self.mps_limit = mps_limit
        self.recent = []                       # accepted send times in the last second
        self.busy = set(busy)                  # pair quota already used elsewhere: 131056 once
        self.held = set(held)                  # template pacing holds these
        self.hang = set(hang)                  # never answer: simulates a lost response
        self.outside_window = set(outside_window)
        self.count = 0

    async def send(self, payload):
        to = payload["to"]
        await asyncio.sleep(0.05)
        if to in self.hang:
            await asyncio.sleep(3600)
        now = time.monotonic()
        self.recent = [t for t in self.recent if now - t < 1.0]
        if len(self.recent) >= self.mps_limit:
            raise SendError(130429)
        if to in self.busy:
            self.busy.discard(to)
            raise SendError(131056)
        if to in self.outside_window and payload["type"] != "template":
            raise SendError(131047)
        self.recent.append(now)
        self.count += 1
        msg = {"id": f"wamid.FAKE{self.count}"}
        if payload["type"] == "template":
            msg["message_status"] = "held_for_quality_assessment" if to in self.held else "accepted"
        return {"messaging_product": "whatsapp",
                "contacts": [{"input": to, "wa_id": to}], "messages": [msg]}


class GraphSender:
    def __init__(self, phone_number_id, token):
        self.url = f"{GRAPH}/{phone_number_id}/messages"
        self.token = token

    def _post(self, payload):
        req = urllib.request.Request(
            self.url, data=json.dumps(payload).encode(), method="POST",
            headers={"Authorization": f"Bearer {self.token}", "Content-Type": "application/json"})
        try:
            with urllib.request.urlopen(req, timeout=30) as resp:
                return json.load(resp)
        except urllib.error.HTTPError as e:
            try:
                body = json.loads(e.read() or b"{}")
            except ValueError:
                body = {}
            raise SendError(body.get("error", {}).get("code"), body) from None

    async def send(self, payload):
        # On timeout the thread keeps running, which is why the outcome is "unknown".
        return await asyncio.to_thread(self._post, payload)


def read_mps(phone_number_id, token):
    req = urllib.request.Request(f"{GRAPH}/{phone_number_id}?fields=throughput",
                                 headers={"Authorization": f"Bearer {token}"})
    with urllib.request.urlopen(req, timeout=30) as resp:
        return mps_from_level(json.load(resp).get("throughput", {}).get("level"))


def template(to, name="order_update", lang="en_US"):
    return {"messaging_product": "whatsapp", "recipient_type": "individual", "to": to,
            "type": "template", "template": {"name": name, "language": {"code": lang}}}


async def demo():
    sender = FakeSender(mps_limit=5, busy={"15550000002"}, held={"15550000011"},
                        hang={"15550000003"}, outside_window={"15550000004"})
    queue = SendQueue(sender, mps=6, workers=4, timeout=2.0)  # 6 > 5 on purpose: triggers 130429
    jobs = [
        ("order-1001", template("15550000001")),
        ("order-1001", template("15550000001")),   # same key: skipped
        ("order-1002", template("15550000001")),   # same user: waits for the 6 s slot
        ("order-1003", template("15550000002")),   # busy user: 131056, then 4^0 s extra
        ("order-1004", template("15550000003")),   # no response: recorded as unknown
        ("chat-77", {"messaging_product": "whatsapp", "to": "15550000004",
                     "type": "text", "text": {"body": "Hi"}}),  # 131047: fails fast
    ]
    jobs += [(f"order-20{i}", template(f"155500000{10 + i}")) for i in range(6)]
    start = time.monotonic()
    await queue.run(jobs)
    print(f"done in {time.monotonic() - start:.1f} s")


async def live(to, name, lang):
    pid, token = os.environ["PHONE_NUMBER_ID"], os.environ["ACCESS_TOKEN"]
    mps = await asyncio.to_thread(read_mps, pid, token)
    queue = SendQueue(GraphSender(pid, token), mps=max(1, int(mps * 0.75)))  # inbound shares the budget
    print(await queue.run([(f"{to}:{name}", template(to, name, lang))]))


if __name__ == "__main__":
    if len(sys.argv) >= 5 and sys.argv[1] == "--live":
        asyncio.run(live(*sys.argv[2:5]))
    else:
        asyncio.run(demo())

The demo finishes in roughly 7 to 15 seconds, depending on which jobs hit 130429. You’ll see the duplicate key skipped and the busy recipient retried. You’ll also see one 131047 failure, one unknown and one held template.

Why the code is shaped this way

The queue objects are created inside the running coroutine. On Python 3.9, an asyncio.Lock or Queue built before asyncio.run can bind to a different event loop. The script keeps the worker tasks in a list because “The event loop only keeps weak references to tasks” (asyncio tasks). It waits with queue.join(), which blocks “until all items in the queue have been received and processed” (asyncio queues).

Refill uses time.monotonic(), so a wall-clock change can’t hand out extra tokens. A failed attempt keeps its reserved 6-second slot. Meta doesn’t say whether 131056 counts attempts or only accepted messages, so the code assumes attempts count.

The TRANSIENT backoff of 2^X seconds is ours. Meta’s fixes for 131000, 131016 and 2 say to try again or check the status page, with no schedule. Everything outside the listed codes is recorded as error and not retried.

Running it past one process

A worker that sleeps through a pair gap is unavailable to other jobs for those seconds. With many repeat recipients, raise workers, or put delayed jobs back on the queue with their slot time. asyncio primitives “are not thread-safe” and live in one process’s memory, so several processes need shared state (asyncio sync primitives). Move the bucket, the next_slot map and the key store to Redis or your database, keyed by phone number ID, recipient and idempotency key.

To let one-time codes jump ahead of marketing, swap in asyncio.PriorityQueue. It retrieves the lowest entry first, with entries “typically tuples of the form (priority_number, data)”. Put (priority, seq, key, payload) on the queue, with seq from a counter, so two equal entries never compare their payload dicts. Then unpack _, _, key, payload in worker.

Meta doesn’t guarantee that messages arrive in request order. If order matters for one user, wait for the delivered webhook before sending the next message, as the sequencing post describes.

Z-API Omni team