# SUBSCRIBE

> Subscribe the connection to one or more Pub/Sub channels.

URL: https://docs.hotkv.com/commands/subscribe/

```
SUBSCRIBE channel [channel ...]
```

- Group: Pub/Sub
- Complexity: O(N) for N channels
- HotKV Cloud: all plans
- On-Premise: no license needed

`SUBSCRIBE` makes the connection receive every message later published with
[PUBLISH](https://docs.hotkv.com/commands/publish/index.md) to any of the given channels. Messages are not
stored: a subscriber only gets messages published while it is subscribed. In a
cluster, a message published on any node reaches subscribers on every node.

The server sends one confirmation per channel. After that a RESP2 connection is in
subscribed mode: it receives messages as they arrive and accepts only
`SUBSCRIBE`, [PSUBSCRIBE](https://docs.hotkv.com/commands/psubscribe/index.md),
[SSUBSCRIBE](https://docs.hotkv.com/commands/ssubscribe/index.md), their `UNSUBSCRIBE` counterparts,
`PUBLISH`, `SPUBLISH`, `PUBSUB`, `PING`, `QUIT` and `RESET`. Other commands
reply with
`ERR Can't execute '<command>': only (P|S)SUBSCRIBE / (P|S)UNSUBSCRIBE / PING / QUIT / RESET are allowed in this context`.
A RESP3 connection (after `HELLO 3`) can run any command while it is subscribed.
The connection leaves subscribed mode when it has no channel, pattern or
shard channel subscriptions left.

## Return value

For each channel, a confirmation:

| Element | Value |
| --- | --- |
| 1 | Bulk string `subscribe` |
| 2 | Bulk string: the channel |
| 3 | Integer: the number of channels and patterns this connection is now subscribed to |

Each message then arrives as `message`, the channel, and the payload. On RESP2
these are arrays; on RESP3 they are push messages with the same elements.

## Examples

```
127.0.0.1:6379> SUBSCRIBE news alerts
1) "subscribe"
2) "news"
3) (integer) 1
1) "subscribe"
2) "alerts"
3) (integer) 2
1) "message"
2) "news"
3) "release 2.0 is out"
```

## Compatibility

Same replies and message format as Redis 7 and Valkey 8. One difference in
subscribed mode: a RESP2 connection may also run `PUBLISH`, `SPUBLISH` and
`PUBSUB`, which Redis refuses there.

## See also

[UNSUBSCRIBE](https://docs.hotkv.com/commands/unsubscribe/index.md), [PUBLISH](https://docs.hotkv.com/commands/publish/index.md),
[PSUBSCRIBE](https://docs.hotkv.com/commands/psubscribe/index.md), [SSUBSCRIBE](https://docs.hotkv.com/commands/ssubscribe/index.md),
[PUBSUB](https://docs.hotkv.com/commands/pubsub/index.md)