Pub-Sub Event Bus with Multiple Threads

Hard
ConcurrencyPub-SubObserver PatternBlockingQueueThread PoolConcurrentHashMap

Problem Statement

Design a thread-safe, asynchronous Pub-Sub message bus where publishers emit messages to named topics and subscribers receive messages for their subscribed topics. Message delivery must be asynchronous — publishers must not block waiting for subscribers to process messages.

interface Subscriber {
    void onMessage(String topic, Object message);
}

class EventBus {
    public EventBus(int deliveryThreadPoolSize) {}
    public void subscribe(String topic, Subscriber subscriber) {}
    public void unsubscribe(String topic, Subscriber subscriber) {}
    public void publish(String topic, Object message) {}
    public void shutdown() throws InterruptedException {}
    public int subscriberCount(String topic) {}
}

Key Entities

  • ConcurrentHashMap<String, CopyOnWriteArraySet<Subscriber>>: Topic → subscriber set.
  • ExecutorService: Async delivery of messages to subscribers.
  • CopyOnWriteArraySet: Allows concurrent subscription changes without blocking publishers.
  • Message envelope: Topic + payload + timestamp.

Requirements

  1. Publishers call publish() and return immediately (non-blocking).
  2. Each subscriber's onMessage() is called asynchronously via the thread pool.
  3. Subscribers can subscribe/unsubscribe at any time without blocking publishers.
  4. Messages to a topic are delivered to all subscribers of that topic.
  5. Slow subscribers must not block other subscribers from receiving messages.

Asked at: Amazon, Google, Microsoft, Uber, Netflix, LinkedIn, Flipkart

!Constraints

- Topic names are non-null, non-empty strings. - A subscriber may subscribe to multiple topics. - Multiple subscribers per topic must all receive every published message. - Message ordering per subscriber should be preserved (messages to the same subscriber are delivered in publish order). - shutdown() completes delivery of all in-flight messages before stopping.
Output

Run or submit your code to see output here.