I have users accessing a URL with a short code they're provided, e.g. example.com/ABCD. I'm running node and using node_redis module, although I don't think it matters much. What is the safe way to generate unique codes?
I can generate something randomly and check if it's in use, but given the async nature of my calls to redis, there's a possibility that it would then be used somewhere else before being saved back to redis.
A few thoughts:
- I'm not worried about the limited namespace, I can extend it if needed but likely won't
- ... But the goal of keeping the code short (easy to type on mobile) means I want to keep the namespace small, increasing the likelihood of a collision.
- I suppose I could keep the list of used (or unused, for that matter) codes in memory, which isn't the worst thing, but seems like a strange move.
- I know I could make redis auto-increment, but I don't want to use numbers (I don't want to be sequential).
If I don't want to keep the list in memory, should I switch data stores? Am I correct in thinking that keeping the list in memory is ok but not great?