Katkat

Implement a Publish-Subscribe Event Bus in JavaScript or TypeScript

TradedeskFrontend Engineer · Onsite

Last updated

A front-end coding question asking the candidate to implement an in-process publish-subscribe utility in JavaScript or TypeScript with subscribe, publish, and unsubscribe. It tests API design, choice of data structures, safe iteration when subscribers change during a publish, isolation of subscriber errors, and cleanup that avoids memory leaks.

Implement a publish-subscribe (pub/sub) utility in JavaScript or TypeScript for use inside one front-end application. Code should be able to subscribe a callback to a named topic, publish a payload to every current subscriber of a topic, and stop receiving messages when it no longer needs them. Write the implementation, explain your API choices, and describe how you would test it.

Constraints and Clarifications

  • The utility runs inside one JavaScript runtime. There is no network transport, persistence, or cross-tab messaging.
  • Publishing to a topic with no subscribers is valid and does nothing.
  • The API surface is up to you. At a minimum, it must support subscribing, publishing, and unsubscribing.

Clarifying Questions

  • Should delivery be synchronous, with subscribers called before publish returns, or asynchronous?
  • If one subscriber throws, should the remaining subscribers still receive the message, and how should the error be reported?
  • Should subscribing the same function twice create two subscriptions or be ignored?
  • Are extras needed, such as one-time subscriptions, wildcard topics, or replaying the last message to late subscribers?

Hints

Hint 1

Design the removal handle: Think about what subscribing should give back so a caller can remove exactly its own subscription, even if the same function is subscribed twice.

Hint 2

Consider subscriptions changing mid-publish: Consider what should happen if a subscriber unsubscribes itself, or adds another subscriber, while a publish is running.

Follow-up questions

  • How would you add a `once` subscription, and what happens if it is unsubscribed before it fires?
  • How would you type the utility in TypeScript so each topic's payload type is checked at compile time?
  • What changes if delivery must be asynchronous but still preserve per-topic order?
  • How would a React component subscribe safely so it never receives messages after unmounting?