In a Rails app I need a source of unique, sequential (no gaps) integers to use as serial numbers. It must be persistent and allow concurrent access.
Database auto-increment isn’t adequate because most don’t guarentee the “no gaps” property.
In straight SQL I would just create a one-line table and say (in PostgreSQL) something like:
update sequence set value = value + 1 returning value
This is apparently standard practice in the SQL world. References exist.
In ActiveRecord I easily created a model the model and found .increment! and .increment_counter in the documentation. But I can’t figure out how to atomically retrieve the incremented value. Locks and transactions don’t seem to help.
If you want to use redis (and maybe you already are because of Resque or Sidekiq), you can do an
INCRon a key, this is atomic and returns the new value.