mediagone / small-uid
Small Unique Identifier - Quite like an ULID, but half smaller (64 bits).
Requires
- php-64bit: ^7.4|^8.0
- ext-gmp: *
- mediagone/types-common: ^0.5.1|^0.6
Requires (Dev)
- phpunit/phpunit: ^9.0
README
⚠️ This project is in experimental phase, the API may may be subject to change.
UUIDs are frequently used as database Primary Key in software development. However, they aren't the best choice mainly due to their random sorting and the resulting fragmentation in databases indexes.
Using ULIDs is generally a very good alternative, solving most of UUID flaws.
Small UIDs are also an ideal alternative when you do not need as much uniqueness and want shorter "user-friendly" encoded strings.
Introduction
Small UIDs are short unique identifiers especially designed to be used as efficient database Primary Key:
- Half smaller than UUID / ULID (64-bit)
- Lexicographically sortable
- Encodable as a short user-friendly and URL-safe base-62 string (
a-zA-Z0-9
) - User-friendly strings are generated in a way to be always very different (no shared prefix due to similar timestamps)
* theorical number of generated uids before the first expected collision.
** the uid includes a timestamp, so collisions may occur only during the same millisecond.
*** monotonic sort order, but random order when generated at the same millisecond.
They are internally stored as 64-bit integers (44-bit timestamp followed by 20 random bits):
|-----------------------| |------------|
Timestamp Randomness
44 bits 20 bits
The random number suffix still guarantees a decent amount of uniqueness when many ids are created in the same millisecond (up to 1,048,576 different values) and you may only expect collision if you're generating more than 1024 random ids during the same millisecond.
Sorting
Because of the sequential timestamp, Small UIDs are naturally sorted chronologically. It improves indexing when inserting values in databases, new ids being appended to the end of the table without reshuffling existing data (read more in this article).
However, sort order within the same millisecond is not guaranteed because of the random bits suffix.
Installation
This package requires PHP (64-bit) 7.4+ and GMP extension.
Add it as Composer dependency:
$ composer require mediagone/small-uid
If you're using Doctrine ORM, you'll probably want to install also appropriate custom types:
$ composer require mediagone/small-uid-doctrine
Examples of usage
Generating Small UIDs
$uid = SmallUid::random(); // from a given base-62 string $uid = SmallUid::fromString('1GUDp752fwX');
Converting Small UIDs
(string)$uid; // string(11) "1GUDp752fwX"
License
Small UID is licensed under MIT license. See LICENSE file.