Why use a Message Queue?

Have you ever wondered why someone would choose to use a message queue instead of executing code immediately?

Synchronous vs. Asynchronous Execution

Consider this: some code takes time to run. Although programming languages like PHP can operate both synchronously and asynchronously, they typically run synchronously.

Synchronous execution implies that each line of code completes before the next one starts. If you have a time-consuming operation, the subsequent lines must wait, creating a traffic jam in your code.

Handling Long-Running Code

To avoid slowing down your entire script, you can delegate time-consuming tasks to another process, such as a message queue. Message queues operate asynchronously, meaning they don't pause for each task to finish before proceeding. This approach frees up your main code and eliminates the bottleneck.

Long-running code might involve complex calculations, intensive resource use, or interactions with external services like APIs or third-party systems.

Managing Bulk Operations

Message queues excel at managing not only lengthy tasks but also large-scale operations. You can send hundreds, thousands, or even millions of messages to a queue and have each processed individually by a background task.

Imagine you need to update many rows in a database. Large-scale updates can be sluggish and inefficient. With a message queue, you can create separate messages for each row update, potentially improving server resource efficiency compared to updating all rows simultaneously.

Background Processing

These queue consumers run as background processes, separate from your main web server's operations. This separation ensures that the processes handling the queue do not interfere with the main server's resources.

Complete and Continue  
Extra lesson content locked
Enroll to access all lessons, source code & comments.
Enroll now to Unlock