5

I have a Puma server configured to use two workers, each with 16 threads. And having config.threadsafe! disabled to allow threading using puma.

Now I have a code, which I doubt not using threadsafety even though I have used Mutex as a constant in there. I want this code to be executed by only one puma thread at a time to avoid concurrency issues, and uses Mutex for it.

Now, My question is,

  1. Does Mutex works to inject threadsafety while using puma threads, on multiple workers? As I understand, worker is a separate process and so Mutex will not work.
  2. If Mutex doesn't work as per above, then what could be the solution to enable threadsafety on perticular code?

Code example

class MyService
  ...
  MUTEX = Mutex.new     
  ...

  def initialize
   ...
  end

  def doTask
    MUTEX.synchronize do
      ...
    end
  end
end
Parth
  • 1,281
  • 8
  • 17

1 Answers1

1

The MUTEX thing didn't worked for me, so I need to find another approach. Please see the solution below.

The problem is, Diff. puma threads are making requests to external remote API at the same time and sometimes the remote API takes time to respond.

I wanted to restrict the number of total API requests, but it was not working because of above issue.

To resolve this,

  • I have created a DB table where I will create a new entry as in-pogress , when the request is sent to external API.
  • Once that API responds back, I will update the entry as processed
  • I am checking total requests having in-progress before making any new requests to the external API.

This way, I am able to restrict the total number of requests from my system to external API.

Parth
  • 1,281
  • 8
  • 17