Publishers emit messages to topics; subscribers receive matching messages without direct coupling. WebSocket commonly carries the client side over a broker (Redis, NATS, Kafka).
function publish(topic, payload) { const subs = topics.get(topic); if (!subs) return; const msg = JSON.stringify({ "type":"msg", "topic":topic, "payload":payload }); for (const c of subs) if (c.readyState === 1) c.send(msg);}
5. Implementing Topic Wildcards
Convention
Match
* (single segment)
orders.* → orders.new
# (multi segment)
orders.# → orders.eu.new
:param
Named capture (custom)
6. Handling Private Channels
Type
Access
Public
Anyone may subscribe
Private (private- prefix)
Auth required
Presence
Auth + member list
Encrypted
End-to-end key per channel
7. Implementing Message Filtering
Example: Predicate filter
// per-subscriber filterfunction publishFiltered(topic, payload) { for (const c of topics.get(topic) ?? []) { if (c.filter?.(payload) ?? true) c.send(JSON.stringify(payload)); }}