<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Hermann D. Schimpf</title>
    <description>The latest articles on DEV Community by Hermann D. Schimpf (@hschimpf).</description>
    <link>https://dev.to/hschimpf</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F362439%2F3a5cf3f4-d2a1-4438-9369-0b42c69bba2a.png</url>
      <title>DEV Community: Hermann D. Schimpf</title>
      <link>https://dev.to/hschimpf</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/hschimpf"/>
    <language>en</language>
    <item>
      <title>How I Managed to Take My Laravel Application to the Serverless World (And How I Almost Died Trying)</title>
      <dc:creator>Hermann D. Schimpf</dc:creator>
      <pubDate>Tue, 01 Apr 2025 18:18:57 +0000</pubDate>
      <link>https://dev.to/hschimpf/how-i-managed-to-take-my-laravel-application-to-the-serverless-world-and-how-i-almost-died-trying-3mhd</link>
      <guid>https://dev.to/hschimpf/how-i-managed-to-take-my-laravel-application-to-the-serverless-world-and-how-i-almost-died-trying-3mhd</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Versión en español &lt;a href="https://dev.to/hschimpf/como-logre-llevar-mi-aplicacion-laravel-al-mundo-serverless-y-como-casi-muero-en-el-intento-4b1h"&gt;aquí&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;In the &lt;a href="https://dev.to/hschimpf/why-i-migrated-my-laravel-app-to-aws-serverless-and-why-it-could-save-you-time-and-money-dem"&gt;first chapter&lt;/a&gt; of this journey, we explored why migrating to AWS Serverless was the best decision for my Laravel application. We talked about automatic scalability, cost savings, and freedom from traditional maintenance. But like in every great adventure, the path has its obstacles.&lt;/p&gt;

&lt;p&gt;One of the concerns shared by most readers is that since &lt;em&gt;serverless&lt;/em&gt; does all the magic for you and scales automatically, your wallet would also need to do so.&lt;/p&gt;

&lt;p&gt;And I must be honest with you: I fell into the trap of the &lt;em&gt;magical serverless&lt;/em&gt;. While I celebrated the absence of servers, my code wandered through the cloud like a tourist with an unlimited credit card: enthusiastic, but wasting resources at every step.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;But hey! That's why I'm here today—to reveal what no tutorial warned me about: the art of writing PHP conscious of Lambda.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's dive into how to turn our Laravel application into a true &lt;em&gt;serverless&lt;/em&gt; warrior. Yes, we will tackle the necessary optimizations and the precautions we must take.&lt;/p&gt;

&lt;p&gt;But let's start lightly with some new concepts.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. The Serverless Magic
&lt;/h2&gt;

&lt;h3&gt;
  
  
  a) Lambda: The Execution Chef
&lt;/h3&gt;

&lt;p&gt;AWS Lambda is, in short, the chef that cooks your code just when needed. Its event-driven model means it only activates upon requests (HTTP, SQS events, cron jobs, etc.), and like an a la carte kitchen, you only pay for the time the stove is used. Additionally, Lambda's free tier allows you to start without worries, as long as you keep an eye on usage limits.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;But&lt;/strong&gt;: Did you know that AWS Lambda, among all the languages it &lt;a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html#runtimes-supported" rel="noopener noreferrer"&gt;natively supports&lt;/a&gt;, PHP is not one of them?&lt;/em&gt; 😤&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For our peace of mind, Lambda allows us to define our own &lt;a href="https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html" rel="noopener noreferrer"&gt;custom runtimes&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  b) Bref: The Bridge that Connects PHP and Lambda
&lt;/h3&gt;

&lt;p&gt;Although I'd love to have created my own solution to run PHP on Lambda like some suggested &lt;em&gt;(and thanks in advance for trusting my abilities so much)&lt;/em&gt;, sometimes it's not necessary to reinvent the wheel.&lt;/p&gt;

&lt;p&gt;That's where Bref comes in, an essential tool that allows us to run PHP applications on Lambda without rewriting all our code.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Great! But, how does it work?&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Personally, I love knowing the &lt;a href="https://bref.sh/docs/how-it-works" rel="noopener noreferrer"&gt;inner workings&lt;/a&gt; of things, but to keep it simple, Bref operates as follows:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg61e9thmubexsvtbgq63.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg61e9thmubexsvtbgq63.png" alt="API Gateway → Lambda → Bref → Laravel" width="800" height="270"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When a request enters your application, it is captured by API Gateway and sent to the Lambda function, where Bref's runtime starts PHP-FPM in the background and redirects the request via FastCGI. Once the result is obtained, it is returned to API Gateway, which in turn sends it as a response to the end user.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Simple, right?&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  c) Serverless Framework: The Glue That Binds All Components
&lt;/h3&gt;

&lt;p&gt;Can you imagine the amount of configurations needed to set up a Lambda function with a custom runtime that runs Bref (and with it, PHP-FPM) so that your Laravel code can work?&lt;/p&gt;

&lt;p&gt;Well, you can relax: the Serverless framework does all that for you. You just need to define the necessary components in a &lt;code&gt;serverless.yml&lt;/code&gt; configuration file and, with a simple &lt;code&gt;serverless deploy&lt;/code&gt;, you're in the cloud! 🚀&lt;/p&gt;




&lt;h2&gt;
  
  
  2. Preparing Laravel for the Serverless Jungle
&lt;/h2&gt;

&lt;p&gt;First, you need to understand that migrating to a &lt;em&gt;serverless&lt;/em&gt; environment means that Laravel must go into &lt;em&gt;"nomadic mode"&lt;/em&gt;. This means adapting it to be &lt;strong&gt;stateless&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Do you remember when I mentioned that Lambda is ephemeral? The simplest way to imagine Lambda is like talking to someone with a very short memory: every time you start the conversation, you have to reintroduce yourself &lt;em&gt;(e.g., session data)&lt;/em&gt;. Do you give him a notebook to write something down and then return it to you &lt;em&gt;(file uploads)&lt;/em&gt;? Forget about it, you won't even find it in the &lt;em&gt;limbo&lt;/em&gt; of Inception.&lt;/p&gt;

&lt;p&gt;So, some essential adjustments are necessary:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Logs to stderr:&lt;/strong&gt; You don't have SSH access to Lambda, so you need to store logs in CloudWatch.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Read-only storage:&lt;/strong&gt; The file system in Lambda is read-only, except for the &lt;code&gt;/tmp&lt;/code&gt; directory. So, file uploads need to be stored in S3 &lt;em&gt;(or similar)&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sessions:&lt;/strong&gt; You need to move session data to &lt;em&gt;cookies&lt;/em&gt; or, better yet, use DynamoDB for a more robust solution.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cache:&lt;/strong&gt; For simplicity, we'll opt for DynamoDB.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Environment variables:&lt;/strong&gt; Forget about the &lt;code&gt;.env&lt;/code&gt; file in production; you'll need to use variables defined in the &lt;code&gt;serverless.yml&lt;/code&gt; configuration file.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Bref's Survival Kit
&lt;/h3&gt;

&lt;p&gt;To make these adjustments easier, the Bref community has created a package called &lt;code&gt;bref/laravel-bridge&lt;/code&gt; that automates most of the changes mentioned above.&lt;/p&gt;

&lt;h3&gt;
  
  
  Getting Our Hands Dirty: Transforming Laravel into a Cloud Nomad
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;It's time to get our hands dirty.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you want to follow along step by step, the requirements from this point on are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;PHP &lt;em&gt;(obviously!)&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;Composer &lt;sup id="fnref1"&gt;1&lt;/sup&gt;
&lt;/li&gt;
&lt;li&gt;Node.js &lt;sup id="fnref2"&gt;2&lt;/sup&gt;
&lt;/li&gt;
&lt;li&gt;serverless &lt;sup id="fnref3"&gt;3&lt;/sup&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's start by creating a new Laravel project &lt;sup id="fnref4"&gt;4&lt;/sup&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Installing Laravel&lt;/span&gt;
laravel new laravel-above-the-clouds
&lt;span class="nb"&gt;cd &lt;/span&gt;laravel-above-the-clouds

&lt;span class="c"&gt;# Create and migrate the database (sqlite by default)&lt;/span&gt;
php artisan migrate

&lt;span class="c"&gt;# Install Node.js packages (Vite.js, Tailwind CSS, etc.) and compile assets&lt;/span&gt;
npm &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; npm run build
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Install the &lt;code&gt;bref/bref&lt;/code&gt; and &lt;code&gt;bref/laravel-bridge&lt;/code&gt; packages &lt;sup id="fnref5"&gt;5&lt;/sup&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer require bref/bref bref/laravel-bridge &lt;span class="nt"&gt;--update-with-dependencies&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;bref/laravel-bridge&lt;/code&gt; package, as I mentioned earlier, resolves the necessary adjustments for Laravel to work in a &lt;em&gt;serverless&lt;/em&gt; environment.&lt;/p&gt;

&lt;p&gt;Bref already includes a preconfigured &lt;code&gt;serverless.yml&lt;/code&gt; file that we can use as a starting point for our first deploy:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;php artisan vendor:publish &lt;span class="nt"&gt;--tag&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;serverless-config
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Think of the &lt;code&gt;serverless.yml&lt;/code&gt; file as a set of LEGO instructions for AWS: it's the guide that allows you to set up your application flawlessly.&lt;/p&gt;

&lt;p&gt;Deploy the project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;serverless deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff7bikbq8q3jytzzmd98x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff7bikbq8q3jytzzmd98x.png" alt="serverless deploy output" width="800" height="244"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;When finishes, in the console you will get the API Gateway URL to access your application on AWS!&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  3. But, what happened with my CSS?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F58ahujvwwlydz8v4j3d5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F58ahujvwwlydz8v4j3d5.png" alt="first request, 404 on assets" width="800" height="472"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The first thing you'll notice is that the assets (CSS and JS) don't load correctly. This happens because, in a &lt;em&gt;serverless&lt;/em&gt; environment, we don't have Apache or Nginx to serve static assets; and here I want to make a brief pause.&lt;/p&gt;

&lt;p&gt;Taking our application to a &lt;em&gt;serverless&lt;/em&gt; environment implies changing our mind-set that a single server is responsible for performing all the tasks to make our application work. In a &lt;em&gt;serverless&lt;/em&gt; environment, each component must be managed by a specialized service.&lt;/p&gt;

&lt;p&gt;In our case, some of the main components in a Laravel application are as follows:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Component&lt;/th&gt;
&lt;th&gt;Servidor Dedicated Server&lt;/th&gt;
&lt;th&gt;AWS Serverless&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Routes, Controllers, ...&lt;/td&gt;
&lt;td&gt;PHP-FPM&lt;/td&gt;
&lt;td&gt;Lambda&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Static Assets &lt;em&gt;(images, javascript, css)&lt;/em&gt;
&lt;/td&gt;
&lt;td&gt;Apache / Nginx&lt;/td&gt;
&lt;td&gt;S3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Session Data&lt;/td&gt;
&lt;td&gt;Database / Cookies&lt;/td&gt;
&lt;td&gt;RDS / DynamoDB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cache&lt;/td&gt;
&lt;td&gt;Local Disk&lt;/td&gt;
&lt;td&gt;DynamoDB / Redis&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;File Upload&lt;/td&gt;
&lt;td&gt;Local Disk&lt;/td&gt;
&lt;td&gt;S3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Scheduled Tasks &lt;em&gt;(Schedule)&lt;/em&gt;
&lt;/td&gt;
&lt;td&gt;crontab&lt;/td&gt;
&lt;td&gt;EventBridge&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Event Queue&lt;/td&gt;
&lt;td&gt;SSH $ &lt;code&gt;php artisan queue:work&lt;/code&gt; / maybe supervisor&lt;/td&gt;
&lt;td&gt;SQS&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;artisan&lt;/code&gt; Commands&lt;/td&gt;
&lt;td&gt;SSH $ &lt;code&gt;php artisan ...&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Lambda&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Application Log&lt;/td&gt;
&lt;td&gt;SSH $ &lt;code&gt;tail -f storage/logs/*&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;CloudWatch&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;But let's take it easy, solving one point at a time.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  From Complexity to Simplicity: Serverless Orchestration
&lt;/h3&gt;

&lt;p&gt;From the points mentioned, the &lt;code&gt;bref/laravel-bridge&lt;/code&gt; package already solves application logs and session data. A log group is created in CloudWatch for application logs, and session data is stored in cookies &lt;em&gt;(we will later see how to move session data to DynamoDB)&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;To serve static assets, we have two alternatives:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The hard way:&lt;/strong&gt; Add the creation of a S3 Bucket to our &lt;code&gt;serverless.yml&lt;/code&gt; configuration, obtain the bucket name, build the public URL, and assign it to the &lt;code&gt;ASSET_URL&lt;/code&gt; environment variable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The easy way:&lt;/strong&gt; Use the &lt;code&gt;serverless-lift&lt;/code&gt; plugin &lt;sup id="fnref6"&gt;6&lt;/sup&gt;, and let the magic flow.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Although I learned a lot the hard way &lt;em&gt;(I've been following Bref's growth since 2020 &lt;sup id="fnref7"&gt;7&lt;/sup&gt;)&lt;/em&gt;, you can take advantage of community-developed tools that simplify our lives.&lt;/p&gt;

&lt;p&gt;We install the &lt;code&gt;serverless-lift&lt;/code&gt; plugin and add a new section &lt;sup id="fnref8"&gt;8&lt;/sup&gt; within the &lt;code&gt;serverless.yml&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;serverless plugin &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-n&lt;/span&gt; serverless-lift
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight diff"&gt;&lt;code&gt;&lt;span class="p"&gt;service: laravel
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="p"&gt;functions:
&lt;/span&gt;  web:
    handler: public/index.php
    runtime: php-82-fpm
&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;  artisan:
    handler: artisan
    runtime: php-82-console
&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gi"&gt;+ constructs:
+   website:
+     type: server-side-website
+     assets:
+       '/build/*': public/build
+       # Add here any file or directory that needs to be served from S3
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="p"&gt;plugins:
&lt;/span&gt;  - ./vendor/bref/bref
&lt;span class="gi"&gt;+   - serverless-lift
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Within the &lt;code&gt;constructs&lt;/code&gt; section, we have defined a &lt;code&gt;website&lt;/code&gt; component of type &lt;code&gt;server-side-website&lt;/code&gt;. This tells the &lt;code&gt;serverless-lift&lt;/code&gt; plugin to create a &lt;strong&gt;CloudFront&lt;/strong&gt; distribution, which will act as a CDN to serve static files from an S3 Bucket, and also as a reverse proxy, redirecting requests to your PHP application's routes through API Gateway =&amp;gt; Lambda.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmp3emi5unpl6e42nzrpt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmp3emi5unpl6e42nzrpt.png" alt="Serverless with CloudFront" width="694" height="417"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;serverless deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;This deployment will take an additional 5-7 minutes only once, as CloudFront distributions are created globally. Subsequent deployments will be faster, as long as you don't modify configurations that affect the CloudFront distribution.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In the console output, you will see that you now have two URLs, one from the API Gateway &lt;em&gt;(which we will no longer use)&lt;/em&gt;, and another from CloudFront, which will serve static assets from the S3 Bucket, and the rest of the routes will be processed by Lambda.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8cujunv9ntlahiwtv3ie.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8cujunv9ntlahiwtv3ie.png" alt="serverless deploy output with CloudFront" width="800" height="266"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And now the CSS loads correctly! Congratulations, you have deployed your first Laravel application in a &lt;em&gt;serverless&lt;/em&gt; environment.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkjiyh2926gopiitc9jwt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkjiyh2926gopiitc9jwt.png" alt="Laravel on AWS Serverless" width="800" height="642"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  4. Optimizing for the Real World: The Battle Against Cold-Start
&lt;/h2&gt;

&lt;p&gt;You may have noticed that the first time you accessed your application, it took a few extra seconds to respond.&lt;/p&gt;

&lt;p&gt;As I mentioned in the previous article, this is called a &lt;em&gt;cold-start&lt;/em&gt; and occurs when Lambda initializes a new instance to run your application. This initialization can take 250ms or more, especially if your application is large.&lt;/p&gt;

&lt;p&gt;Lambda keeps an instance alive for up to 10 minutes after processing a request, then it is automatically destroyed.&lt;/p&gt;

&lt;p&gt;We can address this from several fronts.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) Keep a Lambda instance always alive &lt;sup id="fnref9"&gt;9&lt;/sup&gt;
&lt;/h3&gt;

&lt;p&gt;In low-traffic applications, it is normal to have periods of inactivity greater than 10 minutes, so we may have a higher percentage of requests processed in a &lt;em&gt;cold-start&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Bref provides a special event that we can use to keep a Lambda instance alive. We simply need to add a &lt;code&gt;schedule&lt;/code&gt; event in our &lt;code&gt;serverless.yml&lt;/code&gt; configuration file with the payload &lt;code&gt;{warmer: true}&lt;/code&gt;. Bref will recognize this special event and respond instantly with status code 100 &lt;sup id="fnref10"&gt;10&lt;/sup&gt; without executing your code, thus keeping the instance alive.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight diff"&gt;&lt;code&gt;&lt;span class="p"&gt;service: laravel
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="p"&gt;functions:
&lt;/span&gt;  web:
    handler: public/index.php
    runtime: php-82-fpm
    events:
      - httpApi: '*'
&lt;span class="gi"&gt;+       - schedule:
+         rate: rate(5 minutes)
+         input:
+           warmer: true
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  b) Reducing the size of your application
&lt;/h3&gt;

&lt;p&gt;During a cold-start, AWS Lambda downloads the application package, decompresses it in a temporary environment, and loads the runtime with all the necessary dependencies and configurations. This process, although optimized, adds latency to the first request. Therefore, reducing the package size (for example, by removing development dependencies or unnecessary modules) can significantly shorten this time.&lt;/p&gt;

&lt;p&gt;The default &lt;code&gt;serverless.yml&lt;/code&gt; file from Bref already ignores certain directories that are not necessary in PHP, such as &lt;code&gt;node_modules&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Development packages
&lt;/h4&gt;

&lt;p&gt;Before deploying, we can uninstall development packages. This will significantly reduce the size of the &lt;code&gt;vendor&lt;/code&gt; directory, and consequently, the total size of the code sent to Lambda.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;--no-dev&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  AWS Services dependencies
&lt;/h4&gt;

&lt;p&gt;In most of my applications, the composer package that takes up the most space is &lt;code&gt;aws/aws-sdk-php&lt;/code&gt; &lt;em&gt;(required by &lt;code&gt;bref/laravel-bridge&lt;/code&gt;)&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The good news is that the community has developed a composer script to clean up unused AWS service packages in our application &lt;sup id="fnref11"&gt;11&lt;/sup&gt;. We just need to specify the services we use in the &lt;code&gt;composer.json&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight diff"&gt;&lt;code&gt;{
  "name": "laravel/laravel",
  "type": "project",
  ...
  "require": {
    "php": "^8.2",
    "bref/bref": "^2.3",
    "bref/laravel-bridge": "^2.5",
    "laravel/framework": "^11.31",
    "laravel/octane": "^2.8",
    ...
  },
  "scripts": {
&lt;span class="gi"&gt;+     "pre-autoload-dump": "Aws\\Script\\Composer\\Composer::removeUnusedServices",
&lt;/span&gt;    "post-autoload-dump": [
      "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
      "@php artisan package:discover --ansi"
    ],
    ...
  },
  "extra": {
    "laravel": {
      "dont-discover": []
    },
&lt;span class="gi"&gt;+     "aws/aws-sdk-php": [
+       "DynamoDb",
+       "S3",
+       "Sqs"
+     ]
&lt;/span&gt;  },
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The cleanup script will run every time you run &lt;code&gt;composer install&lt;/code&gt; or &lt;code&gt;composer update&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  c) Boosting Performance with Laravel Octane
&lt;/h3&gt;

&lt;p&gt;Even when &lt;em&gt;cold-starts&lt;/em&gt; occur, Laravel Octane kicks in to keep the application in memory and significantly reduce response times. By avoiding a full Laravel boot on each request, the user experience is greatly improved.&lt;/p&gt;

&lt;p&gt;Laravel Octane acts as an accelerator that "keeps the application warm". Once Lambda initializes the application, Octane takes care of keeping it in memory, so that subsequent requests can be served almost instantly. It's like starting a car engine and leaving it ready to go at any moment, rather than starting it from scratch each time.&lt;/p&gt;

&lt;p&gt;Steps to implement Laravel Octane:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer require laravel/octane
php artisan octane:install
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once installed, update the &lt;code&gt;serverless.yml&lt;/code&gt; file to use Laravel Octane as the handler &lt;sup id="fnref12"&gt;12&lt;/sup&gt;. This will ensure that your application runs with the improved performance that Laravel Octane offers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight diff"&gt;&lt;code&gt;&lt;span class="p"&gt;service: laravel
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="p"&gt;functions:
&lt;/span&gt;  web:
    handler: Bref\LaravelBridge\Http\OctaneHandler
    runtime: php-82
&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, deploy your application with the changes made:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;serverless deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  d) Metrics that Validate Progress
&lt;/h3&gt;

&lt;p&gt;Applying all the improvements mentioned, we have reduced the initialization time &lt;em&gt;(cold-start)&lt;/em&gt; of our application. And with Laravel Octane, we have not only improved the time of the &lt;em&gt;cold-start&lt;/em&gt;, but also improved the overall response time of our application.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;We can visualize the response times in the CloudWatch logs that were already configured automatically for us.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Cold-start &lt;strong&gt;without optimizations&lt;/strong&gt; &lt;em&gt;(499ms)&lt;/em&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fquieaec9z2cepjz0dazz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fquieaec9z2cepjz0dazz.png" alt="php-fpm coldstart" width="800" height="315"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Cold-start with &lt;strong&gt;Laravel Octane and optimizations&lt;/strong&gt; &lt;em&gt;(190ms)&lt;/em&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjfh1wtwucl0unkfq6q4k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjfh1wtwucl0unkfq6q4k.png" alt="Laravel Octane coldstart" width="800" height="255"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Note that when using Laravel Octane, Laravel execution is kept in memory, so be careful of memory leaks &lt;sup id="fnref13"&gt;13&lt;/sup&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  5. Falls and Lessons Learned: Errors Every Serverless Migrant Should Know
&lt;/h2&gt;

&lt;p&gt;You may have noticed that there is a function called &lt;code&gt;artisan&lt;/code&gt; in the &lt;code&gt;serverless.yml&lt;/code&gt; file. This function uses the &lt;em&gt;"console"&lt;/em&gt; version of the Bref runtime &lt;sup id="fnref14"&gt;14&lt;/sup&gt;, which allows us to run Laravel Artisan commands in AWS Lambda.&lt;/p&gt;

&lt;p&gt;Since we don't have SSH access to the Lambda instances, Bref provides a bridge to execute &lt;code&gt;cli&lt;/code&gt; commands using the &lt;code&gt;bref:cli&lt;/code&gt; command from &lt;em&gt;serverless&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;serverless bref:cli &lt;span class="nt"&gt;--args&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"&amp;lt;artisan command and its options&amp;gt;"&lt;/span&gt;
serverless bref:cli &lt;span class="nt"&gt;--args&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"route:list"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Optimizations
&lt;/h3&gt;

&lt;p&gt;A very important point I want to reinforce is that we must change our mentality when developing applications for &lt;em&gt;serverless&lt;/em&gt; environments. In this new paradigm, it is crucial to design our processes and workflows considering the unique characteristics of &lt;em&gt;serverless&lt;/em&gt; computing, such as the ephemeral nature of functions and the billing model based on usage.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Serverless is not expensive... but poorly adapted code is.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In my first month migrating one of my applications to a &lt;em&gt;serverless&lt;/em&gt; environment, I made the mistake of not thoroughly reviewing certain processes. One of them was responsible for synchronizing the products of the online store with an external billing system, including updating product images. And as I mentioned in the previous article, some processes are not ideal for execution in a &lt;em&gt;serverless&lt;/em&gt; environment. In this case, I was paying for idle time, during the image download, my code in Lambda was not doing anything more than waiting 5-8 seconds per image. With 65,000 items in the store and two daily synchronizations, this resulted in a bill of &lt;strong&gt;~$530&lt;/strong&gt; just for the idle time during image download.&lt;/p&gt;

&lt;p&gt;This incident led me to redesign the synchronization process. In a first attempt at optimization, I implemented the download of multiple images in parallel using PHP ZTS, which led me to develop the &lt;code&gt;hds-solutions/parallel-sdk&lt;/code&gt; library &lt;sup id="fnref15"&gt;15&lt;/sup&gt;. This version reduced costs to &lt;strong&gt;~160$&lt;/strong&gt;, but it was still not enough; my goal was to have costs below what I was spending originally on EC2.&lt;/p&gt;

&lt;p&gt;In a second attempt, I moved the image download process to a dedicated EC2 instance. Although this significantly reduced costs to &lt;strong&gt;~50$&lt;/strong&gt;, the application was divided into two separate components.&lt;/p&gt;

&lt;p&gt;Finally, in the third version of the synchronization process, after talking to the client, I implemented a small script on the billing system server. Instead of my application downloading the images, this script sent the images directly from the billing system server to S3 using pre-signed URLs &lt;sup id="fnref16"&gt;16&lt;/sup&gt;. This eliminated the costs associated with image download, leaving only the cost of S3 storage.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. What's Next?
&lt;/h2&gt;

&lt;p&gt;With this, we close another chapter in our journey to the &lt;em&gt;serverless&lt;/em&gt; world! Today, we saw how to transform Laravel into a true cloud nomad, adapting it to live without the weight of a traditional server. But this is just the beginning.&lt;/p&gt;

&lt;p&gt;In the next article, we'll dive into the heart of integration: we'll see how to transfer session and cache data to DynamoDB, how to use S3 for file management, configure SQS for queuing and use EventBridge to orchestrate scheduled tasks. See you in the next part!&lt;/p&gt;




&lt;p&gt;In the meantime, have you migrated your Laravel application to &lt;em&gt;serverless&lt;/em&gt;? Share your experiences in the comments! And for those who haven't, I encourage you to experiment with what we've implemented so far and share your doubts and experiences.&lt;/p&gt;




&lt;ol&gt;

&lt;li id="fn1"&gt;
&lt;p&gt;&lt;a href="https://getcomposer.org/download" rel="noopener noreferrer"&gt;https://getcomposer.org/download&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn2"&gt;
&lt;p&gt;&lt;a href="https://github.com/nvm-sh/nvm#installation-and-update" rel="noopener noreferrer"&gt;https://github.com/nvm-sh/nvm#installation-and-update&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn3"&gt;
&lt;p&gt;&lt;a href="https://www.serverless.com/framework/docs/getting-started" rel="noopener noreferrer"&gt;https://www.serverless.com/framework/docs/getting-started&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn4"&gt;
&lt;p&gt;&lt;a href="https://laravel.com/docs/installation" rel="noopener noreferrer"&gt;https://laravel.com/docs/installation&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn5"&gt;
&lt;p&gt;&lt;a href="https://bref.sh/docs/laravel/getting-started" rel="noopener noreferrer"&gt;https://bref.sh/docs/laravel/getting-started&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn6"&gt;
&lt;p&gt;&lt;a href="https://bref.sh/docs/use-cases/websites" rel="noopener noreferrer"&gt;https://bref.sh/docs/use-cases/websites&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn7"&gt;
&lt;p&gt;&lt;a href="https://github.com/brefphp/bref/releases/tag/0.5.20" rel="noopener noreferrer"&gt;https://github.com/brefphp/bref/releases/tag/0.5.20&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn8"&gt;
&lt;p&gt;&lt;a href="https://github.com/getlift/lift/blob/master/docs/server-side-website.md" rel="noopener noreferrer"&gt;https://github.com/getlift/lift/blob/master/docs/server-side-website.md&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn9"&gt;
&lt;p&gt;&lt;a href="https://bref.sh/docs/use-cases/http/advanced-use-cases#cold-starts" rel="noopener noreferrer"&gt;https://bref.sh/docs/use-cases/http/advanced-use-cases#cold-starts&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn10"&gt;
&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/100" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/100&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn11"&gt;
&lt;p&gt;&lt;a href="https://github.com/aws/aws-sdk-php/tree/master/src/Script/Composer" rel="noopener noreferrer"&gt;https://github.com/aws/aws-sdk-php/tree/master/src/Script/Composer&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn12"&gt;
&lt;p&gt;&lt;a href="https://bref.sh/docs/laravel/octane" rel="noopener noreferrer"&gt;https://bref.sh/docs/laravel/octane&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn13"&gt;
&lt;p&gt;&lt;a href="https://laravel.com/docs/11.x/octane#managing-memory-leaks" rel="noopener noreferrer"&gt;https://laravel.com/docs/11.x/octane#managing-memory-leaks&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn14"&gt;
&lt;p&gt;&lt;a href="https://bref.sh/docs/runtimes/console" rel="noopener noreferrer"&gt;https://bref.sh/docs/runtimes/console&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn15"&gt;
&lt;p&gt;&lt;a href="https://github.com/hschimpf/parallel-sdk" rel="noopener noreferrer"&gt;https://github.com/hschimpf/parallel-sdk&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn16"&gt;
&lt;p&gt;&lt;a href="https://docs.aws.amazon.com/es_es/AmazonS3/latest/userguide/PresignedUrlUploadObject.html" rel="noopener noreferrer"&gt;https://docs.aws.amazon.com/es_es/AmazonS3/latest/userguide/PresignedUrlUploadObject.html&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;/ol&gt;

</description>
      <category>laravel</category>
      <category>php</category>
      <category>serverless</category>
      <category>aws</category>
    </item>
    <item>
      <title>Como Logré Llevar Mi Aplicación Laravel al Mundo Serverless (Y como casi muero en el intento)</title>
      <dc:creator>Hermann D. Schimpf</dc:creator>
      <pubDate>Tue, 11 Mar 2025 22:36:10 +0000</pubDate>
      <link>https://dev.to/hschimpf/como-logre-llevar-mi-aplicacion-laravel-al-mundo-serverless-y-como-casi-muero-en-el-intento-4b1h</link>
      <guid>https://dev.to/hschimpf/como-logre-llevar-mi-aplicacion-laravel-al-mundo-serverless-y-como-casi-muero-en-el-intento-4b1h</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;English version &lt;a href="https://dev.to/hschimpf/how-i-managed-to-take-my-laravel-application-to-the-serverless-world-and-how-i-almost-died-trying-3mhd"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;En el &lt;a href="https://dev.to/hschimpf/por-que-migre-mi-aplicacion-laravel-a-aws-serverless-y-por-que-podria-ahorrarte-tiempo-y-dinero-6hp"&gt;primer capítulo&lt;/a&gt; de esta travesía, exploramos por qué migrar a AWS Serverless fue la mejor decisión para mi aplicación Laravel. Hablamos de escalabilidad automática, ahorro de costos y libertad del mantenimiento tradicional. Pero como en toda gran aventura, el camino tiene sus obstáculos.&lt;/p&gt;

&lt;p&gt;Una de las preocupaciones que compartieron la mayoría de los lectores es que, dado que &lt;em&gt;serverless&lt;/em&gt; hace toda la magia por ustedes y escala automáticamente, su billetera también tendría que hacerlo.&lt;/p&gt;

&lt;p&gt;Y debo ser sincero con ustedes: caí en la trampa del &lt;em&gt;serverless&lt;/em&gt; mágico. Mientras yo celebraba la ausencia de servidores, mi código se paseaba por la nube como un turista con tarjeta de crédito ilimitada: entusiasta, pero derrochando recursos a cada paso.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Pero hey! Para eso estoy hoy aquí—para revelarles lo que ningún tutorial me advirtió: el arte de escribir PHP consciente de Lambda.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Vamos a meternos de lleno en el cómo convertir nuestra aplicación Laravel en un verdadero guerrero &lt;em&gt;serverless&lt;/em&gt;. Sí, atacaremos las optimizaciones necesarias y las precauciones que debemos tener.&lt;/p&gt;

&lt;p&gt;Pero empecemos liviano con algunos conceptos nuevos.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. La Magia Serverless
&lt;/h2&gt;

&lt;h3&gt;
  
  
  a) Lambda: El Chef de la Ejecución
&lt;/h3&gt;

&lt;p&gt;AWS Lambda es, en pocas palabras, el chef que cocina el código justo cuando se le necesita. Su modelo basado en eventos significa que solo se activa ante solicitudes (HTTP, eventos de SQS, cron jobs, etc.) y, como en una cocina a la carta, solo pagan por el tiempo que se utiliza la estufa. Además, el nivel gratuito de Lambda les permite arrancar sin preocupaciones, siempre y cuando mantengan un ojo en los límites de uso.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;Pero&lt;/strong&gt;: ¿sabían que AWS Lambda, entre todos los lenguajes que &lt;a href="https://docs.aws.amazon.com/es_es/lambda/latest/dg/lambda-runtimes.html#runtimes-supported" rel="noopener noreferrer"&gt;soporta nativamente&lt;/a&gt; nativamente, PHP no es uno de ellos?&lt;/em&gt; 😤&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Para nuestra tranquilidad, Lambda permite definir nuestros propios &lt;a href="https://docs.aws.amazon.com/es_es/lambda/latest/dg/runtimes-custom.html" rel="noopener noreferrer"&gt;runtimes personalizados&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  b) Bref: El Puente que une PHP y Lambda
&lt;/h3&gt;

&lt;p&gt;Aunque me encantaría haber creado mi propia solución para ejecutar PHP en Lambda como sugirieron algunos &lt;em&gt;(y gracias de antemano por confiar tanto en mis capacidades)&lt;/em&gt;, a veces no es necesario reinventar la rueda.&lt;/p&gt;

&lt;p&gt;Aquí es donde entra Bref, una herramienta esencial que nos permite ejecutar aplicaciones PHP en Lambda sin reescribir todo nuestro código.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;¡Buenísimo! Pero, ¿cómo funciona?&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Personalmente, me encanta conocer a fondo el &lt;a href="https://bref.sh/docs/how-it-works" rel="noopener noreferrer"&gt;funcionamiento interno&lt;/a&gt; de las cosas, pero para mantener la simplicidad, Bref opera de la siguiente manera:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg61e9thmubexsvtbgq63.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg61e9thmubexsvtbgq63.png" alt="API Gateway → Lambda → Bref → Laravel" width="800" height="270"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Cuando una solicitud ingresa a tu aplicación, esta es capturada por API Gateway y enviada a ejecución en la función Lambda, donde el runtime de Bref inicia PHP-FPM en background y la redigire la solicitud vía FastCGI. Una vez obtenido el resultado, lo devuelve al API Gateway, para que a su vez sea enviado finalmente como respuesta al usuario final.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;¿Simple, cierto?&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  c) Serverless Framework: El Pegamento que Une Todos los Componentes
&lt;/h3&gt;

&lt;p&gt;¿Se imaginan la cantidad de configuraciones que necesitan realizar para poner en marcha una función Lambda, con un runtime personalizado, que ejecute Bref (y con éste, PHP-FPM) para que tu código Laravel pueda funcionar?&lt;/p&gt;

&lt;p&gt;Pues ya puedes relajarte: el framework Serverless hace todo eso por ustedes. Solo tienen que definir los componentes necesarios en un fichero de configuración &lt;code&gt;serverless.yml&lt;/code&gt; y, con un simple &lt;code&gt;serverless deploy&lt;/code&gt;, ¡ya están en la nube! 🚀&lt;/p&gt;




&lt;h2&gt;
  
  
  2. Preparando Laravel para la Jungla Serverless
&lt;/h2&gt;

&lt;p&gt;Primero deben entender que migrar a un entorno &lt;em&gt;serverless&lt;/em&gt; implica que Laravel debe ponerse en &lt;em&gt;"modo nómada"&lt;/em&gt;. Esto significa adaptarlo para que sea &lt;strong&gt;stateless&lt;/strong&gt; &lt;em&gt;(sin estado)&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;¿Recuerdan que mencioné que Lambda es efímero? La forma más simple de imaginar Lambda es como conversar con alguien que tiene una memoria muy corta: cada vez que inician la conversación, tienen que volver a presentarte &lt;em&gt;(por ej, los datos de sesión)&lt;/em&gt;. ¿Le dan un cuaderno para que les anote algo y luego se lo devuelva &lt;em&gt;(upload de archivos)&lt;/em&gt;? Olvídenlo, ni en el &lt;em&gt;limbo&lt;/em&gt; de Inception lo encontrarán.&lt;/p&gt;

&lt;p&gt;Por lo tanto, es necesario realizar algunos ajustes esenciales:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Logs a stderr:&lt;/strong&gt; No tienen acceso SSH a Lambda, por lo que deben hacer que los logs se almacenen en CloudWatch.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Almacenamiento de solo lectura:&lt;/strong&gt; El sistema de archivos en Lambda es de solo lectura, a excepción del directorio &lt;code&gt;/tmp&lt;/code&gt;. Por lo que la subida de archivos debe ser almacenada en S3 &lt;em&gt;(o similar)&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sesiones:&lt;/strong&gt; Deben mover los datos de sesión a &lt;em&gt;cookies&lt;/em&gt; o, mejor aún, usar DynamoDB para una solución más robusta.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Caché:&lt;/strong&gt; Por simplicidad, optamos por DynamoDB.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Variables de entorno:&lt;/strong&gt; Olvídense del fichero &lt;code&gt;.env&lt;/code&gt; en producción; deberán utilizar variables definidas en el fichero de configuración &lt;code&gt;serverless.yml&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  El Kit de Supervivencia de Bref
&lt;/h3&gt;

&lt;p&gt;Para facilitar estos ajustes, la comunidad de Bref ha creado un paquete llamado &lt;code&gt;bref/laravel-bridge&lt;/code&gt; que automatiza la mayoría de los cambios mencionados anteriormente.&lt;/p&gt;

&lt;h3&gt;
  
  
  Manos a la Obra: Transformando Laravel en un Nómada Cloud
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Es hora de ensuciarnos las manos.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Si quieren ir siguiendo el paso a paso, los requisitos a partir de este punto son los siguientes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;PHP &lt;em&gt;(¡obviamente!)&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;Composer &lt;sup id="fnref1"&gt;1&lt;/sup&gt;
&lt;/li&gt;
&lt;li&gt;Node.js &lt;sup id="fnref2"&gt;2&lt;/sup&gt;
&lt;/li&gt;
&lt;li&gt;serverless &lt;sup id="fnref3"&gt;3&lt;/sup&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Empecemos creando un proyecto de Laravel nuevo &lt;sup id="fnref4"&gt;4&lt;/sup&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Instalación de Laravel&lt;/span&gt;
laravel new laravel-above-the-clouds
&lt;span class="nb"&gt;cd &lt;/span&gt;laravel-above-the-clouds

&lt;span class="c"&gt;# Creamos y migramos la base de datos (sqlite por defecto)&lt;/span&gt;
php artisan migrate

&lt;span class="c"&gt;# Instalamos los paquetes de Node.js (Vite.js, Tailwind CSS, etc.) y compilamos los assets&lt;/span&gt;
npm &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; npm run build
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instalamos los paquetes &lt;code&gt;bref/bref&lt;/code&gt; y &lt;code&gt;bref/laravel-bridge&lt;/code&gt; &lt;sup id="fnref5"&gt;5&lt;/sup&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer require bref/bref bref/laravel-bridge &lt;span class="nt"&gt;--update-with-dependencies&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;El paquete &lt;code&gt;bref/laravel-bridge&lt;/code&gt;, como mencioné anteriormente, resuelve los ajustes necesarios para que Laravel funcione en un ambiente &lt;em&gt;serverless&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Bref ya incluye un fichero de configuración &lt;code&gt;serverless.yml&lt;/code&gt; preconfigurado que podemos utilizar como base para nuestro primer deploy:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;php artisan vendor:publish &lt;span class="nt"&gt;--tag&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;serverless-config
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Piensen en el fichero &lt;code&gt;serverless.yml&lt;/code&gt; como las instrucciones de un set de LEGO para AWS: es la guía que le permite montar su aplicación de forma impecable.&lt;/p&gt;

&lt;p&gt;Realicen el deploy del proyecto:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;serverless deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff7bikbq8q3jytzzmd98x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ff7bikbq8q3jytzzmd98x.png" alt="serverless deploy output" width="" height=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Al finalizar, en la consola obtendrán la URL del API Gateway para acceder a su aplicación en AWS!&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  3. Pero, ¿qué ha pasado con mi CSS?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F58ahujvwwlydz8v4j3d5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F58ahujvwwlydz8v4j3d5.png" alt="first request, 404 on assets" width="800" height="472"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Lo primero que notarán es que los assets (CSS y JS) no cargan correctamente. Esto sucede porque, en un entorno &lt;em&gt;serverless&lt;/em&gt;, no disponemos de Apache o Nginx para servir los assets estáticos; y aquí quiero hacer una breve pausa.&lt;/p&gt;

&lt;p&gt;Llevar nuestra aplicación a un entorno &lt;em&gt;serverless&lt;/em&gt; implica cambiar nuestro mind-set de que un único servidor es responsable de realizar todas las tareas para hacer funcionar nuestra aplicación. En un entorno &lt;em&gt;serverless&lt;/em&gt;, cada componente debe ser gestionado por un servicio especializado.&lt;/p&gt;

&lt;p&gt;En nuestro caso, algunos de los componentes principales en una aplicación Laravel son los siguientes:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Componente&lt;/th&gt;
&lt;th&gt;Servidor Dedicado&lt;/th&gt;
&lt;th&gt;AWS Serverless&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Rutas, Controladores, ...&lt;/td&gt;
&lt;td&gt;PHP-FPM&lt;/td&gt;
&lt;td&gt;Lambda&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Assets estáticos &lt;em&gt;(imágenes, javascript, css)&lt;/em&gt;
&lt;/td&gt;
&lt;td&gt;Apache / Nginx&lt;/td&gt;
&lt;td&gt;S3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Datos de sesión&lt;/td&gt;
&lt;td&gt;Base de Datos / Cookies&lt;/td&gt;
&lt;td&gt;RDS / DynamoDB&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Caché&lt;/td&gt;
&lt;td&gt;Disco local&lt;/td&gt;
&lt;td&gt;DynamoDB / Redis&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Upload de archivos&lt;/td&gt;
&lt;td&gt;Disco local&lt;/td&gt;
&lt;td&gt;S3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Tareas programadas &lt;em&gt;(Schedule)&lt;/em&gt;
&lt;/td&gt;
&lt;td&gt;crontab&lt;/td&gt;
&lt;td&gt;EventBridge&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Cola de Eventos&lt;/td&gt;
&lt;td&gt;SSH $ &lt;code&gt;php artisan queue:work&lt;/code&gt; / quizás supervisor&lt;/td&gt;
&lt;td&gt;SQS&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Comandos &lt;code&gt;artisan&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;SSH $ &lt;code&gt;php artisan ...&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Lambda&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Log de Aplicación&lt;/td&gt;
&lt;td&gt;SSH $ &lt;code&gt;tail -f storage/logs/*&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;CloudWatch&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Pero vayamos con calma, resolviendo un punto a la vez.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  De la Complejidad a la Simplicidad: La Orquestación Serverless
&lt;/h3&gt;

&lt;p&gt;De los puntos mencionados, el paquete &lt;code&gt;bref/laravel-bridge&lt;/code&gt; ya resuelve el log de la aplicación y los datos de sesión. Se crea un grupo de logs en CloudWatch para los logs de aplicación, y los datos de sesión son almacenados en cookies &lt;em&gt;(más adelante veremos cómo llevar los datos de sesión a DynamoDB)&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Para poder servir los assets estáticos, tenemos dos alternativas:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;La difícil:&lt;/strong&gt; Agregar la creación de un Bucket S3 a nuestra configuración &lt;code&gt;serverless.yml&lt;/code&gt;, obtener el nombre del bucket, armar la URL pública y asignarla en la variable de entorno &lt;code&gt;ASSET_URL&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;La simple:&lt;/strong&gt; Utilizar el plugin &lt;code&gt;serverless-lift&lt;/code&gt; &lt;sup id="fnref6"&gt;6&lt;/sup&gt;, y dejar que la magia fluya.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Aunque aprendí mucho por el camino difícil &lt;em&gt;(vengo acompañando el crecimiento de Bref desde 2020 &lt;sup id="fnref7"&gt;7&lt;/sup&gt;)&lt;/em&gt;, ustedes pueden aprovechar que la comunidad ha desarrollado herramientas que nos simplifican la vida.&lt;/p&gt;

&lt;p&gt;Instalamos el plugin &lt;code&gt;serverless-lift&lt;/code&gt; y agregamos una nueva sección &lt;sup id="fnref8"&gt;8&lt;/sup&gt; dentro del fichero &lt;code&gt;serverless.yml&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;serverless plugin &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;-n&lt;/span&gt; serverless-lift
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight diff"&gt;&lt;code&gt;&lt;span class="p"&gt;service: laravel
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="p"&gt;functions:
&lt;/span&gt;  web:
    handler: public/index.php
    runtime: php-82-fpm
&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;  artisan:
    handler: artisan
    runtime: php-82-console
&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gi"&gt;+ constructs:
+   website:
+     type: server-side-website
+     assets:
+       '/build/*': public/build
+       # Agreguen aquí cualquier archivo o directorio que necesite ser servido desde S3
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="p"&gt;plugins:
&lt;/span&gt;  - ./vendor/bref/bref
&lt;span class="gi"&gt;+   - serverless-lift
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Dentro de la sección &lt;code&gt;constructs&lt;/code&gt; hemos definido un componente &lt;code&gt;website&lt;/code&gt; del tipo &lt;code&gt;server-side-website&lt;/code&gt;. Esto le dice al plugin &lt;code&gt;serverless-lift&lt;/code&gt; que cree una distribución de &lt;strong&gt;CloudFront&lt;/strong&gt;, la cual actuará como CDN para servir los archivos estáticos desde un Bucket S3, y a su vez como proxy reverso, redirigiendo las solicitudes a las rutas de tu aplicación PHP a través de API Gateway =&amp;gt; Lambda.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmp3emi5unpl6e42nzrpt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmp3emi5unpl6e42nzrpt.png" alt="Serverless with CloudFront" width="" height=""&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;serverless deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Este deploy demorará unos 5-7 minutos adicionales por única vez, ya que las distribuciones de CloudFront son creadas globalmente. Los siguientes deploys serán más rápidos, siempre que no modifiquen configuraciones que afecten a la distribución de CloudFront.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;En el resultado de la consola verán que ahora disponen de dos URLs, una del API Gateway &lt;em&gt;(que ya no utilizaremos)&lt;/em&gt;, y otra de CloudFront, el cual servirá los assets estáticos desde el Bucket S3, y el resto de las rutas serán procesadas por Lambda.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8cujunv9ntlahiwtv3ie.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8cujunv9ntlahiwtv3ie.png" alt="serverless deploy output with CloudFront" width="800" height="266"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;¡Y ahora el CSS se carga correctamente! Felicidades, han desplegado su primera aplicación Laravel en ambiente &lt;em&gt;serverless&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkjiyh2926gopiitc9jwt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkjiyh2926gopiitc9jwt.png" alt="Laravel on AWS Serverless" width="800" height="642"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  4. Optimizando para el Mundo Real: La Batalla Contra el Cold-Start
&lt;/h2&gt;

&lt;p&gt;Seguramente habrán notado que la primera vez que ingresaron a su aplicación, esta demoró unos segundos adicionales en responder.&lt;/p&gt;

&lt;p&gt;Así como mencioné en el artículo anterior, esto es llamado &lt;em&gt;cold-start&lt;/em&gt; y ocurre cuando Lambda inicializa una nueva instancia para ejecutar su aplicación. Esta inicialización puede llevar 250ms o más, especialmente si tu aplicación es grande.&lt;/p&gt;

&lt;p&gt;Lambda mantiene viva una instancia hasta 10 minutos después de procesar una solicitud, luego es destruida automáticamente.&lt;/p&gt;

&lt;p&gt;Podemos abordar esto desde varios frentes.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) Mantener siempre viva una instancia Lambda &lt;sup id="fnref9"&gt;9&lt;/sup&gt;
&lt;/h3&gt;

&lt;p&gt;En aplicaciones con poco tráfico, es normal que hayan periodos mayores a 10 minutos de inactividad, por lo que podremos tener un porcentaje mayor de solicitudes procesadas en un &lt;em&gt;cold-start&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Bref dispone de un evento especial que podemos utilizar para mantener viva una instancia de Lambda. Simplemente debemos agregar un evento &lt;code&gt;schedule&lt;/code&gt; en nuestro fichero de configuración &lt;code&gt;serverless.yml&lt;/code&gt; con el payload &lt;code&gt;{warmer: true}&lt;/code&gt;. Bref reconocerá este evento especial y responderá instantáneamente con el código de estado 100 &lt;sup id="fnref10"&gt;10&lt;/sup&gt; sin ejecutar tu código, manteniendo así viva la instancia.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight diff"&gt;&lt;code&gt;&lt;span class="p"&gt;service: laravel
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="p"&gt;functions:
&lt;/span&gt;  web:
    handler: public/index.php
    runtime: php-82-fpm
    events:
      - httpApi: '*'
&lt;span class="gi"&gt;+       - schedule:
+         rate: rate(5 minutes)
+         input:
+           warmer: true
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  b) Reducir el tamaño de su aplicación
&lt;/h3&gt;

&lt;p&gt;Durante un cold-start, AWS Lambda descarga el paquete de la aplicación, lo descomprime en un entorno temporal y carga el runtime junto con todas las dependencias y configuraciones necesarias. Este proceso, aunque está optimizado, añade latencia a la primera solicitud. Por ello, reducir el tamaño del paquete &lt;em&gt;(por ejemplo, eliminando dependencias de desarrollo o módulos innecesarios)&lt;/em&gt; puede acortar considerablemente este tiempo de inicialización.&lt;/p&gt;

&lt;p&gt;El fichero &lt;code&gt;serverless.yml&lt;/code&gt; por defecto de Bref ya ignora ciertos directorios que no son necesarios en PHP, como por ejemplo &lt;code&gt;node_modules&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Paquetes de desarrollo
&lt;/h4&gt;

&lt;p&gt;Antes de realizar el deploy, podemos desinstalar los paquetes de desarrollo. Esto reducirá en gran manera el tamaño del directorio &lt;code&gt;vendor&lt;/code&gt;, y en consecuencia, el tamaño total del código enviado a Lambda.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer &lt;span class="nb"&gt;install&lt;/span&gt; &lt;span class="nt"&gt;--no-dev&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Dependencias de servicios AWS
&lt;/h4&gt;

&lt;p&gt;En la mayoría de mis aplicaciones, el paquete de composer que más ocupa espacio es &lt;code&gt;aws/aws-sdk-php&lt;/code&gt; &lt;em&gt;(requerido por &lt;code&gt;bref/laravel-bridge&lt;/code&gt;)&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Lo bueno es que la comunidad ha desarrollado un script de composer para limpiar los paquetes de servicios AWS no utilizados en nuestra aplicación &lt;sup id="fnref11"&gt;11&lt;/sup&gt;. Solo debemos especificar en el fichero &lt;code&gt;composer.json&lt;/code&gt; los servicios que sí utilizamos:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight diff"&gt;&lt;code&gt;{
  "name": "laravel/laravel",
  "type": "project",
  ...
  "require": {
    "php": "^8.2",
    "bref/bref": "^2.3",
    "bref/laravel-bridge": "^2.5",
    "laravel/framework": "^11.31",
    "laravel/octane": "^2.8",
    ...
  },
  "scripts": {
&lt;span class="gi"&gt;+     "pre-autoload-dump": "Aws\\Script\\Composer\\Composer::removeUnusedServices",
&lt;/span&gt;    "post-autoload-dump": [
      "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
      "@php artisan package:discover --ansi"
    ],
    ...
  },
  "extra": {
    "laravel": {
      "dont-discover": []
    },
&lt;span class="gi"&gt;+     "aws/aws-sdk-php": [
+       "DynamoDb",
+       "S3",
+       "Sqs"
+     ]
&lt;/span&gt;  },
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;El script de limpieza correrá cada vez que ejecutemos &lt;code&gt;composer install&lt;/code&gt; o &lt;code&gt;composer update&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  c) Impulsando el Rendimiento con Laravel Octane
&lt;/h3&gt;

&lt;p&gt;Incluso cuando se producen &lt;em&gt;cold-starts&lt;/em&gt;, Laravel Octane entra en acción para mantener la aplicación en memoria y reducir significativamente los tiempos de respuesta. Al evitar un arranque completo de Laravel en cada solicitud, se mejora notablemente la experiencia del usuario final.&lt;/p&gt;

&lt;p&gt;Laravel Octane actúa como un acelerador que "mantiene caliente" la aplicación. Una vez que Lambda inicia la aplicación, Octane se encarga de conservarla en memoria, de modo que las siguientes solicitudes se atiendan casi de inmediato. Es como encender el motor de un coche y dejarlo listo para arrancar en cualquier momento, en lugar de encenderlo desde cero cada vez.&lt;/p&gt;

&lt;p&gt;Pasos para implementar Laravel Octane:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;composer require laravel/octane
php artisan octane:install
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Una vez instalado, actualicen el fichero &lt;code&gt;serverless.yml&lt;/code&gt; para utilizar Laravel Octane como handler &lt;sup id="fnref12"&gt;12&lt;/sup&gt;. Esto asegurará que tu aplicación se ejecute con el rendimiento mejorado que ofrece Laravel Octane:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight diff"&gt;&lt;code&gt;&lt;span class="p"&gt;service: laravel
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;span class="err"&gt;
&lt;/span&gt;&lt;span class="p"&gt;functions:
&lt;/span&gt;  web:
    handler: Bref\LaravelBridge\Http\OctaneHandler
    runtime: php-82
&lt;span class="gd"&gt;- # ...
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finalmente, desplieguen su aplicación con los cambios realizados:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;serverless deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  d) Métricas que Validan el Progreso
&lt;/h3&gt;

&lt;p&gt;Aplicando todas las mejoras mencionadas, hemos reducido el tiempo de inicialización &lt;em&gt;(cold-start)&lt;/em&gt; de nuestra aplicación. Y con Laravel Octane, no solo hemos mejorado el tiempo del &lt;em&gt;cold-start&lt;/em&gt;, sino que mejoramos el tiempo de respuesta general de nuestra aplicación.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Podemos visualizar los tiempos de respuesta en los logs de CloudWatch que ya se configuraron automáticamente por nosotros.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Cold-start &lt;strong&gt;sin optimizaciones&lt;/strong&gt; &lt;em&gt;(499ms)&lt;/em&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fquieaec9z2cepjz0dazz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fquieaec9z2cepjz0dazz.png" alt="php-fpm coldstart" width="" height=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Cold-start con &lt;strong&gt;Laravel Octane y optimizaciones&lt;/strong&gt; &lt;em&gt;(190ms)&lt;/em&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjfh1wtwucl0unkfq6q4k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjfh1wtwucl0unkfq6q4k.png" alt="Laravel Octane coldstart" width="800" height="255"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Tengan en cuenta que al utilizar Laravel Octane, se mantiene la ejecución de Laravel en memoria, por lo que deben cuidarse de los memory leaks &lt;sup id="fnref13"&gt;13&lt;/sup&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  5. Caídas y Aprendizajes: Los Errores que Todo Migrante Serverless Debe Conocer
&lt;/h2&gt;

&lt;p&gt;Seguramente se dieron cuenta que hay una función llamada &lt;code&gt;artisan&lt;/code&gt; en el fichero &lt;code&gt;serverless.yml&lt;/code&gt;. Esa función utiliza la versión &lt;em&gt;"consola"&lt;/em&gt; del runtime de Bref &lt;sup id="fnref14"&gt;14&lt;/sup&gt;, la cual nos permite ejecutar comandos de Laravel Artisan en AWS Lambda.&lt;/p&gt;

&lt;p&gt;Como no tenemos acceso SSH a las instancias de Lambda, Bref nos disponibiliza un puente para poder ejecutar comandos &lt;code&gt;cli&lt;/code&gt; mediante el comando &lt;code&gt;bref:cli&lt;/code&gt; de &lt;em&gt;serverless&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;serverless bref:cli &lt;span class="nt"&gt;--args&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"&amp;lt;comando artisan y sus opciones&amp;gt;"&lt;/span&gt;
serverless bref:cli &lt;span class="nt"&gt;--args&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"route:list"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Optimizaciones
&lt;/h3&gt;

&lt;p&gt;Un punto muy importante que quiero reforzar es que debemos cambiar nuestra mentalidad al desarrollar aplicaciones para entornos &lt;em&gt;serverless&lt;/em&gt;. En este nuevo paradigma, es crucial diseñar nuestros procesos y flujos de trabajo considerando las características únicas de la computación &lt;em&gt;serverless&lt;/em&gt;, como la naturaleza efímera de las funciones y el modelo de facturación basado en el uso.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Serverless no es caro... pero el código mal adaptado sí lo es.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;En mi primer mes migrando una de mis aplicaciones al entorno &lt;em&gt;serverless&lt;/em&gt;, cometí el error de no revisar detalladamente ciertos procesos. Uno de ellos se encargaba de sincronizar los productos de la tienda en línea con un sistema de facturación externo, incluyendo la actualización de imágenes de productos. Y como mencioné en el artículo anterior, algunos procesos no son ideales para ejecutarse en un entorno &lt;em&gt;serverless&lt;/em&gt;. En este caso, estaba pagando por tiempo muerto, durante la descarga de imágenes, mi código en Lambda no estaba realizando nada más que esperar 5-8 segundos por imágen. Con 65,000 artículos en la tienda y dos sincronizaciones diarias, esto resultó en una factura de &lt;strong&gt;~$530&lt;/strong&gt; solo por el tiempo inactivo durante la descarga de imágenes.&lt;/p&gt;

&lt;p&gt;Este incidente me llevó a rediseñar el proceso de sincronización. En un primer intento de optimización, implementé la descarga de múltiples imágenes en paralelo utilizando PHP ZTS, lo que me llevó a desarrollar la librería &lt;code&gt;hds-solutions/parallel-sdk&lt;/code&gt; &lt;sup id="fnref15"&gt;15&lt;/sup&gt;. Esta versión redujo los costos a &lt;strong&gt;~160$&lt;/strong&gt;, pero aún no era suficiente; mi objetivo era que los costos estuvieran por debajo de lo que gastaba originalmente en EC2.&lt;/p&gt;

&lt;p&gt;En un segundo intento, trasladé el proceso de descarga de imágenes a una instancia EC2 dedicada. Aunque esto redujo significativamente los costos a &lt;strong&gt;~50$&lt;/strong&gt;, la aplicación quedó dividida en dos componentes separados.&lt;/p&gt;

&lt;p&gt;Finalmente, en la tercera versión del proceso de sincronización, tras conversar con el cliente, implementé un pequeño script en el servidor del sistema de facturación. En lugar de que mi aplicación descargara las imágenes, este script enviaba las imágenes directamente desde el servidor del sistema de facturación a S3 utilizando URLs pre-firmadas &lt;sup id="fnref16"&gt;16&lt;/sup&gt;. Esto eliminó por completo los costos asociados a la descarga de imágenes, quedando únicamente el costo de almacenamiento en S3.&lt;/p&gt;




&lt;h2&gt;
  
  
  6. ¿Qué Sigue?
&lt;/h2&gt;

&lt;p&gt;¡Con esto, cerramos otro capítulo en nuestro viaje hacia el mundo &lt;em&gt;serverless&lt;/em&gt;! Hoy vimos cómo transformar a Laravel en un auténtico nómada en la nube, adaptándolo para vivir sin el peso de un servidor tradicional. Pero esto es solo el comienzo.&lt;/p&gt;

&lt;p&gt;En el próximo artículo nos adentraremos en el corazón de la integración: veremos cómo trasladar los datos de sesión y caché a DynamoDB, cómo aprovechar S3 para el manejo de archivos, configurar SQS para gestionar colas y utilizar EventBridge para orquestar tareas programadas. ¡Nos vemos en la siguiente entrega!&lt;/p&gt;




&lt;p&gt;Mientras tanto, ¿han migrado su aplicación Laravel a &lt;em&gt;serverless&lt;/em&gt;? ¡Compartan sus experiencias en los comentarios! Y para los que aún no lo han hecho, les animo a experimentar con lo que hemos implementado hasta ahora y a compartir sus dudas y experiencias.&lt;/p&gt;




&lt;ol&gt;

&lt;li id="fn1"&gt;
&lt;p&gt;&lt;a href="https://getcomposer.org/download" rel="noopener noreferrer"&gt;https://getcomposer.org/download&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn2"&gt;
&lt;p&gt;&lt;a href="https://github.com/nvm-sh/nvm#installation-and-update" rel="noopener noreferrer"&gt;https://github.com/nvm-sh/nvm#installation-and-update&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn3"&gt;
&lt;p&gt;&lt;a href="https://www.serverless.com/framework/docs/getting-started" rel="noopener noreferrer"&gt;https://www.serverless.com/framework/docs/getting-started&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn4"&gt;
&lt;p&gt;&lt;a href="https://laravel.com/docs/installation" rel="noopener noreferrer"&gt;https://laravel.com/docs/installation&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn5"&gt;
&lt;p&gt;&lt;a href="https://bref.sh/docs/laravel/getting-started" rel="noopener noreferrer"&gt;https://bref.sh/docs/laravel/getting-started&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn6"&gt;
&lt;p&gt;&lt;a href="https://bref.sh/docs/use-cases/websites" rel="noopener noreferrer"&gt;https://bref.sh/docs/use-cases/websites&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn7"&gt;
&lt;p&gt;&lt;a href="https://github.com/brefphp/bref/releases/tag/0.5.20" rel="noopener noreferrer"&gt;https://github.com/brefphp/bref/releases/tag/0.5.20&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn8"&gt;
&lt;p&gt;&lt;a href="https://github.com/getlift/lift/blob/master/docs/server-side-website.md" rel="noopener noreferrer"&gt;https://github.com/getlift/lift/blob/master/docs/server-side-website.md&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn9"&gt;
&lt;p&gt;&lt;a href="https://bref.sh/docs/use-cases/http/advanced-use-cases#cold-starts" rel="noopener noreferrer"&gt;https://bref.sh/docs/use-cases/http/advanced-use-cases#cold-starts&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn10"&gt;
&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/100" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/100&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn11"&gt;
&lt;p&gt;&lt;a href="https://github.com/aws/aws-sdk-php/tree/master/src/Script/Composer" rel="noopener noreferrer"&gt;https://github.com/aws/aws-sdk-php/tree/master/src/Script/Composer&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn12"&gt;
&lt;p&gt;&lt;a href="https://bref.sh/docs/laravel/octane" rel="noopener noreferrer"&gt;https://bref.sh/docs/laravel/octane&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn13"&gt;
&lt;p&gt;&lt;a href="https://laravel.com/docs/11.x/octane#managing-memory-leaks" rel="noopener noreferrer"&gt;https://laravel.com/docs/11.x/octane#managing-memory-leaks&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn14"&gt;
&lt;p&gt;&lt;a href="https://bref.sh/docs/runtimes/console" rel="noopener noreferrer"&gt;https://bref.sh/docs/runtimes/console&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn15"&gt;
&lt;p&gt;&lt;a href="https://github.com/hschimpf/parallel-sdk" rel="noopener noreferrer"&gt;https://github.com/hschimpf/parallel-sdk&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn16"&gt;
&lt;p&gt;&lt;a href="https://docs.aws.amazon.com/es_es/AmazonS3/latest/userguide/PresignedUrlUploadObject.html" rel="noopener noreferrer"&gt;https://docs.aws.amazon.com/es_es/AmazonS3/latest/userguide/PresignedUrlUploadObject.html&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;/ol&gt;

</description>
      <category>laravel</category>
      <category>php</category>
      <category>serverless</category>
      <category>aws</category>
    </item>
    <item>
      <title>Por qué Migré Mi Aplicación Laravel a AWS Serverless (Y Por Qué Podría Ahorrarte Tiempo y Dinero)</title>
      <dc:creator>Hermann D. Schimpf</dc:creator>
      <pubDate>Wed, 29 Jan 2025 00:01:51 +0000</pubDate>
      <link>https://dev.to/hschimpf/por-que-migre-mi-aplicacion-laravel-a-aws-serverless-y-por-que-podria-ahorrarte-tiempo-y-dinero-6hp</link>
      <guid>https://dev.to/hschimpf/por-que-migre-mi-aplicacion-laravel-a-aws-serverless-y-por-que-podria-ahorrarte-tiempo-y-dinero-6hp</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;English version &lt;a href="https://dev.to/hschimpf/why-i-migrated-my-laravel-app-to-aws-serverless-and-why-it-could-save-you-time-and-money-dem"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3ydzkg9z8tp6oqswgj45.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3ydzkg9z8tp6oqswgj45.png" alt="PHP meets serverless" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;Spoiler&lt;/strong&gt;: No se trata solo de ahorrar dinero—aunque mi billetera no se queja.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Imagina esto: has creado una brillante aplicación en Laravel—tu obra maestra, una navaja suiza digital con funciones tan útiles que podrían cortar mantequilla... o los comentarios de los usuarios. Pero hay un detalle. Cada mes estás pagando por una instancia EC2 que está tan infrautilizada como una membresía de gimnasio después de enero. Mientras tanto, escalar se siente como intentar aparcar un crucero en medio de un huracán.&lt;/p&gt;

&lt;p&gt;¿Te ha pasado? A mí también.&lt;/p&gt;

&lt;p&gt;Hace tres años, hice algo que la mayoría de los desarrolladores llamarían una locura: desplegué PHP en AWS Lambda. “¿PHP? ¿En serverless? ¡Eso es como poner piña en la pizza!”, decían.&lt;/p&gt;

&lt;p&gt;Pero aquí estoy, tres años después, comiendo mi pizza con piña con orgullo. Déjame contarte por qué Laravel en serverless es la actualización en la nube que no sabías que necesitabas.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. El Problema del Hosting Tradicional con Laravel
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;(ó: Por qué mis instancias EC2 estaban teniendo una crisis existencial)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Antes de serverless, mi aplicación Laravel vivía en EC2. Para los no iniciados, EC2 es la versión de Amazon de un servidor privado virtual, donde alquilas una parte de una máquina para ejecutar tu código. Suena bien, ¿verdad? Hasta que la realidad te golpea más fuerte que un &lt;code&gt;composer update&lt;/code&gt; rebelde.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) Primero está: El Costo de Existir
&lt;/h3&gt;

&lt;p&gt;Ejecutar una instancia EC2 es como tener un Tesla que dejas encendido las 24 horas del día, solo por si acaso quieres conducir. Mi aplicación no siempre estaba ocupada, pero eso no detenía el contador. Entre instancias EC2, balanceadores de carga y almacenamiento compartido, gastaba alrededor de $110/mes en un stack de servidores que pasaba la mayor parte del tiempo inactivo. ¿Mi billetera? Hundida como el Titanic.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Lo sé, no es mucho en el gran esquema de las cosas, pero como desarrollador/emprendedor en solitario, cada dólar cuenta.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  b) Después: Las Pesadillas de Escalado
&lt;/h3&gt;

&lt;p&gt;Las instancias EC2 son como ese amigo que reacciona de forma exagerada a todo.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;¿Pico de tráfico? &lt;em&gt;"¡Me voy a caer ahora, gracias!"&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;¿No hay tráfico? &lt;em&gt;"¡Igual seguiré quemando tu dinero!"&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Gestionar el autoescalado se sentía como enseñar a un pez a hacer malabares—es posible, pero ¿a qué costo? Ajustar manualmente los grupos de escalado, configurar balanceadores de carga y rezar para no provisionar de más se sentía como un segundo trabajo al que nunca me postulé.&lt;/p&gt;

&lt;h3&gt;
  
  
  c) Y finalmente: DevOps, el Interno No Pagado
&lt;/h3&gt;

&lt;p&gt;Nadie me dijo que el desarrollo con Laravel venía con un lado de responsabilidades de sysadmin:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Aplicar parches de seguridad.&lt;/li&gt;
&lt;li&gt;Depurar configuraciones de nginx/apache a las 3 AM.&lt;/li&gt;
&lt;li&gt;Susurrar palabras bonitas a los comandos &lt;code&gt;sudo&lt;/code&gt;, esperando que funcionaran esta vez.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;No me inscribí para esta vida.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Fue entonces cuando comencé a explorar alternativas, y serverless se destacó como la solución perfecta para resolver estos dolores de cabeza.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  2. AWS Serverless: El Resurgimiento de PHP en la Nube
&lt;/h2&gt;

&lt;p&gt;Aclaremos un mito: serverless no significa "sin servidores". Solo significa que los servidores son el problema de otra persona. En este caso, AWS hace el trabajo pesado mientras yo me concentro en lo que realmente disfruto: programar.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) Lambda: El Mago Impulsado por Eventos
&lt;/h3&gt;

&lt;p&gt;AWS Lambda es como un superhéroe que solo aparece cuando lo necesitas. Ejecuta tu código en respuesta a eventos—solicitudes HTTP, mensajes de SQS, tareas programadas, tu nómbralo. Y cuando el trabajo termina, desaparece más rápido que una pizza gratis en una reunión de desarrolladores.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Sin costos inactivos&lt;/strong&gt;: Solo pagas por el tiempo de ejecución (medido en milisegundos).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Magia de escalado automático&lt;/strong&gt;: ¿Recibiste un pico de 100,000 solicitudes? Lambda las maneja sin sudar (ni vaciar tu cuenta bancaria).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Stateless por diseño&lt;/strong&gt;: Es como un borrón y cuenta nueva cada vez, un diseño que te obliga a pensar de forma modular.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  b) Servicios Administrados: Los Héroes Anónimos
&lt;/h3&gt;

&lt;p&gt;Serverless no es solo Lambda—es un ecosistema. AWS reemplaza tu infraestructura DIY (hazlo tú mismo) con servicios administrados que "simplemente funcionan":&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Base de datos&lt;/strong&gt;: Opciones como Aurora Serverless (MySQL/Postgres) para los amantes de SQL.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;S3&lt;/strong&gt;: Almacena tus archivos sin preocuparte por quedarte sin espacio en disco.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;SQS&lt;/strong&gt;: Desacopla trabajos de larga duración y procésalos de forma asíncrona.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  c) La Paradoja de PHP
&lt;/h3&gt;

&lt;p&gt;Debo admitirlo: PHP no &lt;em&gt;nació&lt;/em&gt; para serverless. Es como pedirle a un pez que trepe un árbol—se quejará, pero eventualmente lo hará. Laravel, tradicionalmente dependiente de PHP-FPM, necesitó algunos ajustes para prosperar en el mundo efímero de Lambda:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Sesiones&lt;/strong&gt;: Muévelas a una base de datos externa, como MySQL o Redis.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Almacenamiento de archivos&lt;/strong&gt;: Redirige todas las operaciones de almacenamiento a S3, usando el facade &lt;code&gt;Storage&lt;/code&gt; de Laravel.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Gestión de colas&lt;/strong&gt;: Configura SQS como el controlador predeterminado para la ejecución de tareas asíncronas.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Caching&lt;/strong&gt;: Aprovecha servicios externos como Redis o DynamoDB en lugar de almacenamiento local.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Optimización del tiempo de arranque&lt;/strong&gt;: Minimiza los inicios en frío (cold starts) recortando lo innecesario (dependencias no utilizadas).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Variables de entorno&lt;/strong&gt;: Reemplaza los archivos &lt;code&gt;.env&lt;/code&gt; con AWS Secrets Manager o Parameter Store para una gestión centralizada y segura de la configuración.&lt;/li&gt;
&lt;/ul&gt;




&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Recuerda que serverless no se trata solo de reemplazar servidores por funciones Lambda. Se trata de repensar tu arquitectura—dejando que AWS maneje los puntos de dolor operativos mientras tú te concentras en construir.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  3. Cómo Serverless Desbloquea Todo el Potencial de Laravel
&lt;/h2&gt;

&lt;p&gt;Entonces, ¿Laravel en serverless realmente cumple sus promesas?&lt;/p&gt;

&lt;p&gt;Serverless no es solo una palabra de moda, es un cambio transformador. La belleza de Laravel en serverless radica en su capacidad para resolver los puntos débiles del alojamiento tradicional, al mismo tiempo que permite soluciones más rápidas, escalables y rentables. Pero la verdadera magia ocurre cuando profundizas en cómo se combinan estos beneficios. Vamos a desglosarlo.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) Cold Starts: Separando el Mito de la Realidad
&lt;/h3&gt;

&lt;p&gt;Los &lt;em&gt;cold starts&lt;/em&gt; ocurren cuando Lambda inicializa una nueva instancia. Piensa en ello como si PHP despertara de una siesta. Los críticos los tratan como si fueran el apocalipsis, pero son manejables:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Realidad&lt;/strong&gt;: Los &lt;em&gt;cold starts&lt;/em&gt; típicos con PHP + Laravel rondan los ~3-5 segundos.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Soluciones&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Laravel Octane&lt;/strong&gt;: Mantiene la aplicación viva entre solicitudes, reduciendo los tiempos de inicio. Las solicitudes posteriores se procesan en ~200ms o menos.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Concurrencia aprovisionada&lt;/strong&gt;: AWS pre-calienta instancias para endpoints críticos &lt;em&gt;(cuesta extra, pero vale la pena para puntos clave)&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;Para la mayoría de las aplicaciones, los retrasos menores a 3 segundos durante el tráfico bajo son aceptables. La mayoría de los usuarios no notará un &lt;em&gt;cold start&lt;/em&gt;, especialmente durante cargas máximas de tráfico cuando Lambda permanece "caliente".&lt;/p&gt;

&lt;h3&gt;
  
  
  b) Escalado Sin Dolor
&lt;/h3&gt;

&lt;p&gt;El escalado en el hosting tradicional suele parecer una batalla interminable. Con serverless, el escalado se vuelve muy sencillo: ya no es necesario ajustar las reglas de autoescalado ni cruzar los dedos durante un aumento repentino de tráfico. AWS Lambda elimina las conjeturas, escalando horizontalmente por defecto.&lt;/p&gt;

&lt;p&gt;Aquí va un ejemplo:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Escenario&lt;/strong&gt;: Tu aplicación se vuelve viral 🚀 yey!&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Antigüa configuración con EC2&lt;/strong&gt;: Comienza a experimentar latencia, corres a iniciar sesión en AWS, ajustas manualmente la cantidad de instancias, y rezas por lo mejor 🫠. Ah, y no olvides equilibrar correctamente esas instancias entre las zonas de disponibilidad.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Nueva configuración con Lambda&lt;/strong&gt;: AWS crea automáticamente tantas instancias como sea necesario, manejando miles de solicitudes concurrentes sin que levantes un dedo. Agarras unas palomitas de maíz y observas las métricas de CloudWatch como si fuera una serie de Netflix 🍿.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Esto no es solo comodidad, es tranquilidad. Mientras tú te concentras en celebrar el éxito de tu aplicación, Lambda hace el trabajo pesado. ¿Y lo mejor? Solo pagas por el tiempo de computación que usas, no por la capacidad inactiva que podrías necesitar "por si acaso".&lt;/p&gt;

&lt;h3&gt;
  
  
  c) Eficiencia de Costos: El Jugador Más Valioso
&lt;/h3&gt;

&lt;p&gt;Serverless no solo ahorra dinero, es como tener un buffet de $5 donde solo pagas por lo que comes.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mi antigua configuración con EC2: &lt;strong&gt;~$110&lt;/strong&gt;/mes.

&lt;ul&gt;
&lt;li&gt;4x instancias EC2 t3.small: &lt;strong&gt;$60.00&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;1x Balanceador de Carga: &lt;strong&gt;$16.40&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;1x EBS (almacenamiento compartido entre instancias EC2): &lt;strong&gt;$7.80&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;1x instancia RDS MySQL (db.t4g.medium): &lt;strong&gt;~26.00&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Lambda: &lt;strong&gt;~$34&lt;/strong&gt;/mes &lt;em&gt;(¡un ahorro del 60%!)&lt;/em&gt;.

&lt;ul&gt;
&lt;li&gt;Lambda, API Gateway ~2.5M solicitudes (~500ms / 512MB de memoria) /mes: &lt;strong&gt;$4.80&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Servicios gestionados (S3, SQS, CloudWatch): &lt;strong&gt;~$2.90&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Instancia RDS MySQL (db.t4g.medium): &lt;strong&gt;~26.00&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Recurso&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Costo EC2&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Costo Lambda&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Computación&lt;/td&gt;
&lt;td&gt;$60.00&lt;/td&gt;
&lt;td&gt;$4.50&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Red (LB, API Gateway)&lt;/td&gt;
&lt;td&gt;$16.40&lt;/td&gt;
&lt;td&gt;$0.30&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Almacenamiento&lt;/td&gt;
&lt;td&gt;$7.80&lt;/td&gt;
&lt;td&gt;$2.90&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Base de datos&lt;/td&gt;
&lt;td&gt;$26.00&lt;/td&gt;
&lt;td&gt;$26.00&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;TOTAL&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;$110.20&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;$33.70&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;En resumen, serverless no solo ahorra dinero, libera ancho de banda mental. Cuantos menos recursos desperdicie preocupándome por el sobreaprovisionamiento, más puedo concentrarme en construir algo increíble.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Hasta ese momento, todavía utilizaba una instancia MySQL como motor de base de datos. Publicaciones posteriores explorarán cómo migrar a DynamoDB para reducir aún más los costos.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  d) Libertad de Mantenimiento: Di Adiós a las Pesadillas Operativas
&lt;/h3&gt;

&lt;p&gt;Serverless me liberó de las cadenas del mantenimiento de servidores. Aquí está cómo:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;No más actualizaciones manuales&lt;/strong&gt;: AWS maneja parches de seguridad, actualizaciones del sistema operativo y mejoras de tiempo de ejecución, lo que significa que siempre estás utilizando una infraestructura segura y actualizada.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Configuraciones simplificadas&lt;/strong&gt;: Con servicios como API Gateway y S3, la complejidad de gestionar configuraciones nginx y despliegues personalizados se convierte en cosa del pasado.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Capacidad elástica&lt;/strong&gt;: Olvídate de pagar de más por recursos de servidor no utilizados o de apresurarte a provisionar más durante picos de tráfico. Lambda escala automáticamente para satisfacer la demanda y deja de facturar cuando está inactivo.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Enfócate en las características, no en apagar incendios&lt;/strong&gt;: El tiempo que antes dedicaba a aplicar parches o a depurar problemas en producción ahora lo invierto en crear características y mejorar la experiencia del usuario.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Serverless no solo reduce el mantenimiento, elimina las distracciones operativas que te impiden programar.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. Pero, ¿Es Laravel Serverless para Todos?
&lt;/h2&gt;

&lt;p&gt;Por muy revolucionario que sea Laravel en serverless, no es una solución universal. Para algunas aplicaciones, la naturaleza stateless y orientada a eventos de serverless puede parecer un sueño hecho realidad. Para otras, puede parecer como tratar de encajar un cuadrado en un círculo. Antes de subirte al tren de serverless, retrocedamos un poco y evaluemos si es adecuado para tu proyecto.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) La Naturaleza Stateless: Una Espada de Doble Filo
&lt;/h3&gt;

&lt;p&gt;Laravel adora las operaciones que guardan información entre interacciones, como almacenar archivos localmente y guardar sesiones en el sistema de archivos. Para pasar a serverless, debes cambiar:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Sesiones&lt;/strong&gt;: Usa bases de datos (MySQL/Postgres) o Redis; nada más de depender del sistema de archivos.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Archivos&lt;/strong&gt;: Redirige las subidas de archivos a S3, o evita completamente pasar por Laravel y utiliza URL pre-firmadas de S3.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Logs&lt;/strong&gt;: Configura Laravel para transmitirlos a CloudWatch.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Configuración&lt;/strong&gt;: Mueve las variables &lt;code&gt;.env&lt;/code&gt; a AWS Secrets Manager o Parameter Store para una gestión centralizada.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Colas&lt;/strong&gt;: Migra los trabajos a AWS SQS para manejar colas y mensajes de manera escalable.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  b) Consideraciones Sobre la Dependencia del Proveedor (&lt;em&gt;Vendor Lock-In&lt;/em&gt;)
&lt;/h3&gt;

&lt;p&gt;Los servicios de AWS son mágicos, pero también son propietarios:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;¿Migrar de SQS a colas Redis? Prepárate para reescribir código.&lt;/li&gt;
&lt;li&gt;¿Quieres pasar de Lambda a Docker? Tómate un café: será una noche larga.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  c) Cuándo No Optar por Serverless
&lt;/h3&gt;

&lt;p&gt;Serverless no es una bala de plata para todas las cargas de trabajo. Debes evitarlo si:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Necesitas &lt;strong&gt;WebSockets&lt;/strong&gt;: Aunque se puede lograr con servicios como API Gateway + WebSocket APIs o herramientas de terceros como Ably, añade complejidad.&lt;/li&gt;
&lt;li&gt;Tu aplicación tiene &lt;strong&gt;cargas computacionales pesadas&lt;/strong&gt;: Tareas como inferencia de IA/ML o codificación de video pueden alcanzar el límite de tiempo de 15 minutos de Lambda.&lt;/li&gt;
&lt;li&gt;Dependes de &lt;strong&gt;servicios con estado&lt;/strong&gt;: Las aplicaciones que asumen un disco persistente o un estado del servidor pueden ser costosas de refactorizar.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  5. ¿Qué Sigue?
&lt;/h2&gt;

&lt;p&gt;Laravel en serverless tiene el potencial de transformar la forma en que construyes y despliegas aplicaciones, pero la verdadera magia está en la implementación. ¿Estás listo para dar el salto y darle a tu aplicación Laravel el tratamiento serverless? Mantente atento a la Parte 2, donde te guiaré a través de los pasos exactos para llevar esta arquitectura a la vida.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Una pregunta para ti&lt;/strong&gt;: ¿Cuál es tu mayor temor con serverless? ¡Compártelo abajo y abordaré los 3 principales en la Parte 2!&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
      <category>serverless</category>
      <category>aws</category>
    </item>
    <item>
      <title>Why I Migrated My Laravel App to AWS Serverless (And Why It Could Save You Time and Money)</title>
      <dc:creator>Hermann D. Schimpf</dc:creator>
      <pubDate>Tue, 28 Jan 2025 03:03:21 +0000</pubDate>
      <link>https://dev.to/hschimpf/why-i-migrated-my-laravel-app-to-aws-serverless-and-why-it-could-save-you-time-and-money-dem</link>
      <guid>https://dev.to/hschimpf/why-i-migrated-my-laravel-app-to-aws-serverless-and-why-it-could-save-you-time-and-money-dem</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;Versión en español &lt;a href="https://dev.to/hschimpf/por-que-migre-mi-aplicacion-laravel-a-aws-serverless-y-por-que-podria-ahorrarte-tiempo-y-dinero-6hp"&gt;aquí&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3ydzkg9z8tp6oqswgj45.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3ydzkg9z8tp6oqswgj45.png" alt="PHP meets serverless" width="800" height="800"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;Spoiler&lt;/strong&gt;: It’s not just about saving money—though my wallet isn’t complaining.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;Picture this: you've built a shiny Laravel app—your magnum opus, a digital Swiss Army knife with features so sharp they could cut through butter... or user feedback. But there's a catch. Every month, you're stuck paying for an EC2 instance that’s as underutilized as a gym membership after January. Meanwhile, scaling feels like trying to parallel park a cruise ship during a hurricane.&lt;/p&gt;

&lt;p&gt;Been there? I have too.&lt;/p&gt;

&lt;p&gt;Three years ago, I did something that most developers would call madness: I deployed PHP on AWS Lambda. "PHP? On serverless? That's like putting pineapple on pizza!" they said.&lt;/p&gt;

&lt;p&gt;But here I am, three years later, eating my pineapple pizza with pride. Let me tell you why serverless Laravel is the cloud upgrade you didn't know you needed.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. The Problem with Traditional Laravel Hosting
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;(or: Why my EC2 instances were having an existential crisis)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Before serverless, my Laravel app lived on EC2. For the uninitiated, EC2 is Amazon’s version of a virtual private server, where you rent a slice of a machine to run your code. Sounds nice, right? Until reality hits you harder than a rogue &lt;code&gt;composer update&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) First there is: The Cost of Breathing
&lt;/h3&gt;

&lt;p&gt;Running an EC2 instance is like owning a Tesla you keep running 24/7, just in case you feel like driving. My app wasn’t always busy, but that didn’t stop the meter from ticking. Between EC2 instances, load balancers, and shared storage, I was shelling out around $110/month for a server stack that spent most of its time idling. My wallet? Doing a Titanic impression.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;I know, it’s not much in the grand scheme of things, but as a solo developer/entrepreneur, every dollar counts.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  b) Then is: The Scaling Nightmares
&lt;/h3&gt;

&lt;p&gt;EC2 instances are like that one friend who overreacts to everything.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Traffic spike? &lt;em&gt;"I'll crash now, thanks!"&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;Traffic hush? &lt;em&gt;"I’ll keep burning your money anyway!"&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Managing autoscaling felt like teaching a fish to juggle—it's possible, but at what cost? Manually tweaking scaling groups, configuring load balancers, and praying I didn’t overprovision felt like a second job I never applied for.&lt;/p&gt;

&lt;h3&gt;
  
  
  c) And lastly DevOps: The Unpaid Intern
&lt;/h3&gt;

&lt;p&gt;Nobody told me Laravel development came with a side of sysadmin responsibilities:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Applying security patches.&lt;/li&gt;
&lt;li&gt;Debugging nginx/apache configs at 3 AM.&lt;/li&gt;
&lt;li&gt;Whispering sweet nothings to &lt;code&gt;sudo&lt;/code&gt; commands, hoping they’d work this time.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I didn't sign up for this life.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;That’s when I started exploring alternatives, and serverless stood out as the perfect fit for solving these headaches.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  2. AWS Serverless: PHP’s Cloud Glow-Up
&lt;/h2&gt;

&lt;p&gt;Let’s clear up a myth: serverless doesn't mean "no servers". It just means the servers are someone else's problem. In this case, AWS does the heavy lifting while I focus on what I actually enjoy—coding.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) Lambda: The Event-Driven Wizard
&lt;/h3&gt;

&lt;p&gt;AWS Lambda is like a superhero that only shows up when you need it. It executes your code in response to events—HTTP requests, SQS messages, cron jobs, you name it. And when the job's done, it disappears faster than a free pizza at a dev meetup.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;No idle costs&lt;/strong&gt;: Pay only for execution time (measured in milliseconds).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Auto-scaling magic&lt;/strong&gt;: Got a 100,000 requests spike? Lambda handles them without breaking a sweat (or your bank account).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Stateless by design&lt;/strong&gt;: It's like a clean slate every time—a design that forces you to think modularly.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  b) Managed Services: The Unsung Heroes
&lt;/h3&gt;

&lt;p&gt;Serverless isn't just Lambda—it's an ecosystem. AWS replaces your DIY infrastructure with managed services that "just work":&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Database&lt;/strong&gt;: Serverless-friendly options like Aurora Serverless (MySQL/Postgres) for SQL lovers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;S3&lt;/strong&gt;: Store your files without worrying about running out of disk space.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;SQS&lt;/strong&gt;: Decouple long-running jobs and process them asynchronously.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  c) The PHP Paradox
&lt;/h3&gt;

&lt;p&gt;I have to admit it: PHP wasn't &lt;em&gt;born&lt;/em&gt; for serverless. It's like asking a fish to climb a tree—it'll complain, but it'll eventually get there. Laravel, traditionally reliant on PHP-FPM, needed some love to thrive in Lambda's ephemeral world:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Sessions&lt;/strong&gt;: Move them to an external database, like MySQL or Redis.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;File storage&lt;/strong&gt;: Reroute all storage operations to S3, using Laravel’s &lt;code&gt;Storage&lt;/code&gt; facade.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Queue handling&lt;/strong&gt;: Set up SQS as the default queue driver for async task execution.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Caching&lt;/strong&gt;: Leverage external services like Redis or DynamoDB instead of local storage.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Boot time optimization&lt;/strong&gt;: Minimize cold starts by trimming fat (unused dependencies).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Environment variables&lt;/strong&gt;: Replace &lt;code&gt;.env&lt;/code&gt; files with AWS Secrets Manager or Parameter Store for secure and centralized configuration management.&lt;/li&gt;
&lt;/ul&gt;




&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Keep in mind that serverless isn't just about swapping out servers for Lambda functions. It’s about rethinking your architecture—letting AWS handle the operational pain points while you focus on building.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  3. How Serverless Unlocks Laravel’s Full Potential
&lt;/h2&gt;

&lt;p&gt;So, does serverless Laravel actually deliver on its promises?&lt;/p&gt;

&lt;p&gt;Serverless isn't just a buzzword—it's a game-changer. The beauty of serverless Laravel lies in its ability to solve the pain points of traditional hosting while enabling faster, more scalable, and cost-effective solutions. But the real magic happens when you dive into how these benefits come together. Let’s break it down.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) Cold Starts: Separating Fact from Fiction
&lt;/h3&gt;

&lt;p&gt;Cold starts occur when Lambda initializes a new instance. Think of it as PHP waking up from a nap. Critics treat them like the apocalypse, but they’re manageable:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Reality&lt;/strong&gt;: Typical cold starts with PHP + Laravel are ~3-5 seconds.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Solutions&lt;/strong&gt;:

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Laravel Octane&lt;/strong&gt;: Keeps the app alive between requests, reducing boot times. The subsequent requests are processed in ~200ms or less.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Provisioned Concurrency&lt;/strong&gt;: AWS pre-warms instances for critical endpoints &lt;em&gt;(costs extra, but worth it for critical endpoints)&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;For most apps, sub-3s delays during low traffic are acceptable. Most users won't notice a cold start, especially during peak traffic loads when Lambda stays warm.&lt;/p&gt;

&lt;h3&gt;
  
  
  b) Scaling Without Tears
&lt;/h3&gt;

&lt;p&gt;Scaling in traditional hosting often feels like fighting a never-ending battle. With serverless, scaling becomes effortless—no more tweaking auto-scaling rules or crossing your fingers during a traffic surge. AWS Lambda eliminates the guesswork, scaling horizontally by default.&lt;/p&gt;

&lt;p&gt;Here's an example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Scenario&lt;/strong&gt;: Your app goes viral 🚀 yey!.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Old EC2 Setup&lt;/strong&gt;: It starts getting latency, you scramble to log into AWS, manually adjust instance counts, and hope for the best 🫠. Oh, and don't forget to balance those instances properly across availability zones.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;New Lambda Setup&lt;/strong&gt;: AWS automatically spins up as many instances as needed, handling thousands of concurrent requests without you lifting a finger. You grab popcorn and watch CloudWatch metrics like it’s a Netflix series 🍿.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This isn’t just convenience—it’s peace of mind. While you focus on celebrating your app's success, Lambda does the heavy lifting. And the best part? You’re billed only for the compute time you use, not for the idle capacity you might need "just in case".&lt;/p&gt;

&lt;h3&gt;
  
  
  c) Cost Efficiency: The Real MVP
&lt;/h3&gt;

&lt;p&gt;Serverless doesn't just save money—it’s like having a $5 buffet where you only pay for what you eat.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;My old EC2 setup: &lt;strong&gt;~$110&lt;/strong&gt; /month.

&lt;ul&gt;
&lt;li&gt;4x EC2 t3.small instances: &lt;strong&gt;$60.00&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;1x Load Balancer: &lt;strong&gt;$16.40&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;1x EBS (shared storage between EC2 instances): &lt;strong&gt;$7.80&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;1x RDS MySQL instance (db.t4g.medium): &lt;strong&gt;~26.00&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Lambda: &lt;strong&gt;~$34&lt;/strong&gt; /month &lt;em&gt;(a 60% saving!)&lt;/em&gt;.

&lt;ul&gt;
&lt;li&gt;Lambda, API Gateway ~2.5M requests (~500ms / 512MB memory) /month: &lt;strong&gt;$4.80&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Managed services (S3, SQS, CloudWatch): &lt;strong&gt;~$2.90&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;RDS MySQL instance (db.t4g.medium): &lt;strong&gt;~26.00&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;strong&gt;Resource&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;EC2 Cost&lt;/strong&gt;&lt;/th&gt;
&lt;th&gt;&lt;strong&gt;Lambda Cost&lt;/strong&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Compute&lt;/td&gt;
&lt;td&gt;$60.00&lt;/td&gt;
&lt;td&gt;$4.50&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Networking (LB, API Gateway)&lt;/td&gt;
&lt;td&gt;$16.40&lt;/td&gt;
&lt;td&gt;$0.30&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Storage&lt;/td&gt;
&lt;td&gt;$7.80&lt;/td&gt;
&lt;td&gt;$2.90&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Database&lt;/td&gt;
&lt;td&gt;$26.00&lt;/td&gt;
&lt;td&gt;$26.00&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;TOTAL&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;$110.20&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;$33.70&lt;/strong&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;In short, serverless doesn’t just save money—it frees up mental bandwidth. The fewer resources I waste worrying about over-provisioning, the more I can focus on building something amazing.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;At that time, I was still using a MySQL instance as database engine. Later posts will explore migrating the database engine to DynamoDB to cut costs further.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  d) Maintenance Freedom: Say Goodbye to Ops Nightmares
&lt;/h3&gt;

&lt;p&gt;Serverless freed me from the shackles of server maintenance. Here’s how:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;No more manual updates&lt;/strong&gt;: AWS handles server patching, operating system updates, and runtime upgrades, meaning you’re always running on secure, up-to-date infrastructure.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Simplified configurations&lt;/strong&gt;: With services like API Gateway and S3, the complexity of managing nginx configs and custom deployments becomes a thing of the past.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Elastic capacity&lt;/strong&gt;: Forget overpaying for unused server resources or scrambling to provision more during traffic spikes. Lambda automatically scales to meet demand and stops billing when idle.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Focus on features, not firefighting&lt;/strong&gt;: The time I once spent applying patches or debugging production issues now goes into building features and improving user experience.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Serverless doesn't just reduce maintenance; it removes the operational distractions that keep you from coding.&lt;/p&gt;




&lt;h2&gt;
  
  
  4. But, "Is Serverless Laravel for Everyone?"
&lt;/h2&gt;

&lt;p&gt;As revolutionary as serverless Laravel is, it's not a one-size-fits-all solution. For some apps, the stateless, event-driven nature of serverless can feel like a dream come true. For others, it might feel like trying to fit a square peg into a round hole. Before you jump on the serverless bandwagon, let’s take a step back and evaluate whether it’s the right fit for your project.&lt;/p&gt;

&lt;h3&gt;
  
  
  a) Statelessness: The Double-Edged Sword
&lt;/h3&gt;

&lt;p&gt;Laravel loves stateful operations like storing files locally and caching sessions in the filesystem. To go serverless you must change:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Sessions&lt;/strong&gt;: Use databases (MySQL/Postgres), or Redis—no more filesystem reliance.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Files&lt;/strong&gt;: Reroute uploads to S3, or bypass Laravel entirely via pre-signed S3 URLs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Logs&lt;/strong&gt;: Configure Laravel to stream them to CloudWatch.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Configuration&lt;/strong&gt;: Move &lt;code&gt;.env&lt;/code&gt; variables to AWS Secrets Manager or Parameter Store for centralized management.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Queues&lt;/strong&gt;: Migrate jobs to AWS SQS for scalable queueing and message handling.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  b) Vendor Lock-In Considerations
&lt;/h3&gt;

&lt;p&gt;AWS services are magical, but they’re also proprietary:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Migrating from SQS to Redis queues? Have fun rewriting code.&lt;/li&gt;
&lt;li&gt;Want to move from Lambda to Docker? Grab a coffee—it’ll be a long night.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  c) When Not to Go Serverless
&lt;/h3&gt;

&lt;p&gt;Serverless isn’t a silver bullet for every workload, you should consider avoiding it if:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You need &lt;strong&gt;WebSockets&lt;/strong&gt;: While achievable with services like API Gateway + WebSocket APIs or third-party tools like Ably, it adds complexity.&lt;/li&gt;
&lt;li&gt;Your app has &lt;strong&gt;heavy computational workloads&lt;/strong&gt;: Tasks like AI/ML inference or video encoding may hit Lambda’s 15-minute timeout.&lt;/li&gt;
&lt;li&gt;You rely on &lt;strong&gt;stateful services&lt;/strong&gt;: Applications that assume a persistent disk or server state can be costly to refactor.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  5. What’s Next?
&lt;/h2&gt;

&lt;p&gt;Serverless Laravel has the potential to transform the way you build and deploy applications, but the real magic is in the implementation. Are you ready to make the leap and give your Laravel app the serverless treatment? Stay tuned for Part 2, where I'll walk you through the exact steps to bring this architecture to life.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Question for you&lt;/strong&gt;: What’s your biggest serverless fear? Share below—I’ll tackle the top 3 in Part 2!&lt;/p&gt;

</description>
      <category>laravel</category>
      <category>php</category>
      <category>serverless</category>
      <category>aws</category>
    </item>
  </channel>
</rss>
