Skip to content

Step 1 of 3 · Reading · ~2 min

Pub/Sub Messaging

Advanced Features

Pub/Sub in a single-client harness

Real Redis pub/sub is inherently multi-client: one connection calls SUBSCRIBE, another calls PUBLISH, and the server pushes messages across sockets asynchronously. Your test harness, however, talks to your server over a single stdin/stdout stream — so this lesson asks you to simulate the multi-client model with internal bookkeeping rather than real concurrent connections. Understanding that constraint up front will save you from over-engineering a socket-based solution you don't need yet.

The subscription registry

Model it as channel → set of subscribers, plus (since there's conceptually one client driving the session) a simple set of "channels I'm subscribed to":

python

Because the harness is single-client, my_subscriptions effectively models "this connection's subscriptions," while channel_subscribers[channel] tracks how many (simulated) subscribers exist in total — which is what PUBLISH's return value depends on.

SUBSCRIBE

Each channel argument gets its own confirmation line, and the count in that confirmation is the running total of subscriptions so far in this call (not just this channel) — that's how real Redis's multi-channel SUBSCRIBE behaves too:

python

PUBLISH

Two things happen on publish: compute the subscriber count for the return value, and — only if this session is itself subscribed to the channel — emit a +message channel text\r\n line, since there's no second connection to push it to:

python

Re-read the exercise contract carefully here: it explicitly simplifies real Redis's "number of clients that received the message" down to a binary 1 (any subscriber exists) or 0 (none do) — don't try to build exact per-message delivery counts across a nonexistent multi-connection model.

UNSUBSCRIBE

Mirrors SUBSCRIBE: confirm per channel, reporting the remaining subscription count after removal. Calling it with no arguments means "unsubscribe from everything currently subscribed":

python

Why this design still teaches the real concept

Even simplified to one connection, this lesson forces you to build the two structural pieces every pub/sub system needs: a topic → subscriber-set index for fan-out, and per-connection subscription state for routing incoming messages to the right sockets. When you later extend this server to handle genuinely concurrent connections, this is the exact data structure you'll reuse — you'll just be pushing +message ...\r\n across real sockets to every entry in channel_subscribers[channel] instead of checking channel in my_subscriptions.

Up nextRDB Persistence — Snapshot to DiskAdvanced Features

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…