Error When Connecting To Mongo Server Using IAM Role

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

 def logs
  @logs ||= Log.or(attributes_condition)
               .order_by(timestamp: :desc)

 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

  # Logic to get mongo URL with a new AWS session token
    clients: {
      default: {
        uri: MongoUriGenerator.audit_log_db_url(old_connection_url),
        options: {
          database: 'my_database'


My connection URL looks something like this

mongodb+srv://<temp_access key>:<temp_secret_key>@<mongourl><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> UNKNOWN NO-MONITORING pool=#<ConnectionPool size=0 (0-20) used=0 avail=0 pending=0 paused>> #<Server address=<someaddress> 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.