8

I plan to use redis as an unique atomic id generator. However, my concern there might be simulatoneous web requests from multiple browsers. I was wondering, what is the common practice to make the following operations atomic?

get id from redis
if id is not found
    insert id as 0 into redis
else
    store the id in a variable
    increase id by one
    store the new id back to redis

If I were in desktop app or mobile app, I would use synchronized keyword in Java to avoid race condition.

However, how about for a PHP web app?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

1 Answers1

12

Assuming you're looking to generate sequential ids, you can use Redis and the INCR command without worrying about race conditions. Since Redis is (mostly) single threaded, you are assured that every request will get it's own unique id from it.

Furthermore, you don't need to check the id key's existence/initialize it because Redis will do that for you (i.e. if you INCR a non-existent key, it will be first created and set to 0 automatically).

Itamar Haber
  • 47,336
  • 7
  • 91
  • 117