Created a Unique Id Generator

Updated At 2024-10-13 13:44:46 by @iamgak

Laravel Technology Web Development

Something Similar to Twiiter's Snowflake UID Generator but with little changes which's good for my needs

Today, I created a UID Generator function for my online-clipboard application. Actually, I want a unique id for Redis / DB where i can store data like type of file(text, non-text), sever id, epoch time, some my random number, user_machine id.
function generateShortSnowflakeId($type, $epoch, $serverNumber){
   
$timestamp = (microtime(true) - $epoch) * 1000; 
    $randomBits = mt_rand(0, 4095); // Generate 12 random bits
    $id = (int)(($type << 44) | ((int)$timestamp << 12) | $serverNumber | $randomBits);
return custom_encoder($id);
} //by the way this generateShortSnowflakeId created by Haiku on request😅 
$type = 1; $epoch = 1609459200; $serverNumber = 1;
generateShortSnowflakeId($type, $epoch, $serverNumber);

So, i was remeber Alex Yu's Book (System Design Interview) where he said something how to create a unique id in which he said a lot of different ideas but for my this is most suitable one right now. 
The only issue it has earlier  is that it's too long i want shorter id. So, added a base 62 encoder Custom Encoder.
function custom_encoder($id){   
    $base62Chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $shortId = '';
  while ($id > 0) {
        $shortId = $base62Chars[$id % 62] . $shortId;
       $id = (int)($id / 62);
    }


return $shortId;
}
Now, I have to think Little bit customising Ratelimiter, adding few attribute in User Activity log to controll/limit no of read and write operations by users, storage of non-text data third party or same server and think about compression methods and parsing this data into my needs

 
 
 




Leave a Comment:




Comments: 0