Kodi
Kodi

Reputation: 787

Database ID generation in a Clustered environment

I am developing a web application in clustered environment. The issue is that we need to generate an ID for each entity that gets created. We are in an environment with a number of database nodes that are all streaming with each other. The idea that I had was a sequence with an offset. So one site would have IDs ending with 1, the next 2, and so on. This seems an unwieldy solution because you are limited to a number of environments. What is the "best" way to guarantee a unique generated primary key when you are in a disturbed database environment?

Upvotes: 2

Views: 1326

Answers (1)

Justin Cave
Justin Cave

Reputation: 231661

Personally, I'd prefer the sequence with an offset. Yes, you are limited to a certain number of environments but, realistically, you can generally set things up from the outset so that the number of available environments is much greater than what you'd really need. If you do something like

At site 1

CREATE SEQUENCE sequence_name
  START WITH 1
  INCREMENT BY 1000;

At site 2

CREATE SEQUENCE sequence_name
  START WITH 2
  INCREMENT BY 1000;

and down the line, you can have up to 999 sites before you have to rework your sequences. That's generally more than enough. If you think you might realistically have 1000 sites, you can simply set the increment to 10,000 or 100,000. Given the number of values a sequence can generate, you still won't run out even if you set the increment in the millions. Realistically, you'll encounter problems with Streams dealing with too many sites long before you'll run into problems with sequences.

If you don't want to go down that path, the other option would be to use SYS_GUID to generate a globally unique ID and use that for your primary keys. That's not as efficient as using a sequence and it will require more space but it does allow you to have an arbitrary number of machines.

Upvotes: 1

Related Questions