Ebaldino
Ebaldino

Reputation: 31

PHP apcu not persistent in Laravel queued/dispatched jobs

(Laravel 8, PHP 8)

Hi. I have a bunch of data in the PHP APC cache that I can access across my Laravel application with the apcu commands.

I decided I should fire an async job to process some of that data for the user during a session and throw the results in the database. So I made a middleware that fires (correctly) when the user accesses the page, and (correctly) dispatches a job called "MemoryProvider". The dispatch command promply instantiates the MemoryProvider class, running its constructor, and then queues the job for execution. About a second later, the queue is processed and the handle method in MemoryProvider is run.

I check the content of the php cache with "apcu_cache_info()" and "apcu_exists()" in the middleware and both in the MemoryProvider constructor and in its handle method.

The problem:

  1. The PHP cache appears populated throughout my Laravel app.
  2. The PHP cache appears populated in the middleware.
  3. The PHP cache appears populated in the job's constructor.
  4. The PHP cache appears EMPTY in the job's handle method.

Here's the middleware:

    {
        $a = apcu_cache_info();                 // 250,000 entries
        $b = apcu_exists('the:2:0');            // true
        MemoryProvider::dispatch($request); 
        return $next($request);
    }

Here's the job's (MemoryProvider) constructor:

    {
        $this->request = $request->all();
        $a = apcu_cache_info();                 // 250,000 entries
        $b = apcu_exists('the:2:0');            // true
    }

And here's the job's (MemoryProvider) handle method:

    {
        $a = apcu_cache_info();                 // 0 entries
        $b = apcu_exists('the:2:0');            // false
    }

Question: is this a PHP limitation or a bad Laravel problem? And how can I access the content of my PHP cache in an async class?

p.s. I have apc.enable_cli=1 in php.ini

Upvotes: 1

Views: 1439

Answers (1)

Ebaldino
Ebaldino

Reputation: 31

I found the answer. Apparently, it's a PHP limitation.

According to a good explanation given by gview back in 2017, a cli process doesn't share state or memory with other cli processes. So the apc memory space will never be shared this way.

I did find a workaround for my specific case: instead of running an async process to handle the heavy work in the background, I can get the same effect by simply issuing an AJAX request. The request is handled independently by PHP, with full access to the APC cache, and I can populate my database and let the user know when it's all done (or gradually done, as is the case).

I wish I had thought of this sooner.

Upvotes: 2

Related Questions