10 Best Practices to architect and scale your Laravel Application on AWS Hosting

Laravel application on AWS Hosting

Most likely, you have heard a lot about AWS and Laravel, and you’re planning to go to the next level to modernize or scale Laravel application, things come to your mind, including AWS Auto Scaling, AWS architecture to support a million users in minutes, increase agility just living on the AWS cloud, and prepare your code-base laravel application to evolve for this scaling transformation obtaining the AWS cost benefits. These features and capabilities are the compelling promoters to transform your application into a high performance and resilient PHP Laravel application, so keep reading to discover laravel architecture best practices.

Stop your paralysis analysis about how to Architect and leverage Laravel on AWS and continue reading to dissipate your constraints.

In this article, I will describe how to architect and scale your Laravel application with high-level scalability standards on AWS, it will help you understand what is required, considerations and sharp action items to gain business value and resiliency. We chose the AWS Cloud since is the most mature IaaS provider and makes things easier to innovate; although, the practices shown below can be applied to any cloud platform.

Furthermore, I will explain why AWS is a vital option to large scale and grow your SaaS Laravel application, present the current/future enterprise architecture and the importance of the twelve-factor app methodology. Lastly, a description of multiple lessons to include in your strategy when architecting on AWS DevOps

This experience is a Decision Maker Article for Entrepreneurs, IT Leaders, and Business Development Managers.

The value of migrating your Laravel App to AWS Hosting.

On my previous article, about running the digital transformation on AWS for your enterprise or web application, I explained the business benefits that brings 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 on the cloud, it’s 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. Also, if you are planning to move to the AWS cloud, you could 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

I really enjoyed this phrase from Stephen Orban because you’re not only transforming your application; once on board to the AWS cloud, naturally, you are in an infinite journey of continuous innovation. I.e. Pay-as-you-go, Micro-services, Serverless, and so on.

ALSO READ: Migration strategies for your AWS Application

Laravel Architecture on Docker and Microservices.

Throughout the AWS Cloud Journey, there have been multiple disruptive evolutions, and one of them is the microservices, 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.

I’ll tell you how to avoid this:

“ Let’s grow gradually”

Oppositely, 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 on 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
In the other hand, for 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

Why not Cpanel?

** Don’t use Cpanel for any web application, it is not recommended to scale as it can slow down your application performance.

AWS checklist migration

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.

“Evidently, 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 time to apply those principles into action for your laravel architecture

Let’s start with the 10 best practices to scale and architect 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 an unlimited cloud storage with superbly capabilities, including 99.99% of durability and high availability, object-based storage acting as an API, and with 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.

“Amazon S3 is reliable, scalable and secure with no real configuration needed.”

The first step to scaling and architect your Laravel application, its 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), fully scalable, redundant, and Serverless. From my empirical evidence, I recommend to host your static websites on Amazon S3. The presented practice can be performed with a few steps and no servers 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.

“ It’s vital to consider that AWS Auto Scaling is the same as Load Balancer, it’s common to confuse these two terms.”

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: Setup AWS Application Load balancing, define a threshold for triggering the autoscaling event on AWS CloudWatch, determine a Min/Max servers amount, set an AWS Auto scaling 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, it’s a database managed service, which 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 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 the high-performance database from AWS, which combines high speed, high availability, and performance. According to AWS, Aurora it’s 5X faster than a standard MySql or 3X faster than PostgreSQL.

“Amazon Aurora is the 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 our “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 to introduce the application Load Balancing (ALB), which is a layer 7 LB; It has multiple benefits, these include, 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.

With that being said, I recommend to architect 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, API’s, and any web socket. Lastly, It’s evident that the ALB was natively built for micro-service environments with Docker, AWS ECS, and Kubernetes, but it can also be used with a monolithic approach, as presented on this architecture.

Practice 5. CloudFront CDN

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

Amazon CloudFront CDN, is an amazing component with numerous features to highlight and collaborates commonly along with Amazon S3. Amazon CloudFront, it’s a Content Delivery network, aimed to cache content, distribute requests, serve video content, and much 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 coming from the Amazon S3 or EC2 (origins).
  • It helps reduce AWS bandwidth costs coming from the amazon s3 due to its caching magic.
  • Similarly, It’s used as a video hosting solution for Media/Video streaming.
  • It’s built to improve application performance and scalability by granting low latency.
  • CloudFront can help to secure your back-end instances and filter common botnets/DDoS attacks. This is achieved with the help of an AWS WAF.
  • It decreases the load on web instances, enabling to use less AWS resources.
  • It has support for security certificates (SSL/TLS).

So, what’s the deal to integrate your Laravel application with CloudFront CDN? Mainly, 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).

As next, you need to create a CloudFront distribution where all content will be distributed across the edge locations; thus end-user will start getting cached. And that’s it, considering you have your Laravel code-base pointing to Amazon S3 – It should take you a few hours to setup 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 as well as robust subnets is essential to growing, architect and structure applications in multiple groups/departments. AWS Networking (Amazon VPC) has various features, including subnet creation, route tables, own IP ranges, network ACL’s, 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, it’s a caching and data storage system that is fully scalable, available and managed, aimed 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.

And more…

“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.

“Lambda is 100% No Operations (NoOps)”

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?

THAT’S IT! – We explored how AWS can be the key to scale laravel application and the Laravel architecture best practices and how AWS can help serve a million users by 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 are also applicable 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 to the AWS cloud, you have joined the journey to the continuous digital transformation that the AWS cloud is pulling us by inertia.

Do you want to know more about Laravel 6? Check it out! What’s new in Laravel 6? Feautres, benefits, and serverless introduction.

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

Why choose ClickIT

Subscribe

to our newsletter

Table of Contents

We Make DevOps Easier

Weekly DevOps Newsletter

Subscribe to our DevOps News

Subscribe to a monthly newsletter to receive the IT best practices, startup-related insights & emerging technologies.

Join hundreds of business leaders and entrepreneurs, who are part of our growing tech community.

We guarantee 100% privacy. Your information will not be shared.

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.