Fanout Seed Gaps: Async Events, Fixtures and Agents

Many CI failures in event-driven systems are not logic bugs. They are timing bugs that look like data bugs. A producer publishes an OrderPlaced event, three consumers each write their own derivative records, and the test fixture set up only one of those paths. The other two are still in the topic when the assertion runs. The test passes on a fast laptop and fails on a loaded CI runner, and the only difference between the two is speed.

A fanout seed gap is the window between publishing a seed event and the moment every downstream consumer has persisted its state. Fixtures describe a point in time; the system under test is eventually consistent. The gap widens with every consumer an event fans out to, and it widens again when coding agents write the tests, because the easiest fix an agent can reach for is time.sleep(2).

This article shows how to map the fanout, wait on each consumer's destination store instead of the clock, keep the topology in a versioned manifest, and write the rules that stop an agent from papering over the gap.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Map the fanout before you seed it

Start by listing every consumer that reacts to each event your fixtures publish, and the table or service each one writes to. A single UserCreated event might reach a profile service (writing user_profiles), a preferences service (user_settings) and an audit log (audit_events). A fixture that inserts users directly and skips those tables leaves every assertion on them racing a consumer, or asserting against state the real system never produces.

In a synchronous call stack the window is zero. With Kafka, SQS or a database outbox it depends on consumer lag, partition assignment, batching and broker round trips, and none of that is visible to a fixture unless you model it. The same blind spot shows up when the consumer's contract changes rather than its timing, which is covered in orphaned consumer fixtures and silent schema drift.

Wait on a condition, per consumer

Replace sleeps with a condition poll. A sleep is either too long (slow suite) or too short (flaky suite); a poll returns as soon as the consumer catches up and fails with a specific message when it does not.

import time

import pytest


def wait_for_rows(conn, query, params, expected, timeout=10.0, interval=0.1):
    """Poll the consumer's destination table until it holds `expected` rows."""
    deadline = time.monotonic() + timeout
    count = 0
    while time.monotonic() < deadline:
        with conn.cursor() as cur:
            cur.execute(query, params)
            count = cur.fetchone()[0]
        if count >= expected:
            return
        time.sleep(interval)
    raise TimeoutError(
        f"expected {expected} rows within {timeout}s, saw {count}: {query} {params}"
    )


@pytest.fixture
def seeded_order(db_conn, publish_event, unique_id):
    order_id = f"ord-{unique_id}"
    publish_event("OrderPlaced", {"order_id": order_id, "user_id": "usr-42"})
    wait_for_rows(db_conn,
                  "SELECT COUNT(*) FROM inventory_reservations WHERE order_id = %s",
                  (order_id,), 1)
    wait_for_rows(db_conn,
                  "SELECT COUNT(*) FROM notification_queue WHERE ref_id = %s",
                  (order_id,), 1)
    yield order_id

The code assumes a DB-API connection such as psycopg (%s placeholders) and publish_event and unique_id fixtures you supply. Two details matter. First, poll once per consumer path, not once for the whole fanout: an aggregate count can reach its threshold on one fast consumer's writes while another is stuck. Second, the timeout message names the query and the count it saw, so a failure in CI tells you which consumer fell behind.

If your system already carries correlation IDs, poll on those rather than on business keys; correlation ID gaps in async seed races covers the case where the ID itself goes missing along the way.

Keep the topology in a versioned manifest

When the fanout is deep or changes often, write it down as data the fixture loader reads:

# tests/fanout_map.yaml
OrderPlaced:
  - consumer: inventory
    table: inventory_reservations
    key_col: order_id
  - consumer: notifications
    table: notification_queue
    key_col: ref_id
  - consumer: billing
    table: billing_intents
    key_col: external_ref
import yaml


def load_fanout_map(path="tests/fanout_map.yaml"):
    with open(path) as f:
        return yaml.safe_load(f)


def wait_for_all_consumers(conn, event_name, key_value, fanout_map):
    entries = fanout_map.get(event_name)
    if not entries:
        raise KeyError(f"{event_name} is not in the fanout map; add its consumers first")
    for entry in entries:
        # table and column names come from the reviewed manifest, never from test input
        query = f"SELECT COUNT(*) FROM {entry['table']} WHERE {entry['key_col']} = %s"
        wait_for_rows(conn, query, (key_value,), 1)

An unknown event raises instead of silently waiting on nothing. The manifest becomes the record of your fanout: when someone adds a consumer, the manifest changes in the same pull request, and a reviewer can see that the seed factory only produces data valid for three of the six consumers listed.

What changes when agents write and run these tests

A coding agent asked to fix a flaky integration test sees a race and has two cheap options: add a sleep, or add a retry around the assertion. Both make the test pass more often, and both hide the gap. The agent cannot see consumer lag on your CI runners; it only sees that the test went green. Put the rules in the file your agent reads for repository guidance, such as .github/copilot-instructions.md or CLAUDE.md:

## Async test data rules
- Never add time.sleep() or assertion retries to fix a flaky event test.
- After publishing a seed event, call wait_for_all_consumers() with the event name.
- If an event or consumer is missing from tests/fanout_map.yaml, add it in the same
  change and say so in the PR description.
- Use unique_id for every key so parallel tests cannot read each other's writes.

The manifest also helps an agent do useful work. Given the consumer code and the map, it can propose entries for consumers the map does not list yet, which a human reviews. That is a far better use of the agent than letting it guess timing.

The same pattern applies when the system under test is itself an agent. If an agent's tool call publishes an event, a test of that agent must wait for the downstream consumers before checking the outcome. Otherwise a run that called the right tool can score as a failure, and the pass rate you report says more about broker lag than about the agent.

Where fanout fixtures still go wrong

Polling the broker instead of the store. Consumer group lag reaching zero means the messages were fetched, not that the consumer committed its transaction. Enrichment calls and batched writes sit between the two. Poll the destination store.

Sharing consumer state across tests. Session- or module-scoped fixtures save setup time, but one test's fanout writes then show up in another test's assertions. Scope consumer-touching fixtures per function and use unique keys so bleed-through is obvious. The same failure in shared seed pools is described in tenant isolation gaps in shared seed pools.

Trusting a local pass. Local setups often run a single-partition broker or in-process consumers, so gaps are short. A fixture that passes locally may simply have been lucky. Make fixtures timing-agnostic by design.

Seeding only the upstream table. That tests a system that never processed the event. Randomising order_id across many seeds does not help if inventory_reservations stays empty; the missing coverage is the consumer-written records, not the values.

Fanout seed gaps are a structural problem. Make the consumer topology explicit, wait on each destination store, scope fixtures tightly, version the manifest with the consumer code, and give your agents rules that forbid the sleep. If your seeds also fail on foreign key ordering, continue with FK seed order and cascade failures.

Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.

Understanding how systems actually work is the first step toward navigating them effectively.

Browse all articles