{
  "id": "ruby",
  "title": "Redis pub/sub with redis-rb",
  "url": "https://redis.io/docs/latest/develop/use-cases/pub-sub/ruby/",
  "summary": "Implement Redis pub/sub messaging in Ruby with redis-rb",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-05-14T08:58:05-05:00",
  "children": [],
  "page_type": "content",
  "content_hash": "e14b752f7af08f69efe67ea76e4a6f83d9c6b4fe483d03d974dcd1bd4ddfbe7d",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "This guide shows you how to implement a Redis-backed pub/sub broadcaster in Ruby with [`redis-rb`](https://redis.io/docs/latest/develop/clients/ruby). It includes a small local web server built with the Ruby standard library [`webrick`](https://github.com/ruby/webrick) so you can publish messages to named channels, add and remove subscribers live, and watch Redis fan out each message to every interested listener."
    },
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "Pub/sub lets your application broadcast events — chat messages, cache invalidation signals, presence updates, notifications — to many consumers without per-pair wiring. The publisher names a *channel*; every client currently subscribed to that channel receives the message, in publish order, with sub-millisecond fan-out.\n\nThat gives you:\n\n* Many-to-many event delivery with no message storage cost in Redis\n* Exact-match subscriptions (`SUBSCRIBE orders:new`) for known topics\n* Pattern subscriptions (`PSUBSCRIBE notifications:*`) for whole topic hierarchies\n* Live server-side introspection through `PUBSUB CHANNELS`, `PUBSUB NUMSUB`, and `PUBSUB NUMPAT`\n* At-most-once delivery: subscribers that are offline when a message is published miss it, so durable state should live in keys or a Stream, not in the pub/sub channel itself\n\nIn this example, the publisher side calls `PUBLISH` with a JSON-encoded body and counts how many subscribers Redis reported delivering to. Each in-process subscriber owns its own Redis connection and a background Ruby `Thread` that pumps incoming messages into a callback."
    },
    {
      "id": "how-it-works",
      "title": "How it works",
      "role": "content",
      "text": "The flow looks like this:\n\n1. The application calls `hub.subscribe(name:, channels:)` or `hub.psubscribe(name:, patterns:)`\n2. The helper creates a fresh `Redis` client for the subscriber, spawns a Ruby `Thread`, and inside that thread calls `redis.subscribe(*channels)` (or `redis.psubscribe(*patterns)`), which blocks the connection in subscribe-only mode\n3. The application (or another process) calls `hub.publish(channel, message)` on the hub's plain (non-subscriber) Redis client\n4. Redis fans the message out over every subscribing client's open socket\n5. Each subscriber's worker thread receives the message inside the `on.message` / `on.pmessage` callback, wraps it as a `ReceivedMessage`, and pushes it into a per-subscriber ring buffer\n6. The publisher receives the integer subscriber count back from `PUBLISH`, which is the number of clients Redis delivered to right then\n\nPattern subscriptions match channels by glob (`*`, `?`, `[abc]`). A single message that matches both an exact subscription and a pattern subscription is delivered twice — once as a `message` and once as a `pmessage`."
    },
    {
      "id": "the-pub-sub-hub-helper",
      "title": "The pub/sub hub helper",
      "role": "content",
      "text": "The `RedisPubSubHub` class wraps the publish, subscribe, and introspection operations\n([source](https://github.com/redis/docs/blob/main/content/develop/use-cases/pub-sub/ruby/pubsub_hub.rb)):\n\n[code example]"
    },
    {
      "id": "data-model",
      "title": "Data model",
      "role": "content",
      "text": "Pub/sub has no Redis keyspace footprint of its own — channels are server-side routing entries, not stored values. The hub keeps its own bookkeeping in process memory:\n\n[code example]\n\nThe implementation uses:\n\n* [`PUBLISH`](https://redis.io/docs/latest/commands/publish) to fan a JSON-encoded message out to every subscriber of a channel\n* [`SUBSCRIBE`](https://redis.io/docs/latest/commands/subscribe) for exact-match subscribers\n* [`PSUBSCRIBE`](https://redis.io/docs/latest/commands/psubscribe) for glob-style pattern subscribers\n* [`PUBSUB CHANNELS`](https://redis.io/docs/latest/commands/pubsub-channels) to list the channels with at least one active exact-match subscriber\n* [`PUBSUB NUMSUB`](https://redis.io/docs/latest/commands/pubsub-numsub) to count subscribers per channel\n* [`PUBSUB NUMPAT`](https://redis.io/docs/latest/commands/pubsub-numpat) to count active pattern subscriptions server-wide\n* A Ruby `Thread` per subscriber, each with its own `Redis` instance, so `redis.subscribe` can monopolise its connection without blocking the rest of the process"
    },
    {
      "id": "publishing-messages",
      "title": "Publishing messages",
      "role": "content",
      "text": "`publish` JSON-encodes the message body, calls `PUBLISH`, and updates the per-channel publish counter:\n\n[code example]\n\nThe integer returned by `PUBLISH` is what Redis itself reports — the number of subscribers (direct and pattern) that received the message in that call. It's a useful sanity check that the channel name is actually being listened to: a steady stream of `0`s means you have a typo somewhere or your subscriber crashed."
    },
    {
      "id": "subscribing-to-channels",
      "title": "Subscribing to channels",
      "role": "content",
      "text": "`subscribe` creates a named in-process `Subscription` that owns its own `Redis` client and a worker thread. Inside `Subscription#initialize` (the relevant excerpt):\n\n[code example]\n\nA few details matter here:\n\n* **Each Subscription gets its own Redis client.** In redis-rb 5.x, `Redis#subscribe` puts its connection into subscribe-only mode: ordinary commands (`GET`, `HSET`) on the same connection will raise. Sharing one client across subscribers would also couple their lifetimes — unsubscribing one would close the channel for the others.\n* **The thread blocks inside `subscribe`.** Unlike redis-py's `pubsub.run_in_thread()`, redis-rb's subscribe loop *is* the worker — it doesn't return until the server has unsubscribed the connection. That's why the helper spawns one `Thread` per subscriber and stores it.\n* **A `Queue` latch lets the constructor wait for the first SUBSCRIBE ack.** Without it, a `publish` issued immediately after `subscribe` could race the subscribe handshake and arrive before Redis knew about the client. Blocking on the `on.subscribe` callback before returning from `initialize` removes that race."
    },
    {
      "id": "pattern-subscriptions-with-psubscribe",
      "title": "Pattern subscriptions with PSUBSCRIBE",
      "role": "content",
      "text": "`psubscribe` works the same way but routes messages through `PSUBSCRIBE` so each binding is a glob, not a literal channel name:\n\n[code example]\n\nWhen a published channel matches a pattern, redis-rb invokes the `on.pmessage` callback with both the matched channel and the original pattern:\n\n[code example]\n\nThat distinction is useful for routing: a pattern subscriber can do one thing for the whole hierarchy (e.g., increment a counter) and dispatch on the specific channel within its callback (e.g., \"invalidate this region's cache\")."
    },
    {
      "id": "unsubscribing-without-sentinel-messages",
      "title": "Unsubscribing without sentinel messages",
      "role": "content",
      "text": "`hub.unsubscribe(name)` (and `hub.shutdown` for everything) needs to break the worker thread out of its blocking `subscribe` call. The cleanest way in redis-rb 5.x is to call `unsubscribe` (or `punsubscribe`) on the *same* subscriber connection from another thread — redis-rb sends the command down the open subscribe socket, Redis responds with the unsubscribe acknowledgement, the subscribe block returns, and the worker thread exits:\n\n[code example]\n\nThat avoids the older \"publish a STOP sentinel and unsubscribe from inside the handler\" pattern, which pollutes the user-facing channel namespace with control messages."
    },
    {
      "id": "inspecting-active-subscribers",
      "title": "Inspecting active subscribers",
      "role": "content",
      "text": "Redis exposes a small set of pub/sub introspection commands that report on subscriber state without traversing any keyspace:\n\n[code example]\n\n`PUBSUB CHANNELS` only reports channels with at least one exact-match subscriber — pattern subscribers do not appear here. That's a deliberate Redis design choice: a glob like `*` would otherwise show up as a subscriber to every conceivable channel. `PUBSUB NUMPAT` covers the pattern side as a single global count.\n\nNote that redis-rb returns `PUBSUB NUMSUB` as an alternating `[channel, count, channel, count, …]` array; the helper pairs the elements up into a hash before returning to keep the wire shape consistent with the other clients."
    },
    {
      "id": "stats-and-history",
      "title": "Stats and history",
      "role": "content",
      "text": "`stats` reports publish and receive counters plus the size of the subscription registry:\n\n[code example]\n\n`delivered_total` is what Redis itself counted; `received_total` is what this process's in-memory subscribers saw. In a single-process demo they should track each other closely — a sustained divergence usually means a callback raised, or a subscriber crashed while a publisher kept publishing. (Pub/sub is at-most-once: if your subscriber wasn't connected at publish time, the message is gone.)"
    },
    {
      "id": "prerequisites",
      "title": "Prerequisites",
      "role": "content",
      "text": "* Redis 6.2 or later running locally on the default port (6379). Earlier versions still work for plain `PUBLISH`/`SUBSCRIBE`; `PUBSUB NUMPAT` is older than that.\n* Ruby 3.0 or later.\n* The [`redis-rb`](https://github.com/redis/redis-rb) gem (5.x). Install it with:\n\n  [code example]\n\n* The [`webrick`](https://github.com/ruby/webrick) gem (it was extracted from the Ruby standard library in Ruby 3.0):\n\n  [code example]"
    },
    {
      "id": "running-the-demo",
      "title": "Running the demo",
      "role": "content",
      "text": ""
    },
    {
      "id": "get-the-source-files",
      "title": "Get the source files",
      "role": "content",
      "text": "The demo consists of two Ruby files. Download them from the [`ruby` source folder](https://github.com/redis/docs/tree/main/content/develop/use-cases/pub-sub/ruby) on GitHub, or grab them with `curl`:\n\n[code example]"
    },
    {
      "id": "start-the-demo-server",
      "title": "Start the demo server",
      "role": "content",
      "text": "From that directory:\n\n[code example]\n\nYou should see:\n\n[code example]\n\nOpen [http://127.0.0.1:8102](http://127.0.0.1:8102) in a browser. You can:\n\n* Publish messages of any text to any channel name in any batch size.\n* Add named subscribers that listen on either a specific channel (`orders:new`) or a glob pattern (`notifications:*`). A single subscriber can listen on multiple targets — enter them comma-separated.\n* Watch each subscriber's incoming-message panel update every 800 ms.\n* See the server-side view: `PUBSUB CHANNELS` lists exact-match channels with subscribers, `PUBSUB NUMSUB` gives per-channel counts, and `PUBSUB NUMPAT` counts active pattern subscriptions.\n* Click **Reset** to drop every subscription, zero the counters, and re-seed the three default subscribers.\n\nIf your Redis server is running elsewhere, start the demo with `--redis-host` and `--redis-port`. The HTTP bind host and port can be overridden with `--host` and `--port`."
    },
    {
      "id": "production-usage",
      "title": "Production usage",
      "role": "content",
      "text": ""
    },
    {
      "id": "pub-sub-is-at-most-once-pair-it-with-durable-state-if-you-need-replay",
      "title": "Pub/sub is at-most-once — pair it with durable state if you need replay",
      "role": "content",
      "text": "A subscriber that's offline when a message is published misses it permanently. For events you can't afford to lose, write the durable record (the order row, the cache key version, the audit log entry) to its primary store, then `PUBLISH` a notification so live consumers can pick it up immediately. On reconnect, consumers reconcile by reading the durable store, not by waiting for missed pub/sub messages. If you actually need replay or at-least-once delivery, switch to [Redis Streams](https://redis.io/docs/latest/develop/data-types/streams) with consumer groups."
    },
    {
      "id": "give-every-subscriber-its-own-redis-connection",
      "title": "Give every subscriber its own Redis connection",
      "role": "content",
      "text": "In redis-rb 5.x, `Redis#subscribe` blocks the calling thread *and* monopolises the underlying connection — any non-pub/sub command issued on the same client will raise. The helper sidesteps that by creating a fresh `Redis` client for every `Subscription`, and using a separate plain client on the hub for `PUBLISH` and the `PUBSUB CHANNELS` / `NUMSUB` / `NUMPAT` introspection commands. In a long-running service, treat each subscriber as owning its connection for the duration of its subscription, and pool connections separately for command-mode work."
    },
    {
      "id": "choose-a-topic-naming-convention-up-front",
      "title": "Choose a topic naming convention up front",
      "role": "content",
      "text": "A flat namespace gets ugly fast — `email`, `email_high_priority`, `email_high_priority_billing`. Pick a colon-separated hierarchy (`notifications:billing:invoice`, `cache:invalidate:products:p-001`) so consumers can subscribe at the right level: a billing service uses `notifications:billing:*`, the audit logger uses `notifications:*`. Glob patterns are evaluated for every published message, so don't go wild with multiple wildcards on hot paths — `*:*:*` matches everything and costs more than a flat `notifications:*` would."
    },
    {
      "id": "don-t-do-heavy-work-in-the-subscribe-block",
      "title": "Don't do heavy work in the subscribe block",
      "role": "content",
      "text": "The worker thread reads messages from a single socket inside the `on.message` / `on.pmessage` callback. If the callback blocks (synchronous HTTP call, big computation, slow DB write), the next message waits behind it and the subscriber's effective throughput drops to whatever the callback's latency is. For heavier work, the callback should hand the message off to a worker pool (a [`Concurrent::ThreadPoolExecutor`](https://github.com/ruby-concurrency/concurrent-ruby), a Sidekiq job, …) or — for true durable handoff — a [Redis Streams](https://redis.io/docs/latest/develop/data-types/streams) consumer group."
    },
    {
      "id": "tune-the-subscriber-buffer-for-your-traffic-shape",
      "title": "Tune the subscriber buffer for your traffic shape",
      "role": "content",
      "text": "The demo caps each subscriber's in-memory message buffer at 50. That's right for showing the recent activity in a UI, but a real subscriber typically processes each message and discards it — the buffer is only there for human inspection. If you keep a buffer, make sure it's bounded; an unbounded ring on a chatty pattern subscriber will eventually OOM the process."
    },
    {
      "id": "use-the-gil-friendly-cooperative-concurrency-model",
      "title": "Use the GIL-friendly cooperative concurrency model",
      "role": "content",
      "text": "Ruby (MRI) threads release the GIL on blocking I/O, so a per-subscriber thread sleeping inside a socket read does not stall the rest of the process. That's why one Ruby thread per active subscriber is a workable model even at hundreds of subscribers — you're not consuming a CPU thread, just a `Redis` connection. If you instead need thousands of subscribers per process, consider switching to one of the fibre-based async drivers (e.g. [`async-redis`](https://github.com/socketry/async-redis)) so subscriber sockets can multiplex inside a single reactor."
    },
    {
      "id": "sharded-pub-sub-on-a-redis-cluster",
      "title": "Sharded pub/sub on a Redis Cluster",
      "role": "content",
      "text": "On a Redis Cluster, plain `PUBLISH` fans every message out to every node via the cluster bus, which becomes a hotspot at high throughput. Redis 7.0 added [sharded pub/sub](https://redis.io/docs/latest/develop/pubsub#sharded-pubsub): channels are hashed to slots, and `SPUBLISH` / `SSUBSCRIBE` only touch the shard that owns the slot. If you're scaling pub/sub on a cluster, prefer the sharded commands and pick channel names whose hash distribution matches your traffic."
    },
    {
      "id": "inspect-pub-sub-state-directly-in-redis",
      "title": "Inspect pub/sub state directly in Redis",
      "role": "content",
      "text": "Because pub/sub has no keyspace, `KEYS`/`SCAN` won't show you anything. Use the introspection commands instead:\n\n[code example]\n\n`redis-cli` in subscribe mode only exits with `Ctrl-C` — it can't issue any other commands while subscribed."
    },
    {
      "id": "learn-more",
      "title": "Learn more",
      "role": "related",
      "text": "This example uses the following Redis commands:\n\n* [`PUBLISH`](https://redis.io/docs/latest/commands/publish) to fan a message out to every subscriber of a channel.\n* [`SUBSCRIBE`](https://redis.io/docs/latest/commands/subscribe) and [`UNSUBSCRIBE`](https://redis.io/docs/latest/commands/unsubscribe) for exact-match topic subscriptions.\n* [`PSUBSCRIBE`](https://redis.io/docs/latest/commands/psubscribe) and [`PUNSUBSCRIBE`](https://redis.io/docs/latest/commands/punsubscribe) for glob-style pattern subscriptions.\n* [`PUBSUB CHANNELS`](https://redis.io/docs/latest/commands/pubsub-channels) to list channels with at least one active exact-match subscriber.\n* [`PUBSUB NUMSUB`](https://redis.io/docs/latest/commands/pubsub-numsub) to count subscribers per named channel.\n* [`PUBSUB NUMPAT`](https://redis.io/docs/latest/commands/pubsub-numpat) to count active pattern subscriptions server-wide.\n\nSee the [`redis-rb` documentation](https://redis.io/docs/latest/develop/clients/ruby) for full client reference, including the [`Redis#subscribe`](https://www.rubydoc.info/gems/redis/Redis#subscribe-instance_method) and [`Redis#psubscribe`](https://www.rubydoc.info/gems/redis/Redis#psubscribe-instance_method) helpers."
    }
  ],
  "examples": [
    {
      "id": "the-pub-sub-hub-helper-ex0",
      "language": "ruby",
      "code": "require 'redis'\nrequire_relative 'pubsub_hub'\n\nhub = PubSubHub::RedisPubSubHub.new(\n  redis_options: { host: 'localhost', port: 6379 }\n)\n\n# Exact-match subscriber\nhub.subscribe(name: 'orders-listener', channels: ['orders:new'])\n\n# Pattern subscriber covering an entire topic hierarchy\nhub.psubscribe(name: 'all-notifications', patterns: ['notifications:*'])\n\n# Publish — returns Redis' delivered count for this PUBLISH\ndelivered = hub.publish('orders:new', { 'order_id' => 42, 'total' => 199.0 })\nputs \"Redis delivered to #{delivered} subscriber(s)\"\n\n# Look at what each subscriber received\nhub.subscriptions.each do |sub|\n  puts \"#{sub.name} #{sub.received_total} messages\"\n  sub.messages(5).each do |message|\n    puts \"  #{message.channel} #{message.payload.inspect}\"\n  end\nend\n\nhub.unsubscribe('orders-listener')\nhub.shutdown  # closes every remaining subscription",
      "section_id": "the-pub-sub-hub-helper"
    },
    {
      "id": "data-model-ex0",
      "language": "text",
      "code": "RedisPubSubHub                          (in-process)\n  subscriptions             Hash{String => Subscription}\n  published_total           Integer\n  delivered_total           Integer\n  channel_published         Hash{channel => count}\n\nSubscription                            (in-process, one per subscriber)\n  name                      String\n  targets                   Array<channel | pattern>\n  is_pattern?               Boolean\n  buffer                    Array<ReceivedMessage>     (capped, default 50)\n  received_total            Integer\n  redis                     Redis                       (its own connection)\n  thread                    Thread                       (blocks on subscribe)",
      "section_id": "data-model"
    },
    {
      "id": "publishing-messages-ex0",
      "language": "ruby",
      "code": "def publish(channel, message)\n  payload = JSON.generate(message)\n  delivered = @redis.publish(channel, payload).to_i\n  @stats_lock.synchronize do\n    @published_total += 1\n    @delivered_total += delivered\n    @channel_published[channel] += 1\n  end\n  delivered\nend",
      "section_id": "publishing-messages"
    },
    {
      "id": "subscribing-to-channels-ex0",
      "language": "ruby",
      "code": "@redis = Redis.new(redis_options)\n@thread = Thread.new do\n  @redis.subscribe(*@targets) do |on|\n    on.subscribe   { |_channel, _count| @ready_latch.push(true) }\n    on.message     { |channel, raw|    dispatch(channel: channel, pattern: nil, raw: raw) }\n    on.unsubscribe { |_channel, _count| }\n  end\nend\n@ready_latch.pop  # block until the server acks SUBSCRIBE",
      "section_id": "subscribing-to-channels"
    },
    {
      "id": "pattern-subscriptions-with-psubscribe-ex0",
      "language": "ruby",
      "code": "hub.psubscribe(name: 'all-notifications', patterns: ['notifications:*'])\nhub.psubscribe(name: 'cache-invalidator', patterns: ['cache:invalidate:*'])",
      "section_id": "pattern-subscriptions-with-psubscribe"
    },
    {
      "id": "pattern-subscriptions-with-psubscribe-ex1",
      "language": "ruby",
      "code": "@redis.psubscribe(*@targets) do |on|\n  on.pmessage do |pattern, channel, raw|\n    dispatch(channel: channel, pattern: pattern, raw: raw)\n  end\nend",
      "section_id": "pattern-subscriptions-with-psubscribe"
    },
    {
      "id": "unsubscribing-without-sentinel-messages-ex0",
      "language": "ruby",
      "code": "def close\n  return if @closed\n  @closed = true\n  if @is_pattern\n    @redis.punsubscribe\n  else\n    @redis.unsubscribe\n  end\n  @thread.join(2)\n  @redis.close\nend",
      "section_id": "unsubscribing-without-sentinel-messages"
    },
    {
      "id": "inspecting-active-subscribers-ex0",
      "language": "ruby",
      "code": "hub.active_channels                       # PUBSUB CHANNELS *\nhub.channel_subscriber_counts(channels)   # PUBSUB NUMSUB ch1 ch2 ...\nhub.pattern_subscriber_count              # PUBSUB NUMPAT",
      "section_id": "inspecting-active-subscribers"
    },
    {
      "id": "stats-and-history-ex0",
      "language": "ruby",
      "code": "def stats\n  published_total, delivered_total, channel_published =\n    @stats_lock.synchronize do\n      [@published_total, @delivered_total, @channel_published.dup]\n    end\n  subs = subscriptions\n  {\n    'published_total'       => published_total,\n    'delivered_total'       => delivered_total,           # sum of PUBLISH return values\n    'received_total'        => subs.sum(&:received_total),\n    'active_subscriptions'  => subs.length,\n    'channel_published'     => channel_published,\n    'pattern_subscriptions' => pattern_subscriber_count\n  }\nend",
      "section_id": "stats-and-history"
    },
    {
      "id": "prerequisites-ex0",
      "language": "bash",
      "code": "gem install redis",
      "section_id": "prerequisites"
    },
    {
      "id": "prerequisites-ex1",
      "language": "bash",
      "code": "gem install webrick",
      "section_id": "prerequisites"
    },
    {
      "id": "get-the-source-files-ex0",
      "language": "bash",
      "code": "mkdir pub-sub-demo && cd pub-sub-demo\nBASE=https://raw.githubusercontent.com/redis/docs/main/content/develop/use-cases/pub-sub/ruby\ncurl -O $BASE/pubsub_hub.rb\ncurl -O $BASE/demo_server.rb",
      "section_id": "get-the-source-files"
    },
    {
      "id": "start-the-demo-server-ex0",
      "language": "bash",
      "code": "gem install redis webrick\nruby demo_server.rb",
      "section_id": "start-the-demo-server"
    },
    {
      "id": "start-the-demo-server-ex1",
      "language": "text",
      "code": "Redis pub/sub demo server listening on http://127.0.0.1:8102\nUsing Redis at localhost:6379\nSeeded 3 default subscription(s)",
      "section_id": "start-the-demo-server"
    },
    {
      "id": "inspect-pub-sub-state-directly-in-redis-ex0",
      "language": "bash",
      "code": "# Which channels currently have at least one exact-match subscriber?\nredis-cli pubsub channels '*'\n\n# How many subscribers does each channel have?\nredis-cli pubsub numsub orders:new notifications:billing chat:lobby\n\n# How many active pattern subscriptions across the whole server?\nredis-cli pubsub numpat\n\n# Subscribe interactively from the CLI to watch traffic on a pattern\nredis-cli psubscribe 'orders:*'",
      "section_id": "inspect-pub-sub-state-directly-in-redis"
    }
  ]
}
