Mike
Mike

Reputation: 7701

Are StackExchange.Redis fire-and-forget calls guaranteed to be delivered in order?

If I make multiple StackExchange.Redis calls from a single thread using fire-and-forget, are they guaranteed to be delivered in order?

Use case: I am adding an item to a Redis stream and then using pub/sub to trigger another service to process that stream. To avoid a race condition, I need to make sure that the item is added to the stream before the pub/sub message is delivered.

Upvotes: 0

Views: 234

Answers (1)

Efran Cobisi
Efran Cobisi

Reputation: 6454

While most StackExchange.Redis APIs are thread-safe, the order of delivery of commands sent through SE.Redis can't be guaranteed out-of-the-box in your scenario for several reasons:

  • your topology could have multiple nodes, where each message of your sequence is delivered to a different node for a change in the topology or according to your own preferences (CommandFlags.Prefer* / CommandFlags.Demand*);
  • your thread could host multiple tasks whose continuations do not respect the intended delivery order;
  • being fire-and-forget, a failure in the delivery of the first command would not stop sending the subsequent ones;

I need to make sure that the item is added to the stream before the pub/sub message is delivered.

I suggest using a Lua script to solve this, which would execute your commands within the same atomic unit and against the same node:

redis.call('XADD', 'foo', '*', 'bar', 'baz')
redis.call('PUBLISH', 'foo-added', '')

Upvotes: 1

Related Questions