← 返回 snapchat 的题目列表In-Memory Pub/Sub
类型:qbank
Implement an in-memory pub/sub service with topic creation, publishing, subscribing, and follow-up discussion around push notification and concurrency.
Requirements
Implement an in-memory publish / subscribe service.
Likely API:
CreateTopic(topic string)
Subscribe(topic string, subscriberID string)
PublishMessage(topic string, message Message)
Expected behavior:
Topics can be created and looked up by name.
Subscribers can subscribe to a topic.
Publishing to a topic records or delivers a message for all subscribers of that topic.
A follow-up may require subscribers to be notified immediately on publish.
Discuss concurrency safety for simultaneous subscribe and publish operations.
Notes
Start with a simple map from topic name to topic object. Each topic owns a subscriber set and, if needed, an append-only message list. For push-style notification in Go, each subscriber can own a channel; PublishMessage iterates over subscribers and sends or enqueues the message.
The main design choice is blocking vs non-blocking delivery. Blocking sends are simple but one slow subscriber can stall publish. A safer design gives each subscriber a buffered queue and a worker, then defines what happens when the buffer is full: drop, backpressure, or disconnect.
For concurrency, protect topic maps and subscriber sets with locks. A read-write lock only helps when reads truly do not mutate shared structures. Publishing often touches subscriber queues, so make the locking boundary explicit and avoid holding a global lock while doing slow notification work.
Preparation
Implement a single-process pub/sub in your strongest language.
Add tests for publishing to an empty topic, multiple subscribers, duplicate subscriptions, and unknown topics.
Practice explaining push vs pull delivery and what happens when a subscriber is slow.
Be ready to add a mutex / RWMutex and identify race-prone map operations.