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:

go
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) int

The 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 10 and 11 to order:1, and user 12 to order:2, then publishing hi to order:1 delivers the message to users 10 and 11 only. Publish returns 2.
  • Publishing hi to an empty topic such as order:9 returns 0.
  • Subscribing user 10 twice to order:1 results in exactly one delivery when the topic is published.
  • After unsubscribing user 10 from order:1, publishing to that topic does not deliver to user 10, while user 11 still receives the message.
  • Unsubscribing user 10 when they are not subscribed does not panic or change the subscription for user 11.
  • After user 10 subscribes to order:1 and order:2, and user 11 subscribes to order:2, calling RemoveUser(10) leaves order:1 empty and order:2 containing only user 11.
  • After subscribing users 30, 10 and 20 to order:1, Subscribers returns [10, 20, 30]. Modifying the returned slice must not change the registry.
  • When user 11 refuses a send and user 10 accepts it, Publish returns 1. Refused sends must not contribute to the returned count.
  • Eight goroutines concurrently perform subscriptions, publishing, subscriber lookups, unsubscriptions and user removals, each running 200 iterations, 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 send callback 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:

bash
cd backend && make test W=5O2

Read 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.

Finished Exercise 5.16?

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. New creates a usable topic registry.
  2. Subscribe prevents duplicate subscriptions, and Unsubscribe removes the specified user.
  3. RemoveUser removes the user from every topic.
  4. Subscribers returns ascending user IDs in an independent slice.
  5. Publish attempts delivery through the callback and counts only accepted sends.
  6. Concurrent registry operations pass the race detector.

Commands

terminal
cd backend && make test W=5O2

Tests

  • TestW5O2_PublishReachesEverySubscriberOfTheTopic in backend/internal/ws/topics/registry_test.go
  • TestW5O2_PublishToAnEmptyTopicDeliversNothing in backend/internal/ws/topics/registry_test.go
  • TestW5O2_SubscribingTwiceDeliversOnce in backend/internal/ws/topics/registry_test.go
  • TestW5O2_UnsubscribeStopsDelivery in backend/internal/ws/topics/registry_test.go
  • TestW5O2_UnsubscribingSomeoneNotSubscribedIsHarmless in backend/internal/ws/topics/registry_test.go
  • TestW5O2_RemoveUserLeavesEveryTopic in backend/internal/ws/topics/registry_test.go
  • TestW5O2_SubscribersAreSortedAndACopy in backend/internal/ws/topics/registry_test.go
  • TestW5O2_PublishCountsOnlyAcceptedSends in backend/internal/ws/topics/registry_test.go
  • TestW5O2_ConcurrentUseIsRaceFree in backend/internal/ws/topics/registry_test.go