Scaling Laravel with Serverless Redis

Introduction

Laravel is a popular PHP framework for building scalable, high-performance web applications.

Prerequisites

Before you get started, you’ll need to have the following:

Architecture Overview

Rather than running Laravel on a single server, let’s consider the following scenario:

  • A single Load Balancer is responsible for routing requests to the two web servers.
  • A MySQL database server, used to store the application’s data.
  • Upstash Serverless Redis cluster is responsible for caching data and storing user sessions.

What is Serverless Redis?

Serverless Redis is a fully managed database as a service product where the pricing is based on per command, so you are only charged what you actually use.

Why Serverless Redis?

By default, Laravel would store the user sessions in files on the web server’s disk. That way if the load balancer forwards the user request to a different server, the user session would be lost.

Horizontal Scaling vs. Vertical Scaling

Just a few words about the difference between horizontal and vertical scaling:

  • Horizontal scaling on the other side, is when you add more servers that are responsible for serving requests to scale-out.

Creating a serverless Redis cluster

With Upstash, you can create a serverless Redis cluster in 30 seconds by following these steps:

  • Click on the Create Database button.
  • Enter the name of your Redis cluster and choose a region.
  • Click on the Create button.

Configuring Laravel with Serverless Redis

Now that you have a serverless Redis cluster, you can configure Laravel to use it just as you would any other Redis instance.

Install the Predis package

In the past, you would use the PHP Redis extension to connect to your Redis cluster. However, now you can use the Predis package instead.

composer require predis/predis
REDIS_HOST=your_upstash_redis_endpoint
REDIS_PASSWORD=your_upstash_redis_password
REDIS_PORT=your_upstash_redis_port
CACHE_DRIVER=redis
SESSION_DRIVER=redis
php artisan config:clear

Conclusion

Using Laravel with Serverless Redis is a great way to scale your application. Even if you are running Laravel on a Kubernetes cluster, you can still use a serverless Redis cluster to store your user sessions and cache data in a scalable way.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bobby Iliev

I am a professional System Administrator with a demonstrated history of working in the internet industry. I am a Linux lover