Skip to main content
⚙️ Systems Primitives

What you're building

A publish/subscribe message bus — the pattern at the core of Kafka, Redis Pub/Sub, Google Cloud Pub/Sub, and every microservices event system.

Unlike a plain event emitter, a pub/sub bus separates topics from subscribers, supports multiple subscriber groups, and can replay missed messages.

Requirements

Build a PubSubBus class:

  • subscribe(topic, handler) — register a handler for a topic. Return an unsubscribe function.
  • publish(topic, message) — deliver message to all handlers subscribed to topic. Return the count of handlers called.
  • unsubscribeAll(topic) — remove every subscriber for a topic.
  • subscriberCount(topic) — return how many handlers are active for a topic.

The bus must support wildcard topics: if a handler subscribes to "*", it receives messages from every topic.

Stretch goals

  • Message history: store the last N messages per topic (configurable). New subscribers can request a replay.
  • Async handlers: detect returned Promises and await them before returning from publish.

What this proves

You understand decoupled architecture, fan-out delivery, and the observer pattern at scale. Any senior backend interview may ask you to sketch a pub/sub system.

⚡ 50 XP
solution.jsRuns in your browser
Loading editor…
Tests4 to pass
publish delivers to subscribers
publish returns handler count
unsubscribe function stops delivery
wildcard * receives all topics

Run your code to check these.