Topic subscription registry
You build a Go topic registry that tracks user subscriptions and publishes messages through a send callback. Publish returns the number of accepted sends.
Ticket
Build a thread-safe topic subscription registry in backend/internal/ws/topics. The topics package must expose Registry, New, Subscribe, Unsubscribe, RemoveUser, Subscribers and Publish.
The tests call these exact signatures directly:
func New() *Registry
func (r *Registry) Subscribe(topic string, userID int64)
func (r *Registry) Unsubscribe(topic string, userID int64)
func (r *Registry) RemoveUser(userID int64)
func (r *Registry) Subscribers(topic string) []int64
func (r *Registry) Publish(topic string, msg []byte, send func(userID int64, msg []byte) bool) intThe WebSocket hub currently sends messages to one user at a time. Order tracking needs several people to watch the same order, including the customer and restaurant. A topic such as order:42 gives those users a shared subscription target. Keep this registry independent of WebSocket connections so the hub can use it without coupling subscription state to connection management.
A slow consumer can refuse a message when its send channel is full. One refused send must not prevent delivery attempts to other subscribers. This is optional extra practice and does not block completion of Week 5.
Acceptance criteria
- Subscribing users
10and11toorder:1, and user12toorder:2, then publishinghitoorder:1delivers the message to users10and11only.Publishreturns2. - Publishing
hito an empty topic such asorder:9returns0. - Subscribing user
10twice toorder:1results in exactly one delivery when the topic is published. - After unsubscribing user
10fromorder:1, publishing to that topic does not deliver to user10, while user11still receives the message. - Unsubscribing user
10when they are not subscribed does not panic or change the subscription for user11. - After user
10subscribes toorder:1andorder:2, and user11subscribes toorder:2, callingRemoveUser(10)leavesorder:1empty andorder:2containing only user11. - After subscribing users
30,10and20toorder:1,Subscribersreturns[10, 20, 30]. Modifying the returned slice must not change the registry. - When user
11refuses a send and user10accepts it,Publishreturns1. Refused sends must not contribute to the returned count. - Eight goroutines concurrently perform subscriptions, publishing, subscriber lookups, unsubscriptions and user removals, each running
200iterations, without data races under the race detector.
Constraints
- Implement the package in
backend/internal/ws/topics/registry.go. - Use only the Go standard library.
- Protect shared registry state with one mutex.
- Keep the registry independent of WebSocket connections. Use the supplied
sendcallback for publishing. - Return subscriber IDs in ascending order as an independent slice.
- Copy subscriber IDs while holding the mutex, then release it before invoking
send. - Do not hold the mutex while invoking callbacks.
- All registry methods must be safe for concurrent use.
Design direction
Keep the implementation in internal/ws/topics. A Registry can own a map from topic names to sets of user IDs. A Go map is a natural fit for the set because it prevents duplicate subscriptions. Use Go maps to represent the relationships without storing duplicate users.
Protect the map with one Mutex. Keep subscription changes short so concurrent operations do not spend unnecessary time waiting for the lock. Remove a topic when its final subscriber leaves.
For Subscribers, build a new slice while reading the set and sort it before returning. Never expose the map's internal state through a returned value.
For Publish, take a snapshot of subscriber IDs while holding the lock. Release the lock before calling the supplied function. This prevents a Slow consumer from blocking subscription changes or other publishing operations. Count only callbacks that return true, and continue attempting delivery when another callback returns false.
Keep the implementation focused on subscription state and delivery accounting. The registry does not need to know how connections are created or closed. Any layout that meets the contract passes.
How to check your work
Run the optional exercise tests from the repository root:
cd backend && make test W=5O2Read the first failing assertion carefully. Compare the actual deliveries, subscriber IDs or accepted-send count with the expected result, and check whether the failure comes from subscription state, callback handling or concurrent access.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
Newcreates a usable topic registry.Subscribeprevents duplicate subscriptions, andUnsubscriberemoves the specified user.RemoveUserremoves the user from every topic.Subscribersreturns ascending user IDs in an independent slice.Publishattempts delivery through the callback and counts only accepted sends.- Concurrent registry operations pass the race detector.
Commands
cd backend && make test W=5O2Tests
TestW5O2_PublishReachesEverySubscriberOfTheTopicinbackend/internal/ws/topics/registry_test.goTestW5O2_PublishToAnEmptyTopicDeliversNothinginbackend/internal/ws/topics/registry_test.goTestW5O2_SubscribingTwiceDeliversOnceinbackend/internal/ws/topics/registry_test.goTestW5O2_UnsubscribeStopsDeliveryinbackend/internal/ws/topics/registry_test.goTestW5O2_UnsubscribingSomeoneNotSubscribedIsHarmlessinbackend/internal/ws/topics/registry_test.goTestW5O2_RemoveUserLeavesEveryTopicinbackend/internal/ws/topics/registry_test.goTestW5O2_SubscribersAreSortedAndACopyinbackend/internal/ws/topics/registry_test.goTestW5O2_PublishCountsOnlyAcceptedSendsinbackend/internal/ws/topics/registry_test.goTestW5O2_ConcurrentUseIsRaceFreeinbackend/internal/ws/topics/registry_test.go