Search code examples
phplaravellumen

Restrict running code in Lumen route to one caller at a time


I'm making a small application with Lumen that has a route that is expensive to run. I'd like to make sure that only one person can hit this route at a time. If a second person tries to hit the route while another person is running it, then the application should return a message saying something like "Please try again in a few minutes." How can I accomplish this?


Solution

  • Use a mutex. If your app runs on a single host with a local filesystem, you can use flock:

    public function my_controller() {
        $fp = fopen('lockfile', 'r');
        if (! flock($fp)) die('Try again later');
        // do expensive thing...
        funlock($fp);
        fclose($fp);
    }
    

    If you have a cluster of machines, or the machine's disk are network mounted, use a database mutex. Eg, in mysql:

    do get_lock('lock');