[NodeJS 10.x/11.x]
I'm looking for an always-increasing time "id" that will be unique and monotonically increasing across processes (but not necessarily across servers). I've looked at Monotonically increasing time in Node.js but that's for performance timing. Basically, I'm looking for a timeId that can be persisted to a database.
Note: I've tried process.hrTime(), but on my MacMini, it's not monotonically increasing. Upgrading to Node10/11 and using hrtime.bigInt() seemed to solve part of my problem.
Here's my current idea (where bigIntToBase64String() is omitted, but does what you'd expect):
let startHrTime = process.hrtime.bigint();
let systemStartTime = BigInt(new Date().getTime()) * BigInt(2**16) * BigInt(2**5);
class TimeId {
getTimeId() {
let t1 = process.hrtime.bigint() - startHrTime;
let ticks = t1 + systemStartTime;
return this.bigIntToBase64String(ticks);
};
}
As you can see, it's a bit of a hack. I subtract the first hrtime I get, and then add that to the system start time (which I've mangled into a BigInt). Assuming perfectly synchronized clocks (ha!) this could possibly be used as a global timeId. (For my purposes, the cross-system clock skew will hopefully be solved another way).
I'm currently configuring some tests to validate my assumption, but, since I'm still quite new to JavaScript/Node.JS, I thought I'd ask... is this a reasonable approach?