Laravel

Using AWS SQS with Laravel 5

Jon Sherrard I am a person. I write PHP and JavaScript. I sort of like the Internet.

Use the power of a Amazon’s scalable queuing system in your Laravel 5 application

In this post, we’ll look at why you might use queues, and then have look at how you can get started quickly and cheaply with Amazon’s SQS (simple queue service), on AWS

When you should use a queue

For the most part, your Laravel 5 web application is responding to HTTP requests. If your app is simple, you’ll probably be doing some simple data manipulation, and then saving that information to a database. As your application grows in complexity, some routes in the system might start doing a decent chunk of work. Things that might take some time include:

  • Image processing
  • Sending an email
  • Communicating with a third party API
  • Pushing files to a service like dropbox or S3

As PHP and PHP executing web servers are generally used synchornously, waiting for all of these to complete before responding to the user’s request could take some time. An example request that uses some of these examples, is uploading a new profile photo:

  1. Write POST-ed image data to the file system
  2. Validate the uploaded image size
  3. Resize the image
  4. Create a thumbnail version of the image
  5. Push the resized image to S3
  6. Push the thumbnail to S3
  7. Save the S3 URLs to the database
  8. Respond to the POST request with a success message
Improve Laravel 5 performance with AWS SQS 1

In our initial version of our app. A request to upload an image takes 1.38ms to complete. This is pretty slow for a modern web application, and it also blocks the process thread from working on anything else.

In this example, steps 3 – 7 don’t need to have happened before we send the success message.

If we’ve validated the image size, then we can respond immediately to the user that their upload is “good”. We’ll then let the system handle the resizing and S3 uploads as and when they get to it. If something does go wrong at that point, we can email the user, or send them a notification in the app that something went wrong.

Improve Laravel 5 performance with AWS SQS

Using the queue architecture, our app now responds far quicker. We’ve now posted a tiny message to the Amazon SQS queue as JSON. Our application will process these queued instructions later, or perhaps via a worker server.