0
class ExampleController < ApplicationController

  def getAPI
      #retrieve and process data from API
  end

end

How can I avoid that the controller action gets executed simultaneous? Would a class variable work?

class ExampleController < ApplicationController
  @@in_progress = false

  def getAPI
      render and return if @@in_progress
      @@in_progress = true
      #retrieve and process data from API
      @@in_progress = false
  end

end

Are class variables persistent even if the applications runs with multiple processes of e.g. passenger. Is this a good idea at all?

Will this work if multiple users request the same controller action or does it only avoid simultaneous execution for one user?

0lli.rocks
  • 1,027
  • 1
  • 18
  • 31

1 Answers1

0

You have to take care of this problem with the right tools depending on many factors.

  • Is your code running on a single, multi-threaded process? Then mutexes could be helpful
  • Is your controller action not to be run concurrently because of database operations only? Then a transaction with a lock might be your solution
  • Is your code running on multiple processes, and maybe on different servers at the same time? Then an external lock should be considered (ex: https://redis.io/topics/distlock)

Edit: Please do not implement a mutex-like mechanism of your own (@@in_progress). There are tools that handle this stuff atomically and they are well-tested.

Edit2: If your controller action is to wait for a synchronous response from an API, this is a job to be run asynchronously. Consider using tools like Sidekiq.

yoones
  • 2,394
  • 1
  • 16
  • 20