I’m using Mongoid 4.0.0.alpha2 in a Rails 4 app. I have a Project model that looks something like this:
class Project
include Mongoid::Document
field :last_serial_number, type: Integer, default: 0
def next_serial_number
inc(last_serial_number: 1). last_serial_number
end
end
From what I understand of inc(), calling next_serial_number repeatedly should result in a unique, ever-incrementing int. Usually it works great. But sometimes when the app is under heavy load the same serial is returned twice, resulting in dupes.
The app is running on a mongo cluster that include three servers. At first I thought the dupes might have something to do with master/replication skew, so I added
Mongoid::Config.sessions['default'] ||= {}
Mongoid::Config.sessions['default']['options'] ||= {}
Mongoid::Config.sessions['default']['options']['read'] = 'primary'
to an initializer. This didn’t help at all. The app is also uses Sidekiq to process background jobs, and I thought that maybe there was some kind of threading problem with atomic increments. The Kiqstand readme, though, seems to suggest that Mongoid 4 should correctly pool connections for Sidekiq out of the box.
Is there something obvious I’m doing wrong here? Could this be some kind of Mongoid 4 bug?