Skip to content
BytePatterns

Event Bus With Topic Wildcards

MediumLow-Level Design#observer#topic-matching~25m

Problem

Design an in-process event bus. subscribe(pattern, handler) registers a handler and returns a token, and unsubscribe(token) removes it again. Topics are dot-separated, such as order.paid, and in a pattern a * matches exactly one segment, so order.* matches order.paid but neither order nor order.paid.late. publish(topic, payload) calls every matching handler in the order they subscribed and returns how many were called. A handler that raises must not stop the handlers after it; the bus counts the failure in failures and carries on.

Examples

Input:  subscribe("order.*", audit), subscribe("order.paid", broken), subscribe("order.paid", ship)
        publish("order.paid", "o7")
Output: 3, log = ['audit o7', 'ship o7'], failures = 1
Why:    broken raised, but ship still ran after it
Input:  then unsubscribe(the audit token), publish("order.created", "o8")
Output: 0
Why:    the only handler for order.* is gone, and order.paid does not match
Input:  then publish("order.paid.late", "o9")
Output: 0
Why:    edge case, a * never stretches over two segments

Hints

0 / 3

Stuck on the idea rather than the code? Observer Pattern covers it.