OBSERVE
Subscribes to a query and pushes the command result whenever the key changes.
- Since DiceDB 1.0.1
- ACL Categories: @keyspace@read
OBSERVE <cmd> <key> [args...] subscribes the current connection to the result of the given
readonly command. DiceDB evaluates the command immediately and sends the current result, then
re-evaluates and pushes a new result every time the observed key is modified.
Right now, DiceDB supports
OBSERVE GETandOBSERVE ZRANGE.
Syntax
OBSERVE <cmd> key [arg [arg ...]]The arguments after the command name are identical to the base command. For example:
OBSERVE GET mykey
OBSERVE ZRANGE myzset 0 -1 WITHSCORESParameters
| Parameter | Description | Type | Required |
|---|---|---|---|
cmd | The readonly command to observe (e.g., GET, ZRANGE) | String | Yes |
key | The key to observe | String | Yes |
arg | Additional arguments required by the base command | Any | Depends on command |
Return Value
Every message (initial result and subsequent change notifications) is a 5-element array:
["observe", "fingerprint", "<hex-fingerprint>", "result", <command-result>]| Element | Description |
|---|---|
observe | Identifies the message as an observe notification |
fingerprint | Label for the fingerprint field |
<hex-fingerprint> | CRC64 hex hash of the command name + arguments; uniquely identifies this subscription |
result | Label for the result field |
<command-result> | The return value of the base command at the time of the notification |
Behaviour
- On subscribe, DiceDB immediately evaluates the base command and sends the current result.
- Any write command that modifies the observed key triggers re-evaluation and then the new result is pushed to all subscribed clients.
- If
observe-debounce-period-msis greater than0, rapid successive writes are buffered and a single notification is emitted after the debounce window expires. - The subscription remains active until
UNOBSERVEis called or the connection is closed. - Observing clients never time out.
Supported Commands
| Command |
|---|
OBSERVE GET |
OBSERVE ZRANGE |
Examples
# Terminal 1 - subscribe
127.0.0.1:7379> OBSERVE GET counter
1) "observe"
2) "fingerprint"
3) "218585a66813d005"
4) "result"
5) (nil)
# Terminal 2 - write a value
127.0.0.1:7379> SET counter 42
# Terminal 1 - receives push notification automatically
1) "observe"
2) "fingerprint"
3) "218585a66813d005"
4) "result"
5) "42"Cancelling a subscription
127.0.0.1:7379> UNOBSERVE 218585a66813d005
(integer) 1Notes
- Only readonly commands can be observed. Write commands cannot be passed to
OBSERVE. - The fingerprint is deterministic: the same command with the same arguments always produces the same fingerprint, so clients can pre-compute fingerprints to match incoming notifications.