bwmarrin / snowflake

A simple to use Go (golang) package to generate or parse Twitter snowflake IDs
BSD 2-Clause "Simplified" License
3.02k stars 374 forks source link

Check for clock drift #11

Closed whwright closed 6 years ago

whwright commented 6 years ago

The current implementation does not check for clock drift when generating snowflakes. This would be fairly easy to implement a basic check, however I think the cleanest way would be to change the Generate() function signature to return an error as well.

I understand this is a breaking API change you may not want. I am wondering if you are open to this change in any form. This could be breaking the API, deploying versioned packages with something like gopkg.in, creating a new API, etc...

Let me know what you think.

whwright commented 6 years ago

Thinking about this some more over the last day: I'm leaning towards a new API like GenerateId() that reuses the Generate() logic with the added functionality of returning an error. This seems to solve both problems.

I can get a PR up for this shortly, but I'm still interested in your feedback.

bwmarrin commented 6 years ago

Let me think about it :) I'd really like to avoid changing the API at this point.

Maybe if it detects a clock drift, it could wait until time catches up?

I'm curious what an example of how we'd check for drift would look too

whwright commented 6 years ago

I'll get a PR up and we can go from there.

whwright commented 6 years ago

We did this in our fork here https://github.com/blacklocus/snowflake. I'm going to close this.

bwmarrin commented 6 years ago

I understand :) I think eventually I'll try to get this or a similar solution added to the library here as well. I just haven't had time to work on it in the last few months :(. Hopefully I catch up!

nishaad78 commented 5 years ago

@whwright the current implementation now uses monotonic clock to safeguard against wall clock backwards movement. Ref: #18

whwright commented 5 years ago

Thanks for the ping @nishaad78; I didn't know about the monotonic clock implementation in go. This is a great way to solve the problem! 🎉