10 Best Practices to Architect and Scale your Laravel Application on AWS Hosting

Laravel application on AWS Hosting

This blog will give you valuable insights into modernizing and scaling your Laravel architecture using AWS. You will learn how to leverage AWS Auto Scaling and architecture to support millions of users in minutes, prepare your Laravel codebase for scaling transformations, and maximize AWS cost benefits. These features and capabilities can transform your application into a high-performance and resilient PHP Laravel application.

This article will guide you through the best practices for architecting and scaling your Laravel application with high-level scalability standards on AWS. You will understand the requirements, considerations, and actionable steps needed to achieve business value and resiliency. While we focus on AWS due to its maturity and ease of innovation, the practices discussed can be applied to any cloud platform.

Additionally, we will explore why AWS is essential for large-scale growth of your SaaS Laravel application, outline the current and future enterprise architecture, and explain the importance of the twelve-factor app methodology. Finally, we will share key lessons to incorporate into your strategy when architecting on AWS DevOps.

This experience is a Decision Maker Article for Entrepreneurs, IT Leaders, and Business Development Managers. Let’s go!

The value of migrating your Laravel App to AWS Hosting.

In our previous article about running the digital transformation on AWS for your enterprise or web application, we explained the business benefits that bring the AWS Cloud adoption, including the reduction of your IT labor force, obtaining pre-configured services, which helps to achieve faster implementations and minimize downtime due to the repeatable and flexible infrastructure.

Living in the cloud is essential to scale SaaS Laravel applications. In there, you can decouple your architecture in multiple service pieces, including cloud storage (Amazon S3 and CDN), automatic scaling EC2 instances (AWS Auto Scaling), and integrate various Saas/Paas AWS components for your modern cloud-native application. 

Planning to move to the AWS cloud? Use this AWS Migration Checklist to prepare for your journey.

“Web Applications and enterprises need to transform, they need to transform to a continuous transformation, and the cloud is the key.”
-Stephen Orban

You’re not only transforming your application; once on board the AWS cloud, naturally, you are on an infinite journey of continuous innovation. I.e., Pay-as-you-go, Micro-services, Serverless, and so on.

Laravel Architecture on Docker and Microservices.

Throughout the AWS Cloud Journey, there have been multiple disruptive evolutions, and one of them is the microservices. In this blog, we won’t dive deep into microservices because, as a first step to transforming your application, although, I won’t cover microservices (Docker) approach. And you might ask why? As a first step to transforming your application towards a cloud-native application, I suggest beginning with this article, which corresponds to a monolithic approach.

Then, we can go down the road with more expertise from your development team, a mature application with thousands of users; I’d suggest jumping into a Laravel microservice approach, i.e., dockerize your Laravel PHP product using Docker, AWS ECS, Kubernetes or AWS Fargate. I’ve found many digital agencies, which are adopting the AWS Cloud and DevOps practices with Docker/Serverless strategies, and literally getting overwhelmed with these sophisticated technologies deriving at the same time on project failure because it was not ready to this stage. You can avoid this by growing gradually.

Conversely, if your Dev team has enough seniority and experience with Docker and microservices, I wouldn’t hesitate to architect with microservices, but it will be covered in a second article called “Microservices with Laravel, Docker, and AWS ECS.”

Who is this article for?

Whether you are kicking off an MVP app on Godaddy/Hostgator, deploying Laravel on AWS with basic principles and Laravel architecture best practices or ready to jump from hundreds of users into million users, this article is for you and will help you scale Laravel architecture on AWS.

Laravel Architecture on AWS to Large-Scale SaaS

So, let’s start by making clear what you most need to scale a Laravel application on AWS.

In the next diagram, we will explore how a next-generation Laravel application should be architected with the full range of AWS DevOps components; each piece mentioned in this AWS stack is highly elastic, scalable, and resilient.

Laravel AWS

1. AWS Auto Scaling and Load Balancing

Initially, the dynamic traffic comes from AWS Route53, which will route all requests to the Application Load Balancing, which the AWS ALB will load balance across a fleet of ec2 instances ( 2…N Instances), this fleet should “scale” horizontally according to the traffic demands or the AWS CloudWatch metrics.

2. Amazon S3 and CloudFront CDN

On the other hand, all static content, including images, videos, and HTML, will be hosted on Amazon S3 – the cloud storage with infinite storage and elasticity. In front of Amazon S3, we will compound AWS CloudFront with the objective of caching the entire static content and reducing bandwidth costs. Integrating this pair of components is crucial.

3. AWS RDS Aurora (managed database services)

The database data should be placed on AWS Aurora or RDS; and AWS ElastiCache (Redis) for session management and cache user data. These AWS components are elastic and scalable, which helps to design the AWS Well-Architected framework with the highest fault-tolerance and resiliency.

4. Amazon VPC and Networking

In the AWS Networking level, we proposed AWS VPC with a public/private enterprise network. Following PCI and HIPAA practices, we should have a VPN encapsulating your Laravel application within your private AWS enterprise network. Also, we considered an AWS VPN Connection and OpenVPN service to access the private network to your multiple Laravel environments.

5. Route53

From the DNS perspective, Route53 is needed to manage the application domain, DNS scalability, routing latency, and more features that Route53 can incorporate to degrade failures.

6. AWS Lambda

This serverless component will be used for async jobs and backend scripts to minimize load in your AWS Autoscaling cluster. Here’s a quick explanation of Lambda, so you can have a general insight into what it is.

We will explore these AWS components substantially in detail later in this article.

Web applications that can fit within this Laravel architecture:

  • API Laravel applications
  • Mobile Backend applications
  • Laravel enterprise applications. CRMs, ERPs, and back-office systems
  • SaaS Laravel applications
  • Front-end applications. i.e., Angular, React, Vue.js or any HTML site.
  • ANY web platform: Python, Node.js, Ruby, PHP, Zend, CakePHP, Yii, and Symfony.

Laravel architecture AWS tech stack

Why not Cpanel?

Cpanel is not recommended to scale as it can slow down your application performance.

Twelve-Factor App Methodology for your SaaS Laravel application on AWS

It is not easy to subsist in a modern cloud ecosystem, that’s why there are fascinating principles that will help you to build a perfect AWS architecture for your Laravel application, including the twelve-factor methodology, design applications with a stateless approach, and decoupling service components.

I’m sure you are adopting many of these principles already, however, I will cover merely the relevant to the AWS Laravel architecture and AWS Auto Scaling to maximize infrastructure robustness.

Twelve-factor App methodology key principles:

Application config files

Should be outside of the codebase, and these config files are replaced with environment variables. i.e., Db connections, secrets, environment, hosts, IP, etc.

Application dependencies

It shouldn’t be in your codebase, and instead, you should use a dependency management tool to declare your large dependencies and libraries required from the server. i.e., Gemfile, site-packages, pom.xml, manifests, etc.

Use a Control Versioning System

Not much to mention here because it is necessary to integrate the Git workflow. i.e., Github, bitbucket or AWS CodeCommit.

Stateless applications and processes

It’s crucial that your application doesn’t store any data in the local file system or is dependable from a persistent state in the application or server. In other words, the application/server can be turned off and recreated without losing any data. Only persistent data is stored in databases or backend services.

In case of application failure, splitting components as much as possible and making them independent of others will result in an easy analysis and isolated issue.

Immutable Infrastructure

Instances shouldn’t be modified after provisioning, and there should be a standard base image (AWS AMI), which is regularly updated and patched. As a result, you’ll get an AWS auto-scaling working smoothly, with fewer deployment failures, and consistent infrastructure.

Dev, test and Production Parity

It’s crucial that these environments should be as similar as possible regarding software, libraries, database data, and code. Furthermore, it’s possible to close the gap across all environments with the hand of a CVS, repeatable infrastructure, and continuous integration/delivery (CI-CD).

Continuous Integration and Continuous Delivery – CI/CD

As the application and traffic grow, you must implement a mechanism to release code to your different instances and enterprise environments. It is essential to design a continuous delivery workflow to improve development productivity with scalability, multiple environments, and a distributed architecture.

These architecture design principles are part of the DevOps culture, which is in the plans of all CTOs, Engineering Directors, and VPs.

10 Best Practices to Scale and Architect your SaaS Laravel Application on AWS

Now is the time to implement those principles for your Laravel architecture. Let’s start with the 10 best practices for scaling and architecting your SaaS Laravel application on AWS (from MVP to million users).

Practice 1.  Amazon S3

In my perspective, Amazon S3 is the second component that boosted the evolution of the Cloud, just behind the pay-as-you-go model with cloud scalability. Amazon S3 is unlimited cloud storage with superb capabilities, including 99.99% durability and high availability, object-based storage acting as an API, and the ability to host static websites based on HTML, Angular, and React! Isn’t it amazing? Amazon S3 Cloud storage can be a serverless application without much effort.

The first step to scaling and architecting your Laravel application is to separate all static content (media, images, video, docs, etc.) to Amazon S3. This split allows distributing the application’s requests in parallel, dynamic content served by the EC2 instance (Web Server), and the rest with Amazon S3. This is a DevOps and Development effort where all static content on your Laravel project is pointed to the Amazon S3 endpoint.

Technically, you need to move your actual content into Amazon S3 buckets, set the correct IAM roles/permissions to allow read access, and configure your Laravel driver to point to Amazon S3—more details about how to integrate Amazon S3 with Laravel.

Amazon S3 can host static websites and front-end applications (HTML, Angular, React, and more) and is fully scalable, redundant, and serverless. Based on my empirical evidence, I recommend hosting your static websites on Amazon S3. The presented practice can be performed in a few steps, and no servers are needed (serverless).

Practice 2. Horizontal Scaling with AWS Auto Scaling (Load Balancer)

The next AWS component in the pipe is AWS Auto Scaling. This fantastic feature revolutionized the scalability paradigm. Before AWS Auto scaling, there was merely manual scaling, and reacting to different traffic events was difficult to converge and used to cause several failures.

AWS Autoscaling scales dynamically behind a load balancer (AWS Application Load Balancing), which is defined by a set of scaling policies (thresholds/limits) that must occur to scale up and down. The instances can scale up and down based on predefined criteria for CPU, RAM, or any other instance metric, allowing you to save money and unneeded AWS resources.

Primarily, to deploy AWS Auto scaling you need to set up AWS Application Load balancing, define a threshold for triggering the autoscaling event on AWS CloudWatch, determine a Min/Max servers amount, set an AWS Autoscaling Group, AWS Auto Scaling launch configuration, and pre-configured O.S with an Amazon Machine Image (AMI).

Practice 3. AWS RDS Aurora with Replication.

Amazon RDS is a database-managed service that requires minimal maintenance and is compatible with Mysql, PostgreSQL, Oracle, and more. The RDS is a self-maintained database with a pre-configured database, software updates, patches, and automated backups. To scale and cluster an Amazon RDS, first, you need to enable the RDS Replication feature, which grants your RDS the capacity to create replicas and establish master-slave relationships with those replicas, similar to Mysql/PostgreSQL replication; this can be achieved with just a few clicks.

Similarly, Amazon Aurora is a high-performance AWS database that combines high speed, high availability, and performance. According to AWS, Aurora is 5X faster than a standard MySql or 3X faster than PostgreSQL.

Amazon Aurora is a high-performance database from AWS. If you are planning to improve your database throughput, you should definitely consider Aurora.

Hint: AWS Aurora with replication and/or multi-AZ availability can be expensive. Take precautions with your cloud hosting budget. You can review this free AWS Cost Optimization Checklist to reduce your AWS billing.

Aurora RDS Aurora with Replication

Practice 4. Application Load balancing – ALB (Laravel Load Balancer)

Another Laravel architecture best practice is introducing the application Load Balancing (ALB), a layer 7 LB. It has multiple benefits, including the capacity to balance requests by domain/URL and not just by port/protocol; it also supports the inclusion of multiple SSL certificates; it is significantly cheaper than ordinary Load balancer service, and it’s billed by request; and one relevant fact about ALB is that you don’t need multiple Load balancers for integrating different APIs/Domains.

That said, I recommend architecting your Laravel architecture based on an ALB – Auto Scaling integration. It’s a must to have a load balancer enabled to scale and grow your SaaS Laravel application. You can balance your HTTP/https services, APIs, and any web socket. Lastly, the ALB was natively built for micro-service environments with Docker, AWS ECS, and Kubernetes. Still, it can also be used with a monolithic approach, as presented in this architecture.

Practice 5. CloudFront CDN

Now that you have Amazon S3 running in your application, we must introduce CloudFront CDN in front of Amazon S3 and save Bandwidth!

Amazon CloudFront CDN, is an amazing component with numerous features to highlight and commonly collaborates with Amazon S3. Amazon CloudFront is a Content Delivery network aimed at caching content, distributing requests, serving video content, and many more features.

Some CloudFront capabilities:

  • This CDN is globally distributed. Consequently, traffic is routed to the nearest edge location, helping to improve User experience and speed.
  • It helps improve application speed by caching static/dynamic content from the Amazon S3 or EC2 (origins).
  • It helps reduce AWS bandwidth costs from the Amazon S3 due to its caching magic.
  • Similarly, it’s a video hosting solution for Media/Video streaming.
  • It’s built to improve application performance and scalability by granting low latency.
  • CloudFront can help secure your back-end instances and filter common botnets/DDoS attacks. An AWS WAF achieves this.
  • It decreases the load on web instances, enabling fewer AWS resources.
  • It supports security certificates (SSL/TLS).

So, what’s the deal with integrating your Laravel application with CloudFront CDN? It’s recommended to have an additional subdomain (C-Name Record) for this CloudFront edge location, i.e., cdn.company.com. Also, as discussed, static content should be placed on an Amazon S3 bucket, and Cloudfront will pull the data from the origin (S3 bucket).

Next, you need to create a CloudFront distribution where all content will be distributed across the edge locations; thus, the end user will start getting cached. And that’s it, considering you have your Laravel codebase pointing to Amazon S3. It should take you a few hours to set it up.

Practice 6: Amazon VPC Amazon Virtual Private Cloud and AWS Networking

Amazon VPC is a logical network on the AWS Cloud, it lets you build multiple isolated logical networks inside your infrastructure. Creating a VPC network and robust subnets is essential to growing, architecting, and structuring applications in multiple groups/departments. AWS Networking (Amazon VPC) has various features, including subnet creation, route tables, own IP ranges, network ACLs, AWS security groups (Network firewall), network gateways, hardware Virtual Private Network (VPN) creation, and more.

When deploying a VPC for your SaaS Laravel application, you must ensure that web instances, databases, and backend services are all included on a private subnet, and in the other hand, the ALB is added on a public subnet. With this network topology, consider deploying a VPN to access your private network.

Your SaaS Laravel application can be transformed into a superbly secure logical network, complying with one of the multiple PCI/HIPAA/FedRamp requirements.

Practice 7. AWS ElastiCache (Redis and Memcached)

Introduce AWS Elasticache to scale Laravel application, to provide higher throughput and lower latency retrieved from your database.

AWS ElastiCache is a fully scalable, available, and managed caching and data storage system that aims to improve application performance, distributed cache data, and in-memory data structure stores. It’s an In-memory key/value store for Memcached and Redis engines, with a few clicks you can run this AWS component entirely self-managed.

To name a few benefits:

  • It Reduces workload on the backend (Database and processing)
  •  It Improves application speed by caching data.
  • It Helps to scale and architect modern applications.
  • ElastiCache manages and stores your application session.
  • It reduces low latency.
  • Can scale from 1 node to many nodes.

AWS ElastiCache use cases:

  1. Real-time transactions.
  2. Real-time Chats.
  3. Analytics and BI.
  4. Session Store (Session management).
  5. Cache, Caches and Caches data.
  6. As a Queuing system

The difficulty here is how to use AWS elastiCache with your application functionality and what application modules can be handled by your caching system. The integration from your PHP Laravel framework to the AWS component, it’s a 3 step-by-step process.

  1. Deploy AWS ElastiCache and identify your Redis end-point and port.
  2. Deploy predis/Redis package via Composer
  3. Connect your config/database.php file with your Redis end-point

Thus, it’s time to let the dev team figure out what pieces of your application can be used with AWS ElastiCache to improve high performance and throughput.

Practice 8. Route 53

Shift from Godaddy DNS to AWS Route 53.

Your DNS might be managed by GoDaddy, but it is a vital practice that the entire DNS domain is controlled by Route 53. This AWS component can act as a DNS Load balancer, to Route traffic according to latency, and helps to scale modern cloud-native applications.

Amazon Route53, it is a modern DNS manager service designed to scale and improve high availability from the DNS perspective. Similarly, it has the ability to act as an API and can interoperate with your API Laravel application, it introduces as well the agility necessary to deploy scalable applications, and useful to integrate to Amazon EC2 instances, Elastic Load Balancing (ELB), and Amazon S3 buckets. I highly incentive, that modern Laravel SaaS applications should be migrated to Amazon Route 53, not just the application, also transfer your DNS records and domain name to Route 53. How to migrate your Godaddy DNS to Amazon Route 53.

Need more redundancy and improve response? Create a new environment in different AWS region and deploy AWS Route53 with routing policies.

Some Amazon Route53 Features:

  • Health Checks. Route53 can monitor your applications for outages or downtimes. Also, can be used as a monitoring system. (Basic, won’t replace a Monitoring system)
  • DNS Failover Routing policy. As the name states, you can obtain a failover solution on the DNS level, separating your SaaS PHP application on two environments, primary and backup waiting to jump in case the primary fails. This brings us more resiliency and high availability.
  • DNS Latency routing policy. This policy directs traffic requests to the lowest latency, between the end-user and the application environment. As a result, application speed and UX improvements.
  • Geographic routing policy. This routing policy, let your requests be routed to the same physical region where you are located. Similar outcomes from the previous point, degrade latency.

A common misunderstanding: DNS Failover (Amazon Route53 Failover), it’s not the same as Load balancer failover, Haproxy failover or Heartbeat.

Practice 9. Why not AWS EFS?

At ClickIT, we used to architect and scale Laravel applications with AWS EFS, but we have encountered that using EFS for sharing code across multiple instances behind an AWS autoscaling slows the application performance and introduces another network layer to the scalability equation. AWS EFS, was a promising NAS replacing NFS, but evidently, when working with remote storages shared within a cluster of instances, there is no way to avoid the network latency. However, AWS EFS can be used for multiple activities, including disaster recovery, improved NFS solution, and elastic file storage.

It’s not recommended to include AWS EFS in your AWS architecture’s equation, due to the network latency that can cause serving your code base or static content.

Practice 10. Scaling with Lambda

AWS Lambda

During these past 10 years in different periods, AWS has revolutionized the cloud vastly fast – Pay-as-you-go model, Auto scaling, DevOps, microservices and now Serverless (Lambda). In 2014, AWS lambda was released with the premise to run code without servers, introduced the paradigm of Serverless applications with minimal IT operations (NoOps), and jumping all *aaS ecosystems up to executing code per events, only when needed; Again, fully scalable, redundant and with the pay-per-use pricing model. With Lambda you are charged for the milliseconds consumed, number of requests, and compute. More info to the Lambda AWS official resource here.

Some Lambda use cases:

  • Serverless web applications. Lambda can be handled to process the application logic of any front-end application (Angular, react and HTML). For instance, sending emails or processing forms requiring a Laravel backend process/job. By the way, if you are willing to dig deeper into the Serverless theme, you can visit our blog at any time!
  • Disaster Recovery and backups. Planning to script you backups inside an EC2 instance? Why don’t you move your bash scripts to a python Lambda function?
  • Lambda and API Gateway. Lambda is commonly combined with AWS API Gateway, any logic that is required by your API Gateway is handled by lambda, for instance, to process persistent data to RDS or JSON calls coming from the AWS API Gateway.
  • Process hot data. Lambda can transition data from Amazon S3 to Kinesis, DynamoDB or RDS. Another good example is, used for recording, processing, and converting video files composed of AWS Elastic Transcoder, S3, and Lambda.
  • Scheduled events, workers, and jobs. Lambda can replace your cronjobs, workers and long-processing jobs that are hosted on a single EC2 instance as a cronjobs/workers.
  • Build IoT and Mobile Backend. Develop your entire digital product (IoT and Mobile) with serverless and NoOps. Composed of AWS Lambda, AWS API Gateway, and the mobile hub.

Here’s the deal:
How to integrate your Laravel PHP application with lambda? It’s up to your imagination. But you can initiate with the presented lambda scenarios.

Why did I not include AWS Beanstalk?

There’s one component that we did not outline about. AWS Beanstalk is a PaaS platform that let us build, deploy and scale cloud-native applications with minimal maintenance. AWS Beanstalk is comparable to Heroku, but for AWS platform. It has his pros and cons, and in this article, we established a different approach without AWS Beanstalk due to various indicators; which includes slow deployments, custom configurations challenging to achieve, hard to maintain (stack upgrades), and lastly, troubleshooting is complicated due to lack of flexibility in the AWS infrastructure.

What have we learned about Laravel Architecture?

This blog explored how AWS can be the key to scale Laravel application and the Laravel architecture best practices. Now we know that AWS can help serve a million users with an eloquent architecture with the ten AWS practices, 12-factor methodology, and DevOps Automation. We have learned crucial AWS components to scale and architect Laravel SaaS applications, which also apply to the enterprise. Additionally, we described the essence of each AWS component, uses cases, and an overview of how to tackle each principle.

By applying these measures to your web application, you are systematically converting a cloud-native application. Lastly, once on board the AWS cloud, you have joined the journey to the continuous digital transformation that the AWS cloud is pulling us by inertia.

You can find this article on DevOps.com here: Using Laravel and AWS: What You Need to Know and Best Practices for Your SaaS Laravel Application on AWS.

Let our AWS-certified engineers guide you to success

Subscribe

to our newsletter

Table of Contents

We Make
DevOps Easier

From building robust applications to staff augmentation

We provide cost-effective solutions tailored to your needs. Ready to elevate your IT game?

Contact us

Work with us now!

You are all set!
A Sales Representative will contact you within the next couple of hours.
If you have some spare seconds, please answer the following question

FREE EBOOK

This is your chance to claim our FEATURED product the AWS Migration Checklist!

Download this checklist to learn how to evaluate your cloud environments running in AWS or if you are planning to deploy your application on the cloud.

Also, learn how to optimize your application performance at a low cost.