1
votes

I've already read multiple articles about redis transactions. I have some lists that contains messages. And I use redis to generate auto-increment IDs for those messages. Here's what I'm trying to do:

  1. Read the counter value, then INCR it.
  2. Put the incremented counter value in the Id field of the message, then serialize the message.
  3. Push the serialized message into the list.

So the counter always holds the last message's ID in the corresponding list. I want to put a lock on the counter key so other requests cannot read and INCR the counter and push another message to the list that conflicts with the last ID.

Since I want to have a limited number of redis clients, WATCH MULTI EXCEC cannot be implemented, because it's the same client doing the transaction. And as far as I know WATCH MULTI EXCEC is for when you have multiple redis clients.

I want to know what is the correct approach for this problem. Should I use LUA scripts and let it serialize the message?

1

1 Answers

2
votes

Lua is definitely the best option for creating an atomic logic unit that both reads and writes data.

In your case, however, I am not convinced that atomicity is really needed. Unless there is a strict requirement that the IDs have no gaps between them, you can just call INCRBY to obtain a new ID and then use it in serializing the message. Other messages will not get the same ID and the only "risk" is having your worker die before using that ID to serialize and store the message (hence creating a gap).