Pub-Sub
easy · observer, topics
Brief-reported interview attribution (unverified): Amazon, Microsoft, Uber
How to approach an LLD roundDesign a publish-subscribe system. Subscribers register a callback
for a topic; publish(topic, message) delivers the message to every current
subscriber of that topic, in subscription order, synchronously. Delivery count is
returned.
class PubSub:
def __init__(self):
def subscribe(self, topic, subscriber_id, callback):
# -> True if newly subscribed, False if this subscriber is already on the topic
def unsubscribe(self, topic, subscriber_id):
# -> True if the subscription existed, False otherwise
def publish(self, topic, message):
# -> number of subscribers the message was delivered to
def topics(self):
# -> sorted list of topics that currently have at least one subscriber
Rules. A subscriber may be on several topics. Publishing to a topic with no
subscribers delivers nothing and returns 0. Publishing must not break if a
callback unsubscribes during delivery (deliver to a snapshot of the subscriber
list). topics() lists only topics with subscribers — publishing alone does not
create a topic.
Tests use explicit inputs and injected clocks/callbacks. No network, real threads or application-server execution is involved.
Public demo
# Public demo: run after implementing the class API above.
p = PubSub()
inbox = []
print(p.subscribe('news', 'alice', lambda message: inbox.append(('alice', message))))
print(p.subscribe('news', 'alice', lambda message: None))Starter code
class PubSub:
def __init__(self):
"""Initialize the state described in the problem."""
pass
def subscribe(self, topic, subscriber_id, callback):
"""-> True if newly subscribed, False if this subscriber is already on the topic"""
pass
def unsubscribe(self, topic, subscriber_id):
"""-> True if the subscription existed, False otherwise"""
pass
def publish(self, topic, message):
"""-> number of subscribers the message was delivered to"""
pass
def topics(self):
"""-> sorted list of topics that currently have at least one subscriber"""
pass
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python compiler