12 ms·
Database IDs Have No Place in URIs (2008)
- adrianmsmith 8y agoAlso, using a numerical auto-incrementing ID in the URL will expose how many users you have so far. Not a problem for Stack Overflow, but I’ve had clients (startups) who wanted to put IDs in the URL, when you sign up and your URL is /profile/432 it’s quite clear the product doesn’t have many users.
- adjkant 8y agoAn easy solution to that is simply not to start at zero/one and pick a random number somewhere around 5-6 digits. Can do that at the database level or programatically.
- jstanley 8y agoIt's still easy for anyone to work out how fast you're gaining users. Just sign up for an account every day and note how much higher the new id is.
- thecatspaw 8y agoyou can also add zeroes (or other digits which get stripped before used for querying) at the end, that way the gain looks orders of magnitudes faster
- jstanley 8y agoSure, but anyone signing up for 3 accounts in quick succession can probably figure out what you're doing. All of these problems go away if you just assign random numbers instead.
- TeMPOraL 8y agoWhy would honest people want to spend time implementing ways to lie to their users? Because that's what we're talking about here. (And I know I'm asking a rhetorical question.)
- jstanley 8y agoAssigning random ids isn't lying to your users, unless you also make representations that the user id corresponds to the number of users that there are.
- verbify 8y agoWhile there might be some edge cases (e.g. startups associated with a high profile brand/person), in most cases there are usually better things for a startup to do than obfuscate the number of users they're gaining.
- treve 8y agoA slightly more advanced version of this to XOR the number with some other number.
- codetrotter 8y agoSimply doing XOR on two integers doesn’t really provide meaningful obfuscation if one of the inputs are constant as I assume they would be in this case. For example: for i in range(25): 167535774 ^ i 167535774 167535775 167535772 167535773 167535770 167535771 167535768 167535769 167535766 167535767 167535764 167535765 167535762 167535763 167535760 167535761 167535758 167535759 167535756 167535757 167535754 167535755 167535752 167535753 167535750 for i in range(250000,250025): 167535774 ^ i 167752718 167752719 167752716 167752717 167752714 167752715 167752712 167752713 167752710 167752711 167752708 167752709 167752706 167752707 167752704 167752705 167752766 167752767 167752764 167752765 167752762 167752763 167752760 167752761 167752758
- eli 8y agoAt that point your requirements seem to require a number with no pattern, so it should probably just be a random unique number or string. But for a lot of use cases the ability to measure growth or enumerate URLs doesn't matter.
- petepete 8y agoALTER SEQUENCE users_id_seq RESTART WITH 54321; "Wow, this service is probably mature, well-tested and reliable!"
- zepolen 8y agoAmateur - you have to do over 1 million or you're not web scale.
- lifthrasiir 8y agoNote that there is a legitimate reason to set the initial sequence in this way: oftentimes the system works fine with 31/32-bit numbers but not with larger ones. Starting with the large sequence number (we have frequently used 10 billion) proactively eliminates this problem.
- koolba 8y agoAnd then come back a week later to see that 500001 => 500004...
- TeMPOraL 8y agoThe number of users who notice the user ID is a small fraction of your total users. The number of users who would notice the ID didn't grow much over the week is a small fraction of that fraction.
- zAy0LfpBZLC8mAC 8y agoNamely, cour competition that tries to figure out what to do about you or whether to even care, yes.
- dexterdog 8y agoExactly. I have done this in research on competition many times.
- deleted 8y ago[deleted]
- ponytech 8y agoThis is why I always obfuscate IDs using Hashids: https://hashids.org https://hashids.org
- zepolen 8y agoHashids are slow though
- branko_d 8y agoJust use GUIDs instead. And if you want to keep using integer IDs internally, put the GUIDs into an alternate key.
- varelaz 8y agoGUIDs are really unreadable and long. You can read and remember some numeric ID, but GUID/UUIDs – totally impossible. I hated them after Microsoft COM.
- joshstrange 8y agoI'm not sure I need "readable and short" to be qualities of my unique identifiers. I copy/paste and UUID/GUID I come across and if you have foreign keys setup you can jump around the DB in most GUI clients with ease, never even having to copy/paste. Furthermore when I'm talking with my coworkers we always just read off the 2nd "set" of numbers/letters in the UUID. In the example of `c495d443-cc7d-4030-840c-8f7e4e0289c3` I will just say "cc7d", 99.9% of the time that is enough to uniquely identify a UUID when we are only dealing with a handful of them and want to pick one out by eye quickly. For anything else I just send them a chat with the UUID and they can query on it, grep, or find it in the results with Ctrl+F or whatever their tools support doing.
- thecatspaw 8y agoThe issue I see with searching by slugs is thats its slower than searching by integer, and its more likely to be entered incorrectly by users when typing a url. You also can not change the slugging algorithm if you want to keep bookmarks valid
- adrianmsmith 8y agoI don’t agree it’s slower in a practical sense. If your service is backed by a relational database like PostgreSQL then you’d have an index on the column you’re looking up. So a request involves network round-trip latency, parsing the request and preparing the response, and searching for the object in the database using the index, most likely a tree with a depth of 3 or 4 levels. I don’t think the number of characters in the key, or the data type, will play a big role here. Happy to see evidence to the contrary though if I’m wrong! The algorithm flexibility might not be a big problem either. The old slugs are stored in the database. Update the algorithm, new slugs adhere to the new algorithm, old ones unchanged, everything still works.
- lxn 8y ago1) Indexing text vs indexing integer it's very different when it comes to memory/space required by the database. 2) There is already an index on ids assuming they are used as primary keys, why adding another index (on text)? 3) To support changing slugs (titles) you will have to keep all the old slugs as well (to redirect them to their new versions). With ids you don't have to do this - ids have no reason to change. In the end you might not feel the difference in execution time, but hardware requirements for servers... I agree that they are annoying, but when the only reason against them is to improve URLs aesthetics (assuming they don't pose a security/information disclosure risk) - the trade of performance, hardware requirements and extra code needed is not worth it IMHO.
- thecatspaw 8y ago> 3) To support changing slugs (titles) you will have to keep all the old slugs as well (to redirect them to their new versions). With ids you don't have to do this - ids have no reason to change. Which basically means a join in the database. While not terribly expensive, its a lot more involved than a simple column value check.
- kozak 8y agoThat can be either good or bad depending on situation. There are plenty of cases where concise sequential identifiers are an advantage.
- dexen 8y ago>where concise sequential identifiers are an advantage For example, certain kinds of attacks are helped with sequential IDs. Wasn't there an AT&T "hack" where the attackers iterated URLs over sequential account numbers to grab nearly all data? Would've been nigh impossible to perform with UUIDs as identifiers. About the only use case I can think of where sequential IDs are helpful is using MAX(PRIMARY KEY) to roughly estimate total number of records. And that's only relevant where there's special cased support for MAX(PRIMARY KEY). Think MySQL, but not PostgreSQL. And that's also subject to the over-estimation due to holes left in the sequence, whether due to deleted records, or backed off transactions.
- branko_d 8y agoSequential integer IDs have some advantages over GUIDs at the database level. Integers are smaller (and cache friendlier!), while sequential values generally improve the fill factor of B-Trees (the DBMS can special-case the insertions that match the B-Tree key order, e.g. Oracle does a 90/10 index block split). On the other hand, they can cause latch contention on INSERT-heavy tables (because of the competition for the last B-Tree leaf), though this is not common.
- dexen 8y agoYou raise valid points, but there's a hidden cost: if you decide to use slugs for URLs, or any identifier other than the Primary Key, you need to perform one extra step of mapping. Either one extra round-trip to the DB, or one extra join, or condition on a non-PK field, with, presumably, the extra index, that in turn needs to be maintained. Not the worst thing to happen, but at any serious scale you take that into account. OTOH, storage for binary UUID representation is just 16 bytes. You get non-sequential big big ints. Possibly use UUID v1, with sequential (time based) trailing part.
- pointe 8y agoYou should not expose any internal identifier (numeric or otherwise) because it then becomes public & part of your API (even if undocumented).
- ilikehurdles 8y agoIn one case the api I worked on used encrypted IDs on the way out to the client, and decrypted them on the way back to the db. Even when multiple clients referred to the same resource, they would see different public IDs, but any instance of the API could reach the underlying value from those public values.
- Jwarder 8y agoOne idea I like is to have a normal internal database ID, but also have a public UUID column to use for URLs, APIs and that sort of thing. This way you can change the record's UUID at any time to display different data without having to worry about updating a bunch of internal foreign keys. You don't have to worry about a user making easy edits to the UUID in the URL to find nearby records (although you still need real protections if you need to restrict data by user).
- mgamache 8y agoI've used that in the past to retrofit an old database and move away from the id=123 in a URL to a UUID. You can keep all the old relationships triggers ect... Just add an index for the new col... UUIDs are not perfect but for most applications they are good enough (I think)
- yrro 8y agoThere was a story posted recently about how the properties of UUIDs are not a good match for how databases index columns. It proposed the 'ulid' which helps in that regard.
- geezerjay 8y agoThank you for mentioning ulid. Very interesting,and perhaps also useful.
- mywittyname 8y agoI'm curious about this if you remember the reference. My gut reaction is UUID is better because the keys would be more uniformly distributed across the key-space. With sequential IDs, a binary tree would end up always being unbalanced -- though, this effect would be reduced as the database gets larger.
- int_19h 8y agoI recall seeing UUID generators that are specifically tuned for use as keys in databases that specifically support them as primary keys. E.g. this has been around for a while: https://docs.microsoft.com/en-us/sql/t-sql/functions/newsequentialid-transact-sql https://docs.microsoft.com/en-us/sql/t-sql/functions/newsequ...
- GauntletWizard 8y agoThis guy sounds like he has bad backups and bad database management. Nothing more. That "database ID" is probably an auto-incrementing primary key, and yes, moving it to another box, restoring from backups, and even migration to another server type should keep the same ID. If not, you've done it wrong. In none of those situations will new entries necessarily follow the same pattern, i.e. there may be huge gaps or it might start filling in deleted questions so entries are "out of order", but those are separate problems and also remedied by using your schema correctly. In short: this post is very misinformed and I hope that it's presented for that purpose and not taken as serious advice.
- aiCeivi9 8y ago> this post is very misinformed. This. The answer to 3 question in article is always "YES". > The slug itself can easily be automatically generated when a new question is saved. Then you can simply retrieve a question by its slug. And that was just pure ignorance. What happens to slug when question(or product) is edited?
- slig 8y agoFor a content website such as SO, the biggest advantage of using /<id>/<slug>/ is being able to update the `slug` whenever the `title` of your content changes, and then it's very easy do a 301 redirect and you're good to go.
- dqybh 8y agoIf you're afraid of Google bombing, the redirect is not even necessary, just make sure the <link rel=canonical> tag contains the correct URL.
- dusted 8y agoWhen talking about public pieces of information, being able to refer to them by their identity is useful and any hashing would be counterproductive (just wasting power), also, I'm sure any database can operate on unique, incrementing numbers more quickly than uuids. If we're talking about private information, it should be transferred in another way than the url in the first place, yes, the chance of "guessing" a hash is lower than an incrementing number, but there are other ways it could be intercepted, a screenshot, accidential copy/paste for example.
- benkuhn 8y agoThis argument seems backwards. As far as I know, no database has ever had any of the problems he mentions with IDs not round-tripping properly during backup/restore. (Please correct me if I'm wrong! But why do I think this is true? Because any database that doesn't roundtrip primary keys would break all foreign keys on backup/restore. Databases with broken backup/restore tend to either fix it real fast, or go away.) On the contrary, it's much easier to keep IDs stable over time, than any other field. The problem with using a different field as an identifier (e.g. a URL component) is that almost any property with an objective meaning, might change over time or become non-unique. This is why it's a best practice not to use, e.g., user email as a primary key. For instance, Stack Overflow allows users to edit the title of a post. Right now when that happens, the canonical URL changes (to include the new slug), but the old URL is easily 301'd to the new one because it includes the ID. If the numeric ID was not in the URL, you'd be stuck with either a misleading slug, or having to maintain a list of former slugs/redirects for each post. Plus, you'd have to hack your slug-generation algorithm to ensure the generated slugs to be unique, and the easiest way to do that is... by appending an incrementing ID to the end of the slug. The point about avoiding cruft like .aspx in URLs is well taken, but unfortunately it's in direct tension with the point about keeping them stable given that "meaningful" non-cruft tends to change over time! (And if you don't want someone to guess your metrics from IDs, you can use a random non-numeric ID instead!)
- dexen 8y ago>As far as I know, no database has ever had any of the problems he mentions with IDs not round-tripping properly during backup/restore. Don't know of any such either. Typical SQLite, MySQL, or PostgerSQL dump/backup is just bunch of SQL statements that re-create the content, including PKs. You can imagine a non-native (perhaps DB-agnostic?) DB dump format that would use generated IDs for PK, rather than actual PKs. Why would one do that, I don't know. Another possible case is using file (or memory) offset as the PK. This gives certain nice properties - one less indirection level, and object identity being pointer identity. Perhaps there's a memory image-based LISP version out there that uses such. Perhaps there's a NoSQL engine like that somewhere. >Plus, you'd have to hack your slug-generation algorithm to ensure the generated slugs to be unique ...or you put the moderators to the task of ruthlessly stamping out duplicate questions. There was a popular website like that, oh wait, that's the Stack Overflow ;-) [edit] I've just remembered that PostgreSQL's ctid and SQLite's ROWID are physical identifiers (offset-like identifiers) of records. They are (to certain extent) exposed to userspace and could be misused as IDs in URLs. As physical identifiers (offset-like), they are naturally subject to change upon dump/restore, vacuum, other maintenance tasks, etc.. Clearly those should not be used as end-user visible IDs in URLs.
- fjni 8y agoGenuine question: What's the proposal for items in an API which have no concept of a "slug"? We could generate a separate mapping of "public ids" to the database internal ones, but I don't even see how that would solve any of the issues here.
- theoh 8y agoI'm not a database expert, but concepts like surrogate and natural keys come to mind. A unique slug is a natural key, but for most, if not all, items, you can come up with a natural key by combining a few bits of data (I've seen name * date of birth used by doctors in general practice, for example). Often there's a pre-existing unique code external to the app which can be used, like a driver's licence number or something like that. That removes the need for a surrogate key in the database. The tricky case is something like email drafts: it's possible for a user to create and then save a draft with no addressee, subject or content. In that case there is little alternative but to make the system use a surrogate key (a database internal key) because the other possible unique identifying values (e.g. time of creation of the draft) are sort of unsatisfactory, because they don't really have a strong, meaningful connection with the content of the item.
- trpc 8y agoI like the way medium.com deals with IDs, 10 random hex chars (i.e. > 10^12) put at the end of the slug are more than enough for most use cases that can be addressed via a url and still clean for search engines and humans. But also the way letterboxd and also quora deal with URLs is admirable but it needs special care (at least in the case of quora)
- localhostdotdev 8y agopretty cool how the urls stayed the same: http://stackoverflow.com/questions/13204/why-doesnt-my-cron-job-work-properly http://stackoverflow.com/questions/13204/why-doesnt-my-cron-... (still works) http://stackoverflow.com/questions/21064/massive-reputation-jump http://stackoverflow.com/questions/21064/massive-reputation-... ("this question was removed from stack overflow for reasons of moderation", still available: https://i.imgur.com/Csy94IL.png https://i.imgur.com/Csy94IL.png)
- jayrwren 8y agoPretty sure the last 10yrs of stackoverflow proves that this is not a concern. I'd file this under: things to not worry about.
- geezerjay 8y agoSequential numeric ids leak information regarding your operations. https://en.m.wikipedia.org/wiki/German_tank_problem https://en.m.wikipedia.org/wiki/German_tank_problem
- wutman 8y agoThis is exactly right, but in my opinion usually not important. If Joe Public, or a competitor, or whoever knows how many posts you have, users you have, administrators you have, etc how much does that actually affect your operation? I guess they can better compete against you in some small way with that information, but in my opinion it's almost never worth the effort to obfuscate. It's like optimizing for a problem you don't have.
- geezerjay 8y ago> how much does that actually affect your operation? If it's a business service then the operation is not the end goal but the means to the end. If it's a business service then the question you should be asking is "should I care that my competitors are able to observe and monitor my service metrics?". Quite often, businesses do care a lot.
- coldtea 8y ago>of Atwood's calibre What was Atwood's calibre at that point? (pre StackOverflow)
- boobsbr 8y agoCoding Horror began in 2004, that's where I knew him from.
- fabian2k 8y agoThat article seems to immediately contradict itself by saying that the most important aspect of URIs is that they never change, and then suggests using the slug derived from the title as unique identifier. Titles change all the time on Stack Overflow, this would immediately break URLs.
- bazzargh 8y agoThe title and slug are related but not tied together. It's quite common to visit slug-based sites and find the slug is a relic of the original title. In addition, slugs have to be unique when used this way, but titles don't. eg a title of Database IDs Have No Place in URIs (2008) may appear again next year, but the url would need to point to a different conversation; your CMS would suggest or generate the slug based on the original title.
- eli 8y agoThe title of a news article sometimes changes because of new reporting that makes the original title inaccurate. Leaving the old title as the slug could cause confusion. Think about a breaking news event where details are very sketchy at first but the article is updated as more becomes known.
- ricardobeat 8y agoAnd then the question gets updated and you either have a broken URI, or a slug that doesn’t match the content. I’ve never heard of IDs being something mutable. When would that ever happen?
- btbuildem 8y agoOne reason would be that the slugs are not guaranteed to be unique - they're based on user-entered post titles.
- geophile 8y agoI don't get this argument at all. If the ID comes from something like a SERIAL column, then yes, you can port those easily. I think every database system has something like SERIAL, as well as the ability to control an initial value, taking care of portability concerns. SERIAL has other problems, namely predictability, so another possibility is UUIDs. And those should be pretty portable too. I know DBMS UUID implementations are different from OS implementations, but the risk of collision should still be vanishingly small. And if you don't use IDs, then what's the choice? If the URI contains an article name then what about article names being changed? What about duplicate article names?
- steego 8y agoI can't believe people have been giving this post this much credit in the first place. All of his contrived examples are solved with trivial methods and it just sounds like he doesn't know how to migrate data from one database system to another.
- LoSboccacc 8y agothis seems backward, as far as the pk remain meaningless they're easier to port around, not harder. it's once you give them a meaning then trouble starts (for example you can't change the slug down the road if the title changes) and with integer keys the worst that can happen is that the sequence is not in the backup so after a restore you need to have the p sequence restart from the previous max id + 1; meanwhile with slug built off user entered data a change in collation can really screw up your day, unless you want to mangle all texts into basic ascii, and SO doesn't https://stackoverflow.com/questions/41102371/sql-doesnt-differentiate-u-and-ü-although-collation-is-utf8mb4-unicode-cia https://stackoverflow.com/questions/41102371/sql-doesnt-diff... (see the ü in the link more than the question itself)
- cryptonector 8y agoBetter blog title: "Do not use INTEGER PRIMARY KEYs in URIs" or "Do not use ROWIDs in URIs".
- xg15 8y agoWhat does he propose I do if two questions map to the same slug or if - beware - someone wants to edit their question?
- ehutch79 8y agoI don't understand why people are saying this is a security issue. If user a has private document 1234 at /doc/1234 and user b has private document 1235 at /doc/1235 when user a goes to /dec/1235 IT SHOULD NOT RETURN THAT DOCUMENT. Who in their right minds considers obscurity to be a replacement for authorization? If a random anonymous individual can access private data by hitting a url, the problem is not the id used in the url.
- ehutch79 8y agoAlso, what about when your users are all generating multiple entries with the same name/slug? thing-name-1532 isn't any easier than things/1532/thing-name I have no reason to enforce uniqueness of the name of things, but I MUST do this because some jerk said so in 2008?
- airstrike 8y ago> when user a goes to /dec/1235 IT SHOULD NOT RETURN THAT DOCUMENT. As a matter of fact, it should return 404 NOT FOUND for both users A and B
- jolmg 8y agoehutch79 said > user b has private document 1235 at /doc/1235 So, why do you say it should return a 404 NOT FOUND for user B?
- newscracker 8y agoThere’s a typo where doc is spelled as dec later on. That’s why the 404 requirement.
- newscracker 8y agoThere’s some time for the OP to edit and fix that typo. But yeah, I noticed that at first glance too.
- ehutch79 8y ago
- _fzslm 8y agoLooks like Hacker News does this too: https://news.ycombinator.com/item?id=1 https://news.ycombinator.com/item?id=1
- jolmg 8y ago> If you have to move the site to a different box, can you guarantee that those database IDs will remain the same? If you don't, then your foreign keys will be broken. > If you have to restore the site’s data from a backup, can you guarantee that those database IDs will remain the same? Ditto. If they're not, then that backup seems broken. > If you have to switch to a different database server (say from Microsoft SQL Server to Oracle), can you guarantee that those database IDs will remain the same? Ditto. I've only had one situation where I had to change the database ids, including making sure to change all foreign keys accordingly in all tables, and that was when I was migrating multiple company-hosted instances of a webapp they had in their intranets to a unified internet-hosted server. I was merging multiple databases into one so modifying ids was necessary so they wouldn't clash. At least in my case, I don't think any of those companies' employees would have had the expectation for their intranet URLs to work. I mean, even the host/domain part of the URI changed. Why would they have the expectation for the path part to still work?
- madrox 8y agoI get the vibe a lot of these critiques are rooted in academic understanding of the issues rather than real world practice. In practice, these are all problems that can be addressed...some rather trivially. The biggest real world concern I've ever had with embedding incremental IDs into URLs is that incremental IDs can leak information, like how many records you have and how quickly that's growing. Depending on your business, you may want to obfuscate that.
- 3xblah 8y ago"URIs in Stack Overflow look like this: http://stackoverflow.com/questions/13204/why-doesnt-my-cron-job-work-properly" http://stackoverflow.com/questions/13204/why-doesnt-my-cron-... Article gives only cons. What are the pros? https://stackoverflow.com/q/13204 https://stackoverflow.com/q/13204 Shorter, easier for users to work with. Could be even shorter with a domain hack. Does Stack Overflow have one? https://en.wikipedia.org/wiki/Domain_hack https://en.wikipedia.org/wiki/Domain_hack http://xona.com/domainhacks/s.cgi?q=stackoverflow.com http://xona.com/domainhacks/s.cgi?q=stackoverflow.com
- JeremyBanks 8y agoThey have s.tk but it's mostly used for internal/intranet links: https://meta.stackexchange.com/q/109795/134300 https://meta.stackexchange.com/q/109795/134300
- cmiles74 8y agoI worked with a customer that was concerned about the "security" of database IDs in the URL. I though their solution was novel: they chose a random long integer whenever a new row was created. It's fast like an integer and random like a UUID, the best of both worlds!
- einrealist 8y ago"URIs should be meaningful, not cluttered with meaningless information." Actually, URIs are opaque. The parts of an URI are implementation details - even the protocol, domain and port. To the user, changing database IDs, that happen to be part of the URI, is no different to changing the domain, port number or the protocol. Whenever I get into a discussion about "URI design", I state two rules: 1) Care about the URI design as much as you want. But never expect from someone else - especially the client - to make sense of that design. 2) When necessary, handle URI changes in a way that does not break the client (redirects are your friend). Btw. For this reason, browsers tend to remove the address bar from the UI (as much as possible).
- spartas 8y agoIt's a good thing™ Stack Overflow doesn't have those IDs in the URI anymore.
- dr01d 8y agoUuids
- michrassena 8y agoSay I'm convinced that IDs could possibly leak information, but UUIDs are problematic (e.g. cost of enforcing uniqueness grows with each added row). Would encrypting the ID with some symmetric key plus a salt be sufficient? The client sees a number where the ID can be recovered on the server side, but which the benefits of having an easily generatable unique identifier while making it challenging to recover the actual ID).
- Geee 8y agoThis is bullshit. It's absolutely necessary for the user to be able to refer to the resource by an ID of some sort. A slug is not an ID.
- jasonhansel 8y agoIf you want to estimate the total # of items in a DB based on auto-increment ID numbers, you can use: https://en.m.wikipedia.org/wiki/German_tank_problem https://en.m.wikipedia.org/wiki/German_tank_problem (Apparently this was used by militaries in WW2, to estimate the total number of tanks from the serial numbers printed on them.)