Welcome to Abdul Malik Ikhsan's Blog

Using igorw/retry to handle collision of Uuid

Posted in Tutorial PHP by samsonasik on December 31, 2014

While the Uuid collide probability is almost zero, and only happen when you have a very very very bad luck, there is always a chance for it. If you’re using PHP, I encourage to use igorw/retry! You can retry your process as many as your wish!
Let’s grab it by adding into composer require :

composer require "igorw/retry:dev-master"

And as demo, I’m going to use “rhumsaa/uuid”, we can add again in composer require :

composer require "rhumsaa/uuid:~2.8"

Great!, let's use it :

require 'vendor/autoload.php';

use function igorw\retry;
use Rhumsaa\Uuid\Uuid;

$uuid    = Uuid::uuid4();
$uuidStr = $uuid->toString();

Now, the Uuid instance and its string random generation created, so we can use it in retry.

$i = 0;
// retry maximum : 5 times until succeed
retry(5, function () use ($uuid, $uuidStr, &$i) {

    $i++;

    if ($i > 1) {
        $uuidStr = $uuid->toString();
    }

    // this is pseudo code
    $this->db('user')->insert([
        'id' => $uuidStr,
        'name' => 'foo'
    ]);
});

When your insertion failed and got exception, it will silently ( doesn’t show error message ) and do re-try again with new string generation instead and stop when it succeded. You can change how many retry by changing 1st parameter in retry function.

References :

  1. http://en.wikipedia.org/wiki/Universally_unique_identifier
  2. https://github.com/igorw/retry
  3. https://github.com/ramsey/uuid

2 Responses

Subscribe to comments with RSS.

  1. Hari K T said, on February 13, 2015 at 2:05 pm

    Hey,

    Nice post. Good practical usage of retry . One question I have is why do you need the $i, and $uuidStr to be passed ? It seems we can do like


    use function igorw\retry;
    use Rhumsaa\Uuid\Uuid;

    $uuid = Uuid::uuid4();
    retry(5, function () use ($uuid) {
    $uuidStr = $uuid->toString();

    $this->db('user')->insert([
    'id' => $uuidStr,
    'name' => 'foo'
    ]);
    });

    • samsonasik said, on February 13, 2015 at 3:01 pm

      yes, that’s to make sure it works with initialize $uuidStr.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: