12 ms·
Pg-shortkey: YouTube-Like Short IDs as Postgres Primary Keys
- karmakaze 6y agoWhy don't README's state how the main thing is done? CREATE EXTENSION IF NOT EXISTS "pgcrypto"; LOOP ... -- 8 bytes gives a collision p = .5 after 5.1 x 10^9 values gkey := encode(gen_random_bytes(8), 'base64'); gkey := replace(gkey, '/', '_'); -- url safe replacement gkey := replace(gkey, '+', '-'); -- url safe replacement key := rtrim(gkey, '='); -- cut off padding ... END LOOP
- tomcam 6y agoWell you just save me a ton of time. Thank you
- ben509 6y agoGenerally so you don't have to update the README every time you update the source.
- karmakaze 6y agoI wasn't suggesting that the actual code be in the README--that was laziness on my part--more in terms of what's used and expected output characteristics. I would specifically want to know if I was using a library with a certain implementation, changed how it did its main thing in a potentially meaningful way (e.g. dependencies, formulas, character set, output length, etc). A README is a good place to document these points.
- ben509 6y agoFair enough. If it's bugged you enough to think through what you're looking for in a README, that'd be a good post for HN.
- contravariant 6y agoWeird choice to pick 8 bytes then cut off the padding, you're effectively not using 2 bits in your last character that way. Might as well make it 12 characters instead of 11 and encode a full 9 bytes. Although seems like Youtube's done the same thing.
- irq-1 6y agothe '=' isn't url safe.
- nostoc 6y agoThat's not the point. encoding 9 bytes doesn't give any '=', because 3 bytes encode to 4 b64 characters.
- ignoramous 6y agoAFAIK: '=' is URI (path) safe [0] '=' is not query-param safe [1] Ex: [0] https://golang.org/pkg/net/url/#PathEscape https://golang.org/pkg/net/url/#PathEscape [1] https://golang.org/pkg/net/url/#QueryEscape https://golang.org/pkg/net/url/#QueryEscape
- gregmac 6y agoWell you do save a byte in the actual key. I guess if you really want to keep it to 11 bytes, it would be better to generate 9 bytes of random data, base64 it (which uses the full 12 characters, with no padding), and truncate to 11. You're throwing away 6 bits of random, but now all 88 bits in your 11-character key are useful (instead of only 86 bits).
- hankchinaski 6y agoi just started using ksuid[0] as my postgres (and in general) primary keys [0] https://github.com/segmentio/ksuid https://github.com/segmentio/ksuid
- c17r 6y agoJust came to say the same thing. While not 100% bulletproof as neither go nor pgsql internals are areas of experience, I’ve managed to cobble enough together so ksuid is a valid pgsql type with the ability to auto-create during a record insert.
- formerly_proven 6y agoInstead of doing random bytes, you can also just use a 64 or 128 bit permutation ("block cipher") on standard primary keys, which doesn't rip and tear your indices.
- pestaa 6y agoSo using random GUIDs is equally harmful to indices? And how so?
- larzang 6y agoPostgres stores records by primary id sequence. If you have completely random IDs, records inserted at the same time are fragmented across the entire set, which makes accessing them slower if they're meant to be sequential. Whether this matters entirely depends on the type of data you're storing. If you're storing unrelated data which is always random access anyway, non-sequential ids don't really matter. If you're storing related data which is mostly accessed sequentially, e.g. Impressions filtered by a creation date range, it's definitely better to have sequential ids for non-fragmented storage. UUIDv6 isn't as commonplace in libraries as v1 or v4 but offers a good compromise for this.
- kevincox 6y agoNote that this can actually be beneficial if you are sharding the table as now new inserts will be put on different shards. (Of course ideally you would be inserting sequentially but on different shards)
- wiredfool 6y agoNo, Mysql does. Postgres doesn't. (edit, at least, some common mysql table types do) (further edit -- You don't actually need a primary key in postgres. You might want one, and depending on how you do it, it's generally good design, but there's no actual requirement for them.)
- jeltz 6y agoNo, I do not think this is a good explanation. What you describe is how InnoDB works. PostgreSQL stores the actual records separately from the primary key index so the actual records won't fragment but the primary key index will. The records themselves will roughly be stored in insertion order. A random primary key in PostgreSQL mainly means that inserts into the primary key index will be more expensive and that it will bloat the primary key index to some extent.
- oauea 6y agoLooks similar to https://hashids.org/ https://hashids.org/ which instead uses a numerical seed to generate a String representation, which lets you use sequential IDs in your database.
- opmac 6y agoI was going to recommend this. No reason to use a special data type for the ID in your database unless you have some sort of actual constraints (like a 64 bit limit or something). Instead just use a sequential integer (or UUID). When you need to expose it publicly, use something like hashids ^. The main downside to straight UUIDs as primary key, is the B-tree used to store the primary key is larger if using UUIDs which are 16 bytes vs 8 for longs. In this case though the IDs are 8 bytes so this point is moot. Also the data is stored randomly on disk, which will make things like range queries slower if querying by ID (but you probably want a different index for querying anyway).
- philsnow 6y agoI briefly read about it, it says the method is similar to just converting numbers to hex (modulo + lookup in an 'alphabet', then shift, repeat until you are at zero), but with a shuffled alphabet. That doesn't sound secure _at all_ -- if an attacker can cause you to generate a bunch of IDs very quickly, it's likely that some of them will be sequential, and from there it should be easy to figure out what the shuffled alphabet was. Indeed, from hashids.org: > Do you have a question or comment that involves "security" and "hashids" in the same sentence? Don't use Hashids. and then they link to a blog post with a detailed analysis (which makes it look like their characterization as just converting a number to a shuffled alphabet doesn't capture all the details) demonstrating that it's weak.
- itake 6y agoWhy not use ints and encrypt them when returning them?
- kebman 6y agoI'm not an expert, but here's some conserns I'd have: Because the returned payload isn't necessarily uniform. Because you aren't guaranteed uniqueness (or that guarantee is mathematically lower). And because the overhead for doing it that way may be too high (we want to achieve it in a way that is computationally light, and most encryption isn't).
- antoinealb 6y agoI am not sure what your concern ab ou it uniqueness is: encrypti on has to be invertible, therefore if each non encrypted integer is unique, it means that each encrypted representation is also unique. w.r.t encryption cost, I think AES is very cheap on modern hardware compared to the cost of SQL or the overhead of writing your app in an interpreted language.
- holtalanm 6y ago> Because you aren't guaranteed uniqueness If your encrypted value is not unique, then your encryption algorithm is broken. You have to be able to turn the encrypted value back into the unencrypted value. if you have two unique unencrypted values that result in the same encrypted value, then that essentially makes it impossible to unencrypt.
- layoutIfNeeded 6y ago>Because the returned payload isn't necessarily uniform Wrong. Flipping a single plaintext bit flips all ciphertext bits with 50% probability. >Because you aren't guaranteed uniqueness Wrong. Encryption is bijective. >And because the overhead for doing it that way may be too high Wrong. Symmetric ciphers are extremely fast.
- tmpyt 6y agoThat's exactly what youtube originally did - video id is just an encrypted (3DES, iirc) 64-bit sequential primary key straight from mysql database. You can convert it back and forth. Problem: if you know the encryption key (it was sitting right there in the code for all devs to see, easy to steal) you could enumerate all the YT videos, including all unlisted videos. At least until a few years ago - they've since switched to random database keys instead of autoincrement to fix this exact hole. Source: worked there.
- StavrosK 6y agoI needed this a few (9, wow) years back and wrote this Python library: https://pypi.org/project/shortuuid/ https://pypi.org/project/shortuuid/
- abathur 6y agoglad you did! <3 me some shortuuid :)
- StavrosK 6y ago<3
- ivan_ah 6y agoI came here to post about this! Thx a lot for this. It works great. Today I'm working on a custom `ShortUUIDField` (a subclass of Django's UUIDField) so I can stick to standard building blocks internally, but show sortuuids to users.
- StavrosK 6y agoI've been thinking of adding that to ShortUUID, do you mind showing me when you're done (or issuing a PR)?
- ivan_ah 6y ago@StavrosK the code still very much WIP, but you can take a look at the links I posted on this issue: https://github.com/skorokithakis/shortuuid/issues/50 https://github.com/skorokithakis/shortuuid/issues/50 I'm making some choices very specific to my use case (truncated to length 7, and use of a prefix), so not directly PR-able, but can followup in January if you find this useful. (Going to have to figure out how to test with all Djangos and DB backends to be sure it works)
- oxfordmale 6y agoThis is a really bad idea as explained eloquently in this blog: https://tomharrisonjr.com/uuid-or-guid-as-primary-keys-be-careful-7b2aa3dcb439 https://tomharrisonjr.com/uuid-or-guid-as-primary-keys-be-ca...
- tgb 6y agoMaybe I just don't know enough about this field, but I didn't actually understand the objections in that post. They were either orthogonal to UUID use (don't store them as string, don't share them publicly) or seemed to not actually come to a conclusion. The "UUIDs are a pain" point makes sense as does the "Primary keys get around" section. But the section "Planning for real scale" seems to stop short of saying anything against UUIDs (it only talks about ints versus bigints?). The author even concludes (confusingly) with: > So, in reality, the right solution is probably: use UUIDs for keys, and don’t ever expose them. Can someone shed light on this?
- zerkten 6y ago>> So, in reality, the right solution is probably: use UUIDs for keys, and don’t ever expose them. > Can someone shed light on this? Some of the answers over at https://softwareengineering.stackexchange.com/questions/218306/why-not-expose-a-primary-key https://softwareengineering.stackexchange.com/questions/2183... cover the reasoning that I had been taught in the mid-nineties: it's an implementation detail and there are better choices to expose outside the database. When it comes to UUIDs, these often have a usability penalty when exposed to users. There may be something better to expose to users depending on the context, but not always. It's never an absolute. Since few people now start by building their database first with relatively rigorous modeling, it's hard to avoid the outside exposure. You should consider the situation though. In the early-2000s, there was a raft of web apps built in the .NET space that exposed GUIDs just because they were cool (I've literally heard them described as that), or devs didn't think about the implications. As with many ASP.NET abstractions at the time, these were problematic in the contexts used: Web Forms relied on POSTing everything and now your URLs weren't "hackable". Retrofitting UUIDs is possible if you are using other keys. If you are merging databases you can introduce these to get the data merged, as long as you are OK with some level of fix-ups to the original (integer?) primary key that you've exposed to the application. Ultimately, it becomes an application problem if you have collisions in the original IDs.
- 02020202 6y agothere is already this thing called bijective function
- chrismorgan 6y ago> -- 8 bytes gives a collision p = .5 after 5.1 x 10^9 values So yeah, a fifty-fifty chance of a collision after only five billion values. You’re at 10% chance before even two billion, and 1% after 609 million. I wouldn’t care to play this random game with even a million keys, the 64-bit key space is just not large enough to pick IDs at random. UUIDs are 128 bits; that’s large enough that you can reasonably assume in most fields that no collisions will occur. Storing a string is also inefficient, wasting more than three, and probably eight or more bytes (I’m not certain of the implementation details in PostgreSQL), growing index sizes and making comparisons slower. It’s more efficient to store it as a number and convert to and from the string form only when needed.
- lucb1e 6y ago> UUIDs are 128 bits; that’s large enough that you can reasonably assume in most fields that no collisions will occur. I'd go a step further than that honestly. Even at 80 bits I'd say you can really be sure that it will never happen. Mind that 2^64 is quite large, and with every single +1 of that power you halve the chance. Anything above 80 bits is quite safe even when someone purposefully tries to find your input, let alone by random chance. The 128 bits includes a decent security margin. Plain MD5 is pretty much the fastest thing you can find. A decent GPU can do 25GH/s on that. If you can have a $1 000 000 hardware budget, it takes you 150 years to have a 50/50 chance of cracking a 2^80 secret with Hashcat. (Ballpark numbers: can be off by an order of magnitude, but not <10 years for that budget if you use today's hardware and today's hashcat.) We haven't even cracked the 3DES key used for Adobe's user database backup, which I'm sure a lot of people would be interested in. Not $1M interested maybe, but still. 2^128 is really gigantic and no collision will ever occur there unless you have a quantum computer. It's more than a "reasonable assumption in most fields". Of course, I agree that 2^64 is too small to just generate a token and assume it's unique without checking if it exists. I'm just trying to prevent someone from assuming that we need 512-bit hashing or something and creating crypto soup (as a security dude, this happens all too often).
- nextaccountic 6y ago> Plain MD5 is pretty much the fastest thing you can find. Faster than BLAKE3?
- boogerlad 6y agoI built something better that's actually secure and performant here: https://github.com/boogerlad/crypt-ids/ https://github.com/boogerlad/crypt-ids/ The issues with this are 1) as more IDs are generated, the probability of collision increases 2) a non integer primary key is slow For a single database instance, it's far more performant to leave it as an autoincrementing integer and when it needs to be exposed, encrypt it in the backend before sending it out. Why not hashids.org? It's insecure: https://carnage.github.io/2015/08/cryptanalysis-of-hashids https://carnage.github.io/2015/08/cryptanalysis-of-hashids
- opmac 6y agoThe hashids documentation is pretty explicit about it not being secure. It says verbatim: > Do you have a question or comment that involves "security" and "hashids" in the same sentence? Don't use Hashids.
- boogerlad 6y agoIt only states that near the end of the page. What is the purpose of it if it's not secure? It only prevents an attacker from performing naive attacks (+1 to get the next id, for example), which might be good enough... But anyone really determined can crack this.
- formerly_proven 6y agoAh, I wish I would've known about format-preserving encryption when I did something similar a few years back! I ended up using IDEA, which (at the time) was still in most crypto libraries and has a 64 bit block size.
- CodesInChaos 6y agoFPE is complex and slow. I'd prefer a 64-bit blockcipher when it fits the application.
- jrochkind1 6y agoI've done something like this but not as the PK. Left the PK as an int or UUID, but added another column, with a trigger to auto-populate, that created a base-64 kind of thing. The trigger also detected colisions and tried again, up to 3 times before giving up and erroring. There's no rule that says what you expose to the public has to be the pk at all. It seemed to me a good idea for it to not be.
- forgotmypw17 6y agoYouTube ids are not human-friendly and undermine URL use. Not a great idea to copy all around, imo.
- yakshaving_jgt 6y agoWhat do you suggest otherwise?
- forgotmypw17 6y agoThere are many options... alphanumeric case insensitive numeric only keyword based above combined with date or topic just about anything is better than case sensitive mixed alphanumeric plus dashes and underscores, which is a challenge even to techies. Just imagine trying to tell someone a youtube id over voice
- yakshaving_jgt 6y agoAnd for each of those, how do you avoid risk of collision? A numeric only ID with the same risk of collision as a UUIDV4 would be 39 digits long, which is longer than a UUIDV4. So is there really a benefit? If it's keyword based, how long is the URI allowed to be? Given the need to support [probably well] over a billion records, I don't think your suggestions meet the design constraints.
- forgotmypw17 6y agoa) it's similar for avoiding collisions, and depends more on your hash algo than the display format. b) the benefit, as stated above, is human readability and shareability and typeinability and writedownability
- Dylan16807 6y agoCollisions are a separate issue from encoding. Since we're treating youtube IDs as acceptable, let's assume 64 bits is enough. It's 11 characters with this encoding. With something like Base32, designed so that you can read it out loud and ignore the case, it would take 13 characters. That sounds like a worthy trade-off to me. It's not visually much bigger, and saying it out loud or transcribing it is actually much faster because you don't have to specify case or squint to determine I/l/1 or O/0 etc.
- pcmaffey 6y agoI’ve always liked instagrams id_generator() for sortable bigints without an external point of failure. http://www.livinginthepast.org/2016/02/24/sharding-into-bigints.html http://www.livinginthepast.org/2016/02/24/sharding-into-bigi...
- jarym 6y agome too - and I Base64 encode it to make it human readable
- pcmaffey 6y agonot sure I understand the base 64 encoding: a bigint generated with this: 2457081803026990508 base64 encoded: MjQ1NzA4MTgwMzAyNjk5MDUwOA== why?
- fatsdomino001 6y agoSounds like they mean they're just hashid'ing the bigint id, likely stored in a separate slug column with the output
- jarym 6y agothe bigint is just 64 bits so I b64 encode the binary representation which is about half the size.
- wayneftw 6y agoThis is what Hashids was built for - https://hashids.org/ https://hashids.org/ > [A library] that generates short, unique, non-sequential ids from numbers. > It converts numbers like 347 into strings like “yr8”, or array of numbers like [27, 986] into “3kTMd”. > You can also decode those ids back. This is useful in bundling several parameters into one or simply using them as short UIDs. Of course, you shouldn't use this as a means of any real security. However, neither should you rely on hiding ids through randomness as security either. If someone gets their hands on an id that doesn't belong to them - they still should not be able to do anything with it. With that in mind, you'll get even better performance with a simple url-safe base64 scheme.
- R0b0t1 6y ago>However, neither should you rely on hiding ids through randomness as security either. Right, this whole discussion is kind of confusing to me. I get the allure of "unlisted" without needing to log in but for public videos what is the benefit to keeping people from enumerating them?
- tmpyt 6y agoOn youtube, uploaders can switch their videos to be public/private/unlisted anytime, you can't rely on this status to be set in stone at upload.
- jrochkind1 6y agoIt would be good to put the width (total number of possible keys) in the README. And what does it do for collisions, does it detect/recover?
- minxomat 6y agoIt will keep generating keys until a non-colliding key is found. Birthday problem collision rates are explained in the code's comments.
- hardwaresofton 6y agoA couple resources with rigorous examination of UUIDs and the tradeoffs involved with using them: - https://www.2ndquadrant.com/en/blog/sequential-uuid-generators/ https://www.2ndquadrant.com/en/blog/sequential-uuid-generato... - https://github.com/uuidjs/uuid/issues/303 https://github.com/uuidjs/uuid/issues/303 (also mentioned: https://gist.github.com/1ma/c837e6f30c0869cfc1222f67ac8b1c52 https://gist.github.com/1ma/c837e6f30c0869cfc1222f67ac8b1c52) I personally use v1 UUIDs as my main identifier and just take the performance hit. ksuids look interesting but don't think there's any need to use that when v1 uuids are good enough.
- tehlike 6y agoyou can use application generated sequential ids.
- gokhan 6y agoAnyone looking for a c# implementation of Comb guid can check NHibernate codebase. https://github.com/nhibernate/nhibernate-core/blob/master/src/NHibernate/Id/GuidCombGenerator.cs https://github.com/nhibernate/nhibernate-core/blob/master/sr...
- tehlike 6y agoFound this post I wrote on this topic: https://nhibernate.info/blog/2009/03/19/nhibernate-poid-generators-revealed.html https://nhibernate.info/blog/2009/03/19/nhibernate-poid-gene...
- gokhan 6y agoNice. One note for anyone going for this on Postgres, ordering is different so requires a different generator. There's a nuget package for that but i can't remember the name right now. Edit: Found it https://www.nuget.org/packages/RT.Comb/ https://www.nuget.org/packages/RT.Comb/
- tehlike 6y agoCheck my post from 10 years ago https://nhibernate.info/blog/2009/03/19/nhibernate-poid-generators-revealed.html https://nhibernate.info/blog/2009/03/19/nhibernate-poid-gene... I put data about fragmentation when using uuid there.
- fatsdomino001 6y agoI've been using ULID as an alternative to UUIDs, e.g.: https://github.com/ulid/spec https://github.com/ulid/spec I've found ULID to be great for my purposes. Wonder if anyone else has tried using them too?
- stickfigure 6y agoWhy is this better than picking an appropriate number of random characters from [A-Za-z0-9]? The base64 encoding seems weird and unnecessary. Plus you get dashes and underscores which can screw up copypaste.
- minxomat 6y agoI wrote this specifically to match youtube's format (see my other comment in this thread).
- stickfigure 6y agoSo... add dash and underscore to your character set? The contortions seem pointless.
- Dylan16807 6y agoYou need to make sure the last character only has 16 possibilities so that it can round-trip to a 64 bit int. But once you're embedding two lists of characters you might as well just do base64 then a punctuation swap to be simpler and easier to understand.
- deleted 6y ago[deleted]
- rekwah 6y agoAdditional approaches in this space: * https://hashids.org/ https://hashids.org/ * https://github.com/ulid/spec https://github.com/ulid/spec
- astatine 6y agoI use nanoid (1) and the length control it gives makes it easy to generate appropriate visible ids. Simple, fast, small and works well. (1) https://github.com/ai/nanoid https://github.com/ai/nanoid
- tehlike 6y agoI came to the conclusion that IDs should be application-assisted, if not application generated. Offloading that to DB brings some unnecessary work that needs to be handled on the application side otherwise, and tends to o be bad for performance. What do i mean by application generated? 1. UUID -> Bad for index, but for some use cases it's ok. 2. Sequential UUID -> Good with index, works most of the time. 3. HiLo (a server gets a chunk of id range from database, and assign that to entities on their own). This allows for more performant applications especially if you are designing somewhat complex data model.
- tehlike 6y agoSee this post for my reasoning: https://nhibernate.info/blog/2009/03/19/nhibernate-poid-generators-revealed.html https://nhibernate.info/blog/2009/03/19/nhibernate-poid-gene...
- foobarbazetc 6y agoNah. Just skip to a Snowflake-like ID generator from the beginning, or encrypt/decrypt your auto incrementing bigserial for external purposes.
- minxomat 6y agoHello, creator here. This is (I hope obviously) just a short snippet you can and should use as a starting point to hack on. For smaller data sets, this is perfectly fine, but if you're at the point where you need this, you will certainly have business-specific requirements that I don't really want to bake into this from the beginning. Here's my use case: I wrote this because I was (and am) working on a music streaming service, and I needed a youtube-like shortkey for public links to artists, albums etc. For my scale (~10,000 artists, ~120,000 tracks), I haven't run into any problems.
- sundbry 6y agoIf you do this in your application code, you can just store it as a 64 bit integer in postgres and optimize your index significantly, instead of using a varchar as the backing data type. These ids pack just right into 64 bits.
- hultner 6y agoCould it be backed by a 64bit integer while still exposing it as a well formatted code without relying on application layer intervention.
- aartav 6y agoCurious as to why not simply use UUIDs instead? Its extremely easy to use uuids as the primary key; make the column a `uuid` type and the `uuid-ossp` extension will generate them. Your sql would look like: CREATE TABLE posts ( post_id uuid DEFAULT uuid_generate_v4(), PRIMARY_KEY(post_id) );
- muminoff 6y agoIf you use Postgresql 13 version you don't need to install `uuid-ossp` extension. There's already built-in function to generate UUID which is `gen_random_uuid ()`.
- maxcan 6y agoI'd guess the idea would be to have more succinct URLs. As to whether or not primary keys should even ever be exposed in URLs, different story.
- markandrewj 6y agoA pattern you see often is people combining a human readable slug with an ID tacked on. This gives you a more readable slug and an easy way to reference the entry. https://wellfire.co/learn/fast-and-beautiful-urls-with-django/ https://wellfire.co/learn/fast-and-beautiful-urls-with-djang...
- foodstances 6y agoSomething to be considered when assigning random-letter IDs to public things: the random combination of letters can include offensive words in them. You should keep a ban list of words in your application and check your assigned ID against the list each time you get an ID.
- koolba 6y agoBetter to just exclude vowels and numbers that look like vowels.
- hamandcheese 6y agofckr.
- jaquers 6y agoThat's part of the fun
- sradman 6y agoThere are many ways to skin a cat. Some considerations: 1. Random value vs. string Hash (e.g. git SHA-1) 2. If Hash, string(s) and/or Salt used for the Hash 3. Fixed Length Key vs. Variable Length URLs/IDs 4. DB Storage: INTEGER, CHAR, VARCHAR, BINARY, VARBINARY 5. Scope of the Single Source of Truth for collisions (e.g. single PostgreSQL instance scoped by its WAL or globally unique ID generating service backed by Cloud Spanner and TrueTime)
- bob1029 6y agoI find that 64 bit integers are by far the best key material. The only compelling argument I've ever seen for using GUIDs vs int is horizontal scalability, but you can usually get around this with some math tricks. The best option in general is probably to divide the key space across some constant number that is higher than the most nodes you will ever need to add to the cluster. That said, pre-allocating numeric ranges in anticipation of future growth could introduce some concerns WRT cardinality. If every insert into a single node cluster consumes a bunch of primary key candidates (which are reserved for future nodes), you may worry that 64 bits is not enough range. This is something that has bothered me enough to try to find some options. If you use C#, there is a type called BigInteger which can be very conveniently converted to and from byte arrays. This type can handle an infinite range of integers, so is an excellent fit for this problem domain. All you need to do is define a BLOB instead of an INTEGER for your PK column and it should compare these using memcmp, providing similar semantics to an integer key. Granted, the performance is not going to be as good during lookups with this approach, but it probably wont be noticeable in most applications without some targeted profiling. Generally, I find primary keys based on entropy games to be questionable at best. I don't want to spend a lot of time worrying if I have enough bits in my hash functions to cover my ass. Deterministic, sequential integers are much more confidence inspiring if we are talking about the fundamental uniqueness of a thing. If you are worried about security (i.e. someone hitting sequential keys in your URLs), then this is arguably an application problem. You should probably generate an additional column that stores some more obfuscated representation of the primary key and index it separately. This has the added benefit of being decoupled from the primary keyspace and is easily adjustable in the future. The consequence of a collision between public video id surrogate keys is probably much less dire than the collision between actual primary keys in the backend representing those videos.