Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis as unique atomic id generator - Thread safe way for web app to avoid race condition

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?

like image 511
Cheok Yan Cheng Avatar asked Jun 04 '14 02:06

Cheok Yan Cheng


1 Answers

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).

like image 50
Itamar Haber Avatar answered Oct 14 '22 08:10

Itamar Haber