2 / 2
Dec 2023

I am using Mongoid gem in Rails with IAM session token to connect with my Atlas Cluster

def logs reload_mongoid_configuration @logs ||= Log.or(attributes_condition) .where(selector) .order_by(timestamp: :desc) end def reload_mongoid_configuration mongo_config = Mongoid::Config.clients[:default] old_connection_url = mongo_config[:uri] return unless mongo_token_expired?(old_connection_url) # Disconnect existing Mongoid clients Mongoid.disconnect_clients # Logic to get mongo URL with a new AWS session token Mongoid.load_configuration( clients: { default: { uri: MongoUriGenerator.audit_log_db_url(old_connection_url), options: { database: 'my_database' } } } ) end

My connection URL looks something like this

mongodb+srv://<temp_access key>:<temp_secret_key>@<mongourl>.mongodb.net/<db>?authMechanism=MONGODB-AWS&authSource=$external&authMechanismProperties=AWS_SESSION_TOKEN:IQo....

As I am using an aws session token I need to regenerate the URL after 1 hour. It’s working fine but after some time I am getting the following error

#<Mongo::Error::NoServerAvailable: No primary server is available in cluster ... #<Server address=<someaddress>.mongodb.net:27017 UNKNOWN NO-MONITORING pool=#<ConnectionPool size=0 (0-20) used=0 avail=0 pending=0 paused>> #<Server address=<someaddress>.mongodb.net:27017 SECONDARY replica_set=atlas-ihuqqp-shard-0 NO-MONITORING>]> with timeout=30, LT=0.015. The following servers have dead monitor threads

@Hassan_Anwer, the approach you’ve taken to refresh credentials looks good, but the error you’re getting is about dead monitoring threads. This is typically seen when our guidance for usage with forking servers isn’t followed.

Updating your application server configuration to ensure Mongoid clients disconnect/reconnect on fork should prevent these issues from occurring.