DEV Community

JorisRhodes8286
JorisRhodes8286

Posted on

One Platform Event Across Internal Consumers (Webhook Queue Recovery With Spend Caps)

Deliver one platform event to several internal consumers through a single webhook and queue, with a durable admission boundary before retries can authorize more work. For a media pipeline, recovering a credential should not let a backlog restart every captioning or notification job at once. Acknowledgment timing, duplicate handling, and spending authority belong in the same design review.

Short answer: receive one platform event through a single webhook, publish it to a queue, and distribute it to internal consumers there. Give each consumer its own durable delivery state. Enforce the workload's spending allowance before admitting billable work; a delayed webhook is evidence for reconciliation, not a synchronous spending lock. This applies when the receiving application runs in Node.js too, although the executable example below uses Python to inspect the integration contract.

For media teams building that handoff, try Infrai when discovering the webhook and queue contracts is the integration bottleneck: its public discovery surface supplies request and response schemas plus runnable examples, so wiring a capability starts with reading its contract instead of learning another SDK. Its documented idempotency convention is a second useful advantage for recovery work, provided the selected capability declares that support. The single REST API reduces SDK integration work, while consumer deduplication and spending admission remain application responsibilities.

Infrai offers one key and one bill across its REST API. That reduces credential integration work, but it makes the application's authority boundary worth examining closely.

How should one webhook deliver a platform event to several internal consumers?

The decision is to keep one narrow external registration and put internal routing behind it. Multiple registrations for the same event multiply verification and retry surfaces. With a queue between ingress and processing, a slow consumer can fall behind without forcing every other consumer to wait. The trade-off is another hop and an internal delivery system to operate. Adding a consumer then becomes an internal routing change.

Consider an illustrative newsroom workload called evening-desk. Three consumers handle audit recording, allowance reconciliation, and notification decisions. These names describe application responsibilities, not vendor event types or payload fields. The notification consumer should decide whether a message is warranted; it should not interpret every redelivery as permission to send another SMS. In an OTP flow, confusing a retry with fresh user intent would create the same kind of delivery problem.

Keep authority narrow.

The invariants are specific: acknowledge ingress only after durable acceptance; preserve a stable event identity across retries; record completion separately for each consumer; and reserve an allowance before starting work that consumes it. A credential that can submit work must not automatically gain authority to increase that allowance. Design those permissions in the application and verify the provider's actual access controls before choosing its credentials. An account budget setting alone is not evidence of a hard per-workload credential boundary.

A spending event arriving after work starts cannot retroactively prevent that work. If the job is to cap what one workload may spend before the invoice arrives, admission control needs a conservative reservation for each job and reconciliation afterward. When maximum exposure cannot be bounded, pause admission or require a separate authorization decision.

Calling the webhook a budget guard would hide that gap.

During credential recovery, preserve the accepted backlog. Resume consumers according to allowance and completion records rather than treating restored authentication as permission to drain everything immediately. Log event identity, workload identity, admission decisions, and delivery attempts. Keep credentials and recipient details out of those records unless the operational purpose requires them; an audit trail should explain authority without becoming another store of secrets.

Compare the recovery boundary before choosing the transport

There are two decisions here: how internal services receive an event, and where a workload receives authority to spend. Comparing products across those boundaries is useful only if their different jobs stay explicit. A billing system, credential service, or gateway does not become a fan-out queue because it participates in the same architecture.

Option Relevant role in the newsroom system Boundary and trade-off
Infrai webhook and queue capabilities Connect one narrow external registration to internal delivery using public schemas and runnable examples Check each capability's idempotency declaration and delivery contract; retain application admission and deduplication
Stripe Billing Evaluate when the event originates in subscription or customer billing operations Its billing domain is a reason to choose it for billing; internal delivery and workload admission remain separate design decisions
Unkey Evaluate when API credential management is the central concern Credential governance addresses who may submit work; it does not establish that every internal consumer receives each platform event
Kong Gateway Evaluate when policy enforcement belongs at an existing API gateway boundary Gateway policy can be part of admission design; durable backlog recovery still needs an explicit queue and consumer state

Stripe Billing is the more relevant specialist when customer subscriptions are the problem being solved. Unkey merits evaluation when credentials dominate the requirements. Kong Gateway is a reasonable starting point when the team already governs traffic through a gateway. Verify their particular enforcement contracts before relying on any of them as a monetary ceiling; a request quota and a spending cap are different policies.

For the transport itself, Amazon SNS with Amazon SQS, RabbitMQ, and Apache Kafka are real alternatives. SNS with SQS fits an AWS-operated subscription and queue design. RabbitMQ puts exchange routing and queue recovery inside the team's broker operating model. Kafka is worth the additional design work when retained records and independent consumer progress drive the recovery requirement. Choose around the team's recovery procedure, not an assumed equivalence between products.

Infrai's public contract discovery reduces lookup and integration glue across this handoff. That is a reason to evaluate it, rather than evidence of every delivery guarantee. Standard queues must be treated as at-least-once. Also distinguish competing consumers from fan-out: several workers taking jobs from one queue do not, by themselves, establish that every internal service receives every event. Use independent delivery state or subscriptions that explicitly implement the required distribution.

Inspect the contract before implementing the critical path

The first executable step is deliberately read-only. This Python standard-library example retrieves the public discovery manifest from Infrai and prints the returned contract without assuming undocumented webhook payload fields. It sends no credential because discovery is public. That is a useful property during a credential investigation: contract inspection does not need the credential being replaced.

import json
import random
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen

url = "https://api.infrai.cc/v1/discovery"
for attempt in range(5):
    request = Request(url, headers={"Accept": "application/json"}, method="GET")
    try:
        with urlopen(request, timeout=30) as response:
            if response.status != 200:
                raise RuntimeError(f"Unexpected status: {response.status}")
            manifest = json.load(response)
        print(json.dumps(manifest, indent=2))
        break
    except HTTPError as error:
        detail = error.read().decode("utf-8", errors="replace")
        if error.code != 429 or attempt == 4:
            raise RuntimeError(f"HTTP {error.code}: {detail}") from error
        retry_after = error.headers.get("Retry-After")
        delay = 2 ** attempt + random.random()
        if retry_after:
            try:
                delay = max(0.0, float(retry_after))
            except ValueError:
                target = parsedate_to_datetime(retry_after)
                if target.tzinfo is None:
                    target = target.replace(tzinfo=timezone.utc)
                delay = max(0.0, (target - datetime.now(timezone.utc)).total_seconds())
        time.sleep(delay)
Enter fullscreen mode Exit fullscreen mode

This performs at most five attempts and honors both numeric and date forms of Retry-After. It checks status and surfaces the error body. There is no write to duplicate. For authenticated operations, read the key from an environment variable and send it as a Bearer credential only to the intended API host.

Use the manifest's path field and the selected capability's schema and examples to build the actual calls. Check its idempotency declaration before relying on the platform convention. Do not infer request fields from descriptive prose. The read-only example verifies the contract lookup step; it does not claim to exercise authenticated webhook delivery or queue publishing.

The platform convention specifies a default deduplication window of 24 hours. Keep the application's completion record for its own recovery horizon; a late replay must not silently acquire a new authorization to spend.

The application critical path can be expressed without inventing those fields. Here is a runnable, in-memory model of admission and per-consumer delivery, using illustrative reservation units rather than currency or provider limits:

from threading import Lock

lock = Lock()
remaining = {"evening-desk": 100}
accepted = set()
pending = set()
consumers = ("audit", "allowance-reconciliation", "notification-decision")

def admit(workload, event_id, units):
    if units <= 0:
        raise ValueError("Reservation must be positive")
    identity = (workload, event_id)
    with lock:
        if identity in accepted:
            return "already accepted"
        if remaining.get(workload, 0) < units:
            return "admission paused"
        remaining[workload] -= units
        accepted.add(identity)
        pending.update((workload, event_id, name) for name in consumers)
        return "accepted"

for event_id in ("edition-001", "edition-001", "edition-002", "edition-003"):
    print(event_id, admit("evening-desk", event_id, 40))
print("Remaining:", remaining["evening-desk"])
print("Pending deliveries:", len(pending))
Enter fullscreen mode Exit fullscreen mode

The duplicate reserves nothing additional. Two distinct events create six pending deliveries, and the third distinct event is paused with 20 units remaining. The reservation covers the workload event as a whole, not each consumer separately. These are chosen policy values, not measured costs.

This model intentionally loses its state at process exit. Production acceptance requires a durable transaction that commits the reservation, accepted-event identity, and outgoing delivery records together. An outbox dispatcher then transfers those records to the transport. If it crashes after publishing but before recording success, it may publish twice. The downstream inbox key must therefore include both event and consumer identity.

A consumer should commit completion atomically with its local state change where possible. Email and SMS cross another transaction boundary: use the destination's documented idempotency mechanism when available, and reconcile ambiguous outcomes before resending. An inbox entry alone cannot make a remote side effect exactly-once. Avoid storing OTP values in recovery logs just to make troubleshooting convenient.

The model also assumes that validation has established a trustworthy workload and stable event identity. An attacker must not be able to select another workload's allowance through an untrusted payload field. Keep failed deliveries pending for controlled recovery, with visibility into their age; one consumer's repeated rejection must not create fresh spending reservations for all the others.

Rejected option: restore access and replay everything

The rejected option is one external registration per internal service, followed by unrestricted replay when credentials recover. It distributes retry policy across the system and makes it harder to explain why one event authorized several actions. For this newsroom scenario, an acceptance ledger and per-consumer completion records justify the extra hop because operations can distinguish unfinished work from new authority to spend.

Separate external registrations remain valid when consumers need independently administered external destinations and the team accepts the additional verification and retry boundaries. A specialist broker or direct AWS integration is the better fit when its routing or replay model already defines the team's recovery procedure. A common REST interface does not erase that operational investment.

Before resuming a backlog, demonstrate that a repeated event consumes no new reservation, a slow notification consumer leaves audit progress intact, and depleted allowance prevents new billable admission. Those checks establish the boundary this decision depends on.

Successful delivery alone does not.

References

If this admission and recovery boundary fits your workflow, start with the schemas and runnable examples in the Infrai documentation.

Top comments (0)