7/12
Technical Architecture & AI Engineering · 7 min read

Pub/Sub Event Bus With Filtered Subscribers and Retry Backoff

Design an async TypeScript pub/sub event bus with predicate filtering, exponential retry backoff, Dead Letter Queue routing, subscriber isolation, and bounded eventId deduplication.

Why This Matters at Engineering Leadership Scale

Event-driven architectures decouple domain squads: when Orders emits order.paid, Billing, Fulfillment, and Analytics subscribe independently. Yet naive in-process buses (like raw EventEmitter or serial for..of await loops) break fast in production: one slow or throwing subscriber blocks every sibling behind it, and transient failures silently drop events with no Dead Letter Queue (DLQ) to replay.

In senior engineering and Engineering Manager code design loops, the Pub/Sub Event Bus drill checks whether you design fault-isolated async boundaries. Keeping O(S) topic fan-out clean while injecting testable retry sleepers lets you absorb the Minute-30 curveballs - async subscriber isolation and eventId deduplication - cleanly.

Core Mental Model & Architecture

Dispatch StrategyPublish LatencyFault IsolationDuplicate GuardFailure Handling
Serial for..of awaitO(sum(T_i))None (one throw/hang blocks all)NoneAborts remaining subscribers on throw
Promise.allSettled + Per-Sub Retry + DLQO(max(T_i))Full (isolated retry loops)Bounded (subId, eventId) setExhausted failures routed to inspectable DLQ
Fire-and-Forget Detached PromisesO(S) instantHigh, no backpressureExternal store requiredRisk of silent drops on shutdown

Three design seams make this resilient:

  1. Per-subscription predicate filter avoids running handlers and retry loops for irrelevant payloads.
  2. Injected sleep(ms) lets unit tests assert exact exponential delays (50ms, 100ms, 200ms) in milliseconds.
  3. Bounded (subscriptionId, eventId) deduplication stops duplicate deliveries from double-processing while keeping memory capped and letting failed sibling subscribers still replay from the DLQ.

Step-by-Step Implementation Tutorial

1. Implement Filtered Subscriptions, Isolated Retries, DLQ, and Deduplication (Minutes 5 to 28)

typescript
export interface BusEvent<T = unknown> { eventId: string; topic: string; payload: T; timestampMs: number; }
export interface RetryPolicy { maxRetries: number; baseDelayMs: number; }
export interface SubscribeOptions<T = unknown> {
  id: string; filter?: (event: BusEvent<T>) => boolean; retryPolicy?: RetryPolicy;
}
export interface DeadLetterEntry {
  event: BusEvent; subscriptionId: string; attempts: number; lastError: string; failedAtMs: number;
}
export interface PublishReport {
  eventId: string; matched: number; succeeded: number; deduplicated: number; deadLettered: number;
}

type EventHandler<T = unknown> = (event: BusEvent<T>) => Promise<void> | void;
type Sleeper = (ms: number) => Promise<void>;
interface Subscription {
  id: string; topic: string; handler: EventHandler<any>;
  filter?: (event: BusEvent<any>) => boolean; retryPolicy: RetryPolicy;
}

const DEFAULT_RETRY: RetryPolicy = { maxRetries: 2, baseDelayMs: 100 };

export class PubSubEventBus {
  private readonly topics = new Map<string, Subscription[]>();
  private readonly dlq: DeadLetterEntry[] = [];
  // Minute-30 Extension: Bounded per-subscriber eventId dedup set
  private readonly processedKeys = new Set<string>();

  constructor(
    private readonly sleep: Sleeper = (ms) => new Promise((r) => setTimeout(r, ms)),
    private readonly maxDedupKeys = 50_000,
    private readonly nowMs: () => number = () => Date.now()
  ) {}

  public subscribe<T>(topic: string, handler: EventHandler<T>, options: SubscribeOptions<T>): () => void {
    if (!topic || !options.id) throw new Error("topic and subscription id required");
    const list = this.topics.get(topic) ?? [];
    if (list.some((s) => s.id === options.id)) throw new Error(`Duplicate sub "${options.id}" on "${topic}"`);

    list.push({ id: options.id, topic, handler, filter: options.filter, retryPolicy: options.retryPolicy ?? DEFAULT_RETRY });
    this.topics.set(topic, list);

    return () => {
      const cur = this.topics.get(topic);
      if (cur) this.topics.set(topic, cur.filter((s) => s.id !== options.id));
    };
  }

  public async publish<T>(event: BusEvent<T>): Promise<PublishReport> {
    if (!event.eventId || !event.topic) throw new Error("eventId and topic required");
    const matched = [...(this.topics.get(event.topic) ?? [])].filter((sub) => this.safeFilter(sub, event));

    // Minute-30 Extension: Async subscriber isolation via Promise.allSettled
    const outcomes = await Promise.allSettled(matched.map((sub) => this.deliverWithRetry(sub, event)));

    let succeeded = 0, deduplicated = 0, deadLettered = 0;
    for (const o of outcomes) {
      if (o.status === "fulfilled" && o.value === "succeeded") succeeded++;
      else if (o.status === "fulfilled" && o.value === "deduplicated") deduplicated++;
      else deadLettered++;
    }
    return { eventId: event.eventId, matched: matched.length, succeeded, deduplicated, deadLettered };
  }

  public getDeadLetterQueue(): readonly DeadLetterEntry[] { return this.dlq; }

  public async replayDeadLetters(): Promise<number> {
    const batch = this.dlq.splice(0, this.dlq.length);
    let recovered = 0;
    for (const entry of batch) {
      const target = (this.topics.get(entry.event.topic) ?? []).find((s) => s.id === entry.subscriptionId);
      if (!target) { this.dlq.push(entry); continue; }
      const status = await this.deliverWithRetry(target, entry.event);
      if (status === "succeeded" || status === "deduplicated") recovered++;
    }
    return recovered;
  }

  private async deliverWithRetry(sub: Subscription, event: BusEvent): Promise<"succeeded" | "deduplicated" | "dead_lettered"> {
    const dedupKey = `${sub.id}:${event.eventId}`;
    if (this.processedKeys.has(dedupKey)) return "deduplicated";

    const maxAttempts = sub.retryPolicy.maxRetries + 1;
    let lastError = "Unknown error";

    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
      try {
        await sub.handler(event);
        this.recordProcessed(dedupKey);
        return "succeeded";
      } catch (err) {
        lastError = err instanceof Error ? err.message : String(err);
        if (attempt < maxAttempts) {
          await this.sleep(sub.retryPolicy.baseDelayMs * Math.pow(2, attempt - 1));
        }
      }
    }

    this.dlq.push({ event, subscriptionId: sub.id, attempts: maxAttempts, lastError, failedAtMs: this.nowMs() });
    return "dead_lettered";
  }

  private safeFilter(sub: Subscription, event: BusEvent): boolean {
    if (!sub.filter) return true;
    try { return sub.filter(event); } catch { return false; }
  }

  private recordProcessed(key: string): void {
    this.processedKeys.add(key);
    if (this.processedKeys.size > this.maxDedupKeys) {
      const oldest = this.processedKeys.keys().next().value;
      if (oldest !== undefined) this.processedKeys.delete(oldest);
    }
  }
}

2. Write Unit Tests & Minute-30 Extension Checks (Minutes 30 to 50)

Inject a spy sleep (const delays: number[] = [];) and verify:

  1. Filter isolation: Subscriber filtered to amount > 1000 skips amount = 500.
  2. Exponential backoff & DLQ: Always-failing subscriber with maxRetries: 3, baseDelayMs: 50 logs delays = [50, 100, 200] and adds 1 DLQ entry with attempts: 4.
  3. Async subscriber isolation: Subscriber A hangs/throws while Subscriber B completes in 1ms unaffected.
  4. Per-subscriber eventId deduplication: Publishing evt_99 twice deduplicates Subscriber A while still allowing failed Subscriber B to recover on replayDeadLetters().

Worked Production Scenario: Before vs. After

Context: A B2B SaaS platform dispatched 45k subscription events/hour (plan.upgraded, seat.added) across Billing, CRM Sync, Audit Trail, and Slack Alerts using a serial for..of await loop. When the CRM API degraded to 12-second 503 timeouts, Billing and Audit stalled behind it and dropped 420 events per incident; webhook retries also double-provisioned seats 5 times in one quarter.

After: Core Platform adopted PubSubEventBus with Promise.allSettled isolation, per-subscriber exponential backoff + DLQ replay, and bounded (subscriptionId, eventId) deduplication.

MetricBeforeAfter
Billing lag during CRM 503 outage12.4 seconds (blocked)18 milliseconds (isolated)
Silent dropped events per outage~420 events0 (retried or captured in DLQ)
Duplicate seat-provisioning incidents5 / quarter0 (eventId deduplicated)
Recovery time after downstream fix4-hour manual backfill< 2 mins DLQ replay

Common Failure Modes & Anti-Patterns

  1. Deduplicating globally by eventId instead of (subscriptionId, eventId): Marking "evt_1" processed once Subscriber A succeeds prevents Subscriber B from replaying out of the DLQ. Fix: Scope keys to ${sub.id}:${event.eventId} and record only on subscriber success.
  2. Retrying without jitter in distributed fleets: 50 pods retrying on exact 100ms -> 200ms -> 400ms ticks create retry storms. Fix: Add small jitter (0.8x to 1.2x) in production sleepers.
  3. Iterating live subscriber arrays during publish(): Self-unsubscribing inside a handler skips the next listener. Fix: Snapshot [...list] before dispatching.

How to Handle Pushback in the Room

Skeptical Principal Engineer: "If the Node.js pod crashes mid-retry, an in-memory DLQ vanishes - why not mandate Kafka or SQS immediately?"

Calm Response: "For cross-process durability across restarts, SQS or Kafka is definitely the right backbone. This bus interface gives modular monoliths isolation, backoff, and idempotent handler contracts immediately - and because subscribers depend only on subscribe() and publish(), swapping the transport to SQS/SNS later touches zero domain code."

Pushing Product Manager: "Can we set maxRetries: 10 on every subscriber so nothing hits the DLQ?"

Calm Response: "Ten exponential retries starting at 500ms holds memory and workers open for nine minutes on a permanent 400 bug. Three fast retries absorb transient blips while DLQ routing alerts us immediately and lets us replay cleanly once fixed."

Key Takeaways & This Week's Action Rep

  • Isolate subscribers with Promise.allSettled: One slow or throwing listener must never block siblings.
  • Deduplicate per (subscriptionId, eventId): Let failed subscribers recover via DLQ without re-running succeeded siblings.
  • Inject sleep for instant deterministic tests: Verify exact backoff curves in milliseconds.
  • Bound every dedup cache: Cap processedKeys so long-lived pods never leak heap.

This Week's Action Rep: Run a 45-minute drill without autocomplete. Build PubSubEventBus with filters, exponential backoff, DLQ replay, and (subscriptionId, eventId) deduplication, proving a slow throwing subscriber never delays a fast sibling.