Queues & Background Jobs

Interview Questions: Workers, Horizon, and Redis

Q1: Why use Queues in Laravel?

Performance: To offload time-consuming tasks (sending emails, processing uploads, generating reports) from the main request cycle. This ensures the user gets a fast response.

Reliability: Jobs can be retried automatically if they fail.

Q2: How do you handle failed jobs?

Configuration: You can define $tries or $backoff properties on the Job class.

Failed Table: Failed jobs are logged to the failed_jobs database table.

Retrying: You can use Artisan commands like queue:retry all or queue:retry {id} to re-run them after fixing the issue.

Q3: What is Laravel Horizon?

Tool: A dashboard and configuration system for Redis queues.

Features: It allows you to monitor key metrics like job throughput, runtime, and failures. It also allows you to balance workers across different queues based on workload (auto-scaling).

Q4: Explain the difference between `dispatch()` and `dispatchSync()`.

`dispatch()`: Pushes the job to the queue. The job will be processed asynchronously by a queue worker in the background. The user gets an immediate response.

`dispatchSync()`: Executes the job immediately within the current request lifecycle. It does not go to the queue. It behaves like a normal function call.

Q5: How do you prevent a job from running twice (Atomic Locks)?

Scenario: If a worker times out but the job is still running, another worker might pick it up, causing duplication.

Solution: Use Cache::lock() or the ShouldBeUnique interface.

// In Job class
public function middleware()
{
    return [new WithoutOverlapping($this->user->id)];
}

Q6: What is the difference between `queue:work` and `queue:listen`?

`queue:work`: Boots the framework once and processes jobs in a loop. It is much more efficient (faster) but requires you to restart the worker (queue:restart) when you change code.

`queue:listen`: Boots the framework for every job. It is slower but useful for local development because it automatically picks up code changes.