> ## Documentation Index
> Fetch the complete documentation index at: https://upstash.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# PSUBSCRIBE

> Subscribe to pattern channels.

Use `PSUBSCRIBE` to subscribe the current connection to channels by glob-style pattern.

A pattern such as `news.*` matches every channel that starts with `news.`, including channels created after the subscription, which is what makes patterns useful for topic hierarchies. `?` matches a single character and `[...]` a character class.

Pattern subscriptions are tracked separately from the exact-channel subscriptions made with [`SUBSCRIBE`](/docs/redis/commands/pub-sub/subscribe), and a message that matches several of a connection's patterns is delivered once per matching pattern, so overlapping patterns produce duplicates. Cancel a pattern with [`PUNSUBSCRIBE`](/docs/redis/commands/pub-sub/punsubscribe), passing exactly the same pattern string.

## Syntax

```redis theme={"system"}
PSUBSCRIBE <pattern> [<pattern> ...]
```

## Arguments

| Argument    | Required | Repeatable | Description                 |
| ----------- | -------- | ---------- | --------------------------- |
| `<pattern>` | Yes      | Yes        | Glob-style channel pattern. |

## Important points

* This is a connection-oriented command and is available over native Redis TCP, not the stateless REST endpoint.
* Subscription commands require a dedicated TCP connection. In RESP3, subscription events use push replies.

## Response

The reply reports the result of the operation. Error replies have the same shape in RESP2 and RESP3 and are surfaced as exceptions by the SDKs below.

| Protocol | Reply                                                   |
| -------- | ------------------------------------------------------- |
| RESP2    | Three-element subscription-state array per pattern      |
| RESP3    | Three-element subscription-state push reply per pattern |

<Note>
  Client libraries often decode bulk strings, maps, sets, and numeric strings into language-native values. The table describes the Redis wire reply.
</Note>

## Examples

TCP examples use the TLS `REDIS_URL` from the Upstash console. REST examples use `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.

<AccordionGroup>
  <Accordion title="Redis CLI" icon="terminal">
    ```bash theme={"system"}
    PSUBSCRIBE events:*
    ```
  </Accordion>

  <Accordion title="ioredis" icon="node-js" iconType="brands">
    ```ts theme={"system"}
    import Redis from "ioredis";

    const subscriber = new Redis(process.env.REDIS_URL!);
    await subscriber.psubscribe("events:*");
    subscriber.on("message", (channel, message) => console.log(channel, message));
    ```
  </Accordion>

  <Accordion title="node-redis" icon="node-js" iconType="brands">
    ```ts theme={"system"}
    import { createClient } from "redis";

    const subscriber = await createClient({ url: process.env.REDIS_URL }).connect();
    await subscriber.pSubscribe("events:*", (message, channel) => {
      console.log(channel, message);
    });
    ```
  </Accordion>

  <Accordion title="redis-py" icon="python" iconType="brands">
    ```python theme={"system"}
    import os
    import redis

    client = redis.from_url(os.environ["REDIS_URL"])
    pubsub = client.pubsub()
    pubsub.psubscribe("events:*")
    for message in pubsub.listen():
        print(message)
    ```
  </Accordion>

  <Accordion title="go-redis" icon="golang" iconType="brands">
    ```go theme={"system"}
    package main

    import (
        "context"
        "fmt"
        "os"

        "github.com/redis/go-redis/v9"
    )

    func main() {
        ctx := context.Background()
        opts, err := redis.ParseURL(os.Getenv("REDIS_URL"))
        if err != nil {
            panic(err)
        }
        client := redis.NewClient(opts)
        pubsub := client.PSubscribe(ctx, "events:*")
        for message := range pubsub.Channel() {
            fmt.Println(message.Channel, message.Payload)
        }
    }
    ```
  </Accordion>

  <Accordion title="jedis" icon="java" iconType="brands">
    ```java theme={"system"}
    import java.net.URI;
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPubSub;

    try (Jedis jedis = new Jedis(new URI(System.getenv("REDIS_URL")))) {
      jedis.psubscribe(new JedisPubSub() {
        @Override
        public void onPMessage(String pattern, String channel, String message) {
          System.out.println(channel + ": " + message);
        }
      }, "events:*");
    }
    ```
  </Accordion>

  <Accordion title="redis-rs" icon="rust" iconType="brands">
    ```rust theme={"system"}
    fn main() -> redis::RedisResult<()> {
        let url = std::env::var("REDIS_URL").expect("REDIS_URL is not set");
        let client = redis::Client::open(url)?;
        let mut connection = client.get_connection()?;
        let mut pubsub = connection.as_pubsub();
        pubsub.psubscribe("events:*")?;
        loop {
            let message = pubsub.get_message()?;
            let payload: String = message.get_payload()?;
            println!("{payload}");
        }
        #[allow(unreachable_code)]
        Ok(())
    }
    ```
  </Accordion>
</AccordionGroup>


## Related topics

- [PSUBSCRIBE](/docs/redis/sdks/ts/commands/pubsub/psubscribe.md)
- [PUNSUBSCRIBE](/docs/redis/commands/pub-sub/punsubscribe.md)
- [PUBSUB](/docs/redis/commands/pub-sub/pubsub.md)
