Redis XCLAIM in PHP (Detailed Guide w/ Code Examples)

Use Case(s)

The XCLAIM command in Redis is used for stream processing. It's commonly used in situations where you need to change the ownership of pending messages in a consumer group. It can be useful in scenarios where a message was delivered to a consumer, but it didn't acknowledge the message within a certain time frame.

Code Examples

To use XCLAIM with PHP, you'd typically use a library like Predis. Below are two examples demonstrating how you might use it.

  1. Claiming a message in a stream:
<?php require 'vendor/autoload.php'; $client = new Predis\Client(); $stream = 'mystream'; $group = 'mygroup'; $consumer = 'myconsumer'; // Claiming a message from a stream that was not acknowledged by another consumer $messageId = '1578666958136-0'; // this would be obtained from previous XREADGROUP or XPENDING commands $client->xclaim($stream, $group, $consumer, 5000, array($messageId)); ?>

In this example, we're claiming a message that has been idle for at least 5000 milliseconds (5 seconds). The id of the message ($messageId) would have been retrieved previously using the XREADGROUP or XPENDING commands.

  1. Claiming a message and changing its value in the stream:
<?php require 'vendor/autoload.php'; $client = new Predis\Client(); $stream = 'mystream'; $group = 'mygroup'; $consumer = 'myconsumer'; $messageId = '1578666958136-0'; // this would be obtained from previous XREADGROUP or XPENDING commands $client->xclaim($stream, $group, $consumer, 5000, array($messageId), 'JUSTID', false, ['Hello' => 'World']); ?>

In this example, not only are we claiming the message, but we're also updating its value in the stream to ['Hello' => 'World'].

Best Practices

When using XCLAIM, it's important to consider how long a message should remain unacknowledged before another consumer can claim it. This will depend on your use case, but it's generally best to allow enough time for a consumer to process a message before it becomes available to others.

Common Mistakes

One common mistake when using XCLAIM is not properly handling failures. If a consumer fails to acknowledge a message, it'll become available to others after the idle time you've specified. You should ensure your application can handle these situations gracefully.


Q: What does the JUSTID option do in XCLAIM? A: When JUSTID is set to true, XCLAIM only returns the ids of the claimed messages, instead of the full messages themselves.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.