Blogs

Fan-Out Queues for Push Notifications During Traffic Spikes

  • Push Notifications
  • Task Queues
  • System Design
  • Python
Dark graphic titled Fan-out push at 10x showing 200,000 tokens split into 400 batches, simulated throughput with and without a rate cap, and the steps fan-out, rate limit, retry and prune

In short: A fan-out queue turns one push campaign into many small jobs: split the audience into batches of up to 500 tokens (the FCM multicast limit), send them from a bounded worker pool, cap the rate under your provider quota, ramp up over at least 60 seconds, retry 429 and 5xx errors with backoff, and delete UNREGISTERED tokens. A 10x spike then fills your queue, not the provider’s error budget.

A fan-out queue is how one “Flash sale starts now” push reaches hundreds of thousands of phones without your sender, your database or your push provider falling over. You enqueue one campaign, a fan-out step splits the audience into batches, and a pool of workers sends those batches at a controlled rate. When traffic spikes 10x, the queue gets longer; nothing else has to get faster.

This post shows how fan-out queues work for push notifications during a spike, with a simulation I wrote and ran so you can see what each piece changes.

You’ll learn:

  • What a fan-out queue is and why naive sending breaks at 10x traffic
  • How batch size, worker count and a rate limiter interact, with measured numbers from a simulation
  • Which FCM errors to retry, which to drop, and which mean “delete this token”
  • How to time a campaign so it lands inside the provider’s limits

What is a fan-out queue for push notifications?

A fan-out queue is a two-stage pipeline: one message describing the campaign goes in, and many delivery jobs come out. The fan-out stage reads the audience (from your device token table) and writes jobs of up to 500 tokens each, because Firebase’s sendEachForMulticast accepts up to 500 tokens per call. The delivery stage is a pool of workers that pull those jobs, call the provider, record the results and clean up dead tokens.

The queue between the two stages is the shock absorber. In production it is a Celery queue, SQS or a Redis stream, so workers can run on many machines. The same design is the backbone of the notification systems I described in How Notification Systems Actually Work.

Why does naive sending break during a 10x spike?

Naive sending breaks because it ties the speed of the send to the speed of the trigger. A loop that sends to every token the moment the sale starts either runs too slowly (one request at a time) or, once you add concurrency, too fast for the provider’s quota. Firebase documents the HTTP v1 budget as 600K quota tokens per one-minute bucket and answers with 429 errors above it. Its scaling guide also asks senders to ramp from zero to their maximum rate over at least 60 seconds rather than jumping straight to full speed.

So the real job is not “send as fast as possible”. It is “send as fast as the quota allows, ramped, and never lose a token along the way.”

Simulation: batches, workers and a rate cap

To make the trade-offs concrete I wrote a small simulation in Python. The provider is fake: each batch call sleeps 100 to 200 ms like a network round trip, 2% of calls fail with a 503 UNAVAILABLE, and 0.5% of tokens come back UNREGISTERED. Workers retry 503s with exponential backoff and jitter, re-queueing the batch instead of holding a worker slot while they wait. An assertion checks that every token ends up sent, pruned or failed exactly once.

# fanout_sim.py: fan one campaign out to many devices with batches, a bounded
# worker pool, retries for transient errors and pruning of dead tokens.
# The "provider" is fake: it sleeps like a network call and fails at set rates.
import asyncio
import random
import time

BATCH = 500             # FCM sendEachForMulticast takes up to 500 tokens per call
DEAD_RATE = 0.005       # share of tokens the provider reports as UNREGISTERED
UNAVAILABLE_RATE = 0.02 # share of batch calls that fail with 503 UNAVAILABLE
MAX_ATTEMPTS = 5


class Unavailable(Exception):
    pass


class RateLimiter:
    """Token bucket that ramps linearly from 0 to `per_second` over `ramp_seconds`."""

    def __init__(self, per_second, ramp_seconds=0):
        self.max_rate, self.ramp = per_second, ramp_seconds
        self.start = self.last = time.monotonic()
        self.allowance = 0.0

    def rate(self, now):
        if not self.ramp:
            return self.max_rate
        return self.max_rate * max(0.01, min(1.0, (now - self.start) / self.ramp))

    async def acquire(self, n):
        while True:
            now = time.monotonic()
            rate = self.rate(now)
            self.allowance = min(self.max_rate, self.allowance + (now - self.last) * rate)
            self.last = now
            if self.allowance >= n:
                self.allowance -= n
                return
            await asyncio.sleep((n - self.allowance) / rate)


async def fake_send_multicast(tokens):
    """Pretend provider call: ~150 ms, sometimes 503, some tokens dead."""
    await asyncio.sleep(random.uniform(0.1, 0.2))
    if random.random() < UNAVAILABLE_RATE:
        raise Unavailable()
    return [("UNREGISTERED" if random.random() < DEAD_RATE else "OK") for _ in tokens]


async def worker(queue, stats, backoff_base, done, limiter):
    while True:
        batch, attempt = await queue.get()
        if limiter:
            await limiter.acquire(len(batch))  # stay under the provider quota
        try:
            results = await fake_send_multicast(batch)
            stats["sent"] += results.count("OK")
            stats["pruned"] += results.count("UNREGISTERED")  # delete these tokens in your DB
        except Unavailable:
            if attempt + 1 < MAX_ATTEMPTS:
                stats["retries"] += 1
                delay = backoff_base * 2 ** attempt * random.uniform(0.5, 1.5)  # backoff + jitter
                # re-queue later without holding a worker slot while waiting
                asyncio.get_running_loop().call_later(delay, queue.put_nowait, (batch, attempt + 1))
                continue
            stats["failed"] += len(batch)  # park for a later run
        stats["outstanding"] -= 1
        if stats["outstanding"] == 0:
            done.set()


async def fan_out(tokens, concurrency, limiter=None, backoff_base=0.2):
    queue = asyncio.Queue()
    for i in range(0, len(tokens), BATCH):
        queue.put_nowait((tokens[i:i + BATCH], 0))
    stats = dict(sent=0, pruned=0, retries=0, failed=0, outstanding=queue.qsize())
    done = asyncio.Event()
    workers = [asyncio.create_task(worker(queue, stats, backoff_base, done, limiter)) for _ in range(concurrency)]
    await done.wait()  # every batch delivered or given up on
    for w in workers:
        w.cancel()
    del stats["outstanding"]
    return stats


if __name__ == "__main__":
    random.seed(7)
    tokens = [f"token-{i}" for i in range(200_000)]
    runs = [
        ("10 workers, no limit", 10, None),
        ("50 workers, no limit", 50, None),
        ("50 workers, 10k/s cap", 50, lambda: RateLimiter(10_000)),
        ("50 workers, 10k/s, 60s ramp", 50, lambda: RateLimiter(10_000, ramp_seconds=60)),
    ]
    for label, concurrency, make_limiter in runs:
        start = time.perf_counter()
        stats = asyncio.run(fan_out(tokens, concurrency, make_limiter() if make_limiter else None))
        elapsed = time.perf_counter() - start
        total = stats["sent"] + stats["pruned"] + stats["failed"]
        assert total == len(tokens), (total, stats)  # every token accounted for exactly once
        print(f"{label:28} {elapsed:6.1f}s  {len(tokens) / elapsed:8.0f} tokens/s  {stats}")

I ran it on my laptop (Intel Core i5-8350U, Windows 11, Python 3.14.6) with 200,000 tokens, which is 400 batches:

SetupTime for 200,000 tokensThroughputRetries
10 workers, no limit6.6 s30,197 tokens/s9
50 workers, no limit1.6 s122,344 tokens/s5
50 workers, capped at 10,000/s20.4 s9,786 tokens/s6
50 workers, 10,000/s cap, 60 s ramp49.3 s4,056 tokens/s average7

Three things stand out:

  1. Concurrency alone overshoots. Fifty workers pushed about 122,000 tokens per second, roughly 7 million per minute, far past a 600K-per-minute budget. Against a real provider that run ends in a wall of 429s.
  2. The rate limiter sets the pace, not the workers. With the cap, 50 workers delivered just under the 10,000 per second limit. Extra workers only make sure the cap is always reached.
  3. The ramp costs about 30 seconds and buys safety. All 200,000 tokens still went out in under a minute, which is well inside the five minute delivery window most campaigns can tolerate.

The numbers come from a fake provider, so treat them as a model of the pipeline, not as FCM benchmarks. In a real deployment workers run in several processes, so the limiter has to be shared, typically a token bucket in Redis like the ones in API Rate Limiting: Token Bucket, Sliding Window, and Redis.

Which push errors should you retry?

Retry the errors that mean “not now” and drop the ones that mean “never”. Firebase’s error code reference maps cleanly onto three actions:

FCM errorHTTPAction
UNAVAILABLE503Retry with exponential backoff and jitter; honor Retry-After
INTERNAL500Retry with backoff; contact support if it persists
QUOTA_EXCEEDED429Back off; Firebase says start at a minimum of 1 minute for message rate
UNREGISTERED404Delete the token and stop sending to it
INVALID_ARGUMENT400Fix the payload; delete the token only if the payload is known to be valid
SENDER_ID_MISMATCH403Do not retry; the token belongs to a different sender

Firebase’s scaling guide adds two rules worth copying into your worker: set a send timeout of at least 10 seconds, and if a request is still failing after 60 minutes of backoff, treat it as a permanent failure or an outage instead of retrying forever. In Celery terms, that is a retry policy with a cap and a dead-letter queue for what is left.

How do you keep the token list clean?

Delete tokens as soon as the provider tells you they are dead, and stop counting stale ones in your audience. Firebase garbage collects Android registrations that have been inactive for 270 days, and by default it considers a registration stale if the app has not connected for a month. Store a timestamp with every token and filter on it when you build the audience. A flash sale is the worst time to discover that a third of your batches go to phones that uninstalled the app last year.

When should a flash sale push go out?

Send slightly before or after the obvious moment. Firebase asks senders to avoid the two minutes around :00, :15, :30 and :45, because that is when everyone else’s scheduled campaigns fire. If the sale opens at 18:00, start the ramp at 17:57 or 18:02 and let the fan-out queue finish the job over the next minute or two.

The takeaway

A fan-out queue survives a 10x spike because it separates deciding to notify from actually sending. Batch to the provider’s limit, run enough workers to keep a shared rate limiter busy, ramp up over a minute, retry only transient errors, and delete dead tokens on the way. The spike then shows up as a longer queue for a minute, which is exactly what you want.

Sources

Related reading

Frequently asked questions

How many devices can one FCM request reach?
The Firebase Admin SDK’s sendEachForMulticast accepts up to 500 tokens per call, and sendEach accepts a list of up to 500 messages. Each returns one result per token, in the same order you sent them.
What is the FCM rate limit?
Firebase documents the HTTP v1 API budget as 600K quota tokens per one-minute bucket, refilled each minute. Above it you get 429 responses; honor the Retry-After header and back off.
Should I send a flash sale push to everyone at the same second?
No. Firebase recommends ramping from zero to your maximum rate over at least 60 seconds and avoiding the two minutes around :00, :15, :30 and :45. Ask whether a 5 minute delivery window still works for the business; it usually does.

Tell me about your next project

Have an AI agent, a backend or a full product in mind? Send a short note and we can talk it through.