Enlightn Profile picture
Your performance/security consultant, an Artisan command away.

Feb 1, 2021, 83 tweets

I'll share 100 Laravel tips on performance, security and reliability over the next 100 days!

Simply follow this thread 👇 to get them daily.

🔥 Laravel Tip #01: Consider adding route caching to your deployment script to speed up your route registration by up to 5x!

🔥 Laravel Tip #02:

Did you know that if you have your MySQL database running on your web server, you can improve performance by up to 50% by using Unix sockets instead of TCP ports?

The folks over at @Percona published a benchmark on this.

Link: percona.com/blog/2020/04/1…

🔥 Laravel Tip #03:

Whenever your app allows the user to define a filename to be uploaded, make sure you strip out the directory from the input to protect against unrestricted file upload attacks.

Learn more: laravel-enlightn.com/docs/security/…

🔥 Laravel Tip #04:

If you're using Redis in your Laravel app, make sure to choose an eviction policy that matches your use case.

Learn more: laravel-enlightn.com/docs/reliabili…

🔥 Laravel Tip #05:

For scalability, it's a good practice to make your tasks (jobs, scheduled commands or service classes) idempotent.

Idempotent tasks can be called multiple times without changing the side effects.

Here's @stauffermatt's talk on this:

🔥 Laravel Tip #06:

If you use resource controllers, make sure to either implement all methods or restrict route registrations with the only method.

Otherwise, there would be dead routes in your app that throw 500 BadMethodCallExceptions rather than serving proper 404s.

🔥 Laravel Tip #07:

For a nice performance boost, it's often a good practice to implement page caching for static pages.

@laravelphp's own website uses this for caching documentation pages.

Github Link: github.com/laravel/larave…

🔥 Laravel Tip #08:

It's a good practice to take a daily backup of your application database and files.

Luckily, for Laravel, the good folks over at @spatie_be built an awesome OSS package for that!

Github Link: github.com/spatie/laravel…

@spatie_be 🔥 Laravel Tip #09:

It feels like data breaches are showing up every week in the news. You should think about how you're storing sensitive data, especially PII.

Consider using Laravel Eloquent's encrypted attribute casting contributed by @gonedark.

PR: github.com/laravel/framew…

🔥 Laravel Tip #10:

If your application allows users to download large datasets computed on the fly, consider using streamed downloads and lazy collections for better performance and reduced memory usage.

🔥 Laravel Tip #11:

To minimize the risk of remote code execution (RCE) and cross-site scripting (XSS), it is a good practice to disable the "allow_url_fopen" and "allow_url_include" php configuration settings in your php.ini file.

Learn more: laravel-enlightn.com/docs/security/…

🔥 Laravel Tip #12:

For protection against brute force attacks, it is recommended to use a combination of login throttling (supported by Laravel out-of-the-box) and a captcha library such as @reCAPTCHA.

🔥 Laravel Tip #13:

If you have free RAM wasting away on your web server, one simple yet powerful technique to increase performance is to increase your PHP FPM max child processes.

🔥 Laravel Tip #14:

When you work with a large number of query results, it is a good practice to use chunking for reduced memory usage.

A great example is @laravelphp Scout internally uses chunking while importing DB records into search indexes.

🔥 Laravel Tip #15:

There is no "one size fits all" when it comes to database queries. You should always consider your options - joins, eager loading, subqueries, etc.

Here's an example by @reinink when subqueries are better than eager loading.

Link: reinink.ca/articles/dynam…

🔥 Laravel Tip #16:

Avoid env calls outside of your config files. This can break your code with config caching.

Once the configuration has been cached, the .env file will not be loaded and all calls to the env function will return null.

Learn more: laravel-enlightn.com/docs/performan…

🔥 Laravel Tip #17:

It's a good practice to regularly rotate your app key, especially when a developer leaves your company.

Don't worry, the app key is not used to hash passwords, so rotating it will not mess up the ability to login.

Learn more: laravel-enlightn.com/docs/security/…

🔥 Laravel Tip #18:

To avoid mass assignment vulnerabilities, it's important that you explicitly whitelist or blacklist attributes either on your model class or before passing them to your model.

Learn more: cheatsheetseries.owasp.org/cheatsheets/La…

🔥 Laravel Tip #19:

Compression headers are underrated. Did you know that minification optimizes only 20% file size while compression can save 80%?

Boost your application's performance by enabling compression on your web server or CDN.

Learn more: laravel-enlightn.com/docs/performan…

🔥 Laravel Tip #20:

Did you know that if you have Redis running on your web server, you can improve performance by ~50% by using Unix sockets instead of TCP ports?

Here's a #redis official benchmark confirming this: redis.io/topics/benchma…

Learn more: laravel-enlightn.com/docs/performan…

🔥 Laravel Tip #21:

Consider using full page caching for static pages. @joseph_silber built an amazing package that skips booting your Laravel app and is lightning fast!

Our own homepage uses this under the hood (avg. 35 ms response time).

Check it out: github.com/JosephSilber/p…

🔥 Laravel Tip #22:

We can't stress enough how important turning off debug mode is in production.

As simple as it sounds, it is incredibly dangerous to have this on in production as it may expose your .env secrets and credentials.

Learn more: laravel-enlightn.com/docs/security/…

🔥 Laravel Tip #23:

Consider switching your app to HTTPS only. It's more secure, more credible (with the lock/secure sign) and better for SEO!

All you need to do is setup the certificate, change your app URL, redirect HTTP traffic to HTTPS and configure HTTPS only cookies.

🔥 Laravel Tip #24:

For improved performance, remember to exclude dev dependencies and optimize the Composer autoloader in your production deployment scripts.

Learn more: getcomposer.org/doc/articles/a…

🔥 Laravel Tip #25:

If you share the same cache servers for multiple Laravel apps, make sure that the cache prefix is distinct to avoid collision issues.

This is especially common for staging and production sites that have the same app name.

Learn more: laravel-enlightn.com/docs/reliabili…

🔥 Laravel Tip #26:

When using queued jobs, remember to free up memory before job completion, especially if you cache values in a static or Singleton class property (not garbage collected).

🔥 Laravel Tip #27:

Consider adding Two Factor Authentication to your Laravel app. @Microsoft suggests that it would have stopped 99.9% of account compromises!

Thankfully, for Laravel apps, Fortify and Jetstream provide this out of the box!

Learn more: techcommunity.microsoft.com/t5/azure-activ…

🔥 Laravel Tip #28:

Make sure your application isn't vulnerable to host injection attacks.

Try injecting the "X-Forwarded-Host" and the "Host" header using Curl, and check if the response contains headers or URLs with the injected host.

Learn more: laravel-enlightn.com/docs/security/…

🔥 Laravel Tip #29:

If your application is on HTTPS, make sure it supports HTTP/2 for better performance with request/response multiplexing, header compression and faster TLS handshakes.

You can check if your app supports HTTP/2 using Curl.

Learn more: developers.google.com/web/fundamenta…

🔥 Laravel Tip #30:

If a task's output is not needed to be displayed in the response, it's generally a good idea to queue it.

Queueing provides faster response times, the ability to retry on failures and load balancing & priority strategies.

🔥 Laravel Tip #31:

As a good security measure, make sure that you have security headers configured either at the web server level or at the app level.

They're incredibly powerful and protect against a wide range of attacks.

Learn more: owasp.org/www-project-se…

🔥 Laravel Tip #32:

Did you know that the first step of a hack attack is reconnaissance?

Make sure that your web server does not expose its version number or operating system. The more info you expose, the easier it is to exploit.

Learn more: laravel-enlightn.com/docs/security/…

🔥 Laravel Tip #33:

Try to avoid method calls on Eloquent collections if the same task can be achieved at the query level.

This can improve performance by reducing heavy queries on the DB and preventing unnecessary loops over collections.

Learn more: laravel-enlightn.com/docs/performan…

🔥 Laravel Tip #34:

While organizing your jobs into queues, it's important to consider the following:

⏱️ How long do these jobs typically take?
⚙️ What type of job is it?
⚠️ What is the priority of the job?

Here's @OhDearApp's awesome post on this: ohdear.app/blog/how-to-si…

🔥 Laravel Tip #35:

If you use Redis in your application, you should swap out your throttling middleware with the Redis specific one for improved performance.

It is atomic and reduces the number of network calls.

Learn more: laravel-enlightn.com/docs/performan…

🔥 Laravel Tip #36:

Is your cache strategy working?

A key metric to measure is cache hit ratio, defined as hits out of all read operations.

If this ratio is <80%, it generally means that there's an issue with your cache strategy or config.

Learn more: laravel-enlightn.com/docs/performan…

🔥 Laravel Tip #37:

For improved console performance, you should prefer handle method injection over constructor injection in your Laravel commands, at least until Laravel 9x arrives with lazy loading!

@freekmurze's tweet explains this well:

🔥 Laravel Tip #38:

If you're building high concurrency apps (e.g. real time collaboration, chat, streaming, networking, gaming, microservices, etc.), you should definitely explore Laravel Octane (releasing soon).

You heard it here first folks! 😉

🔥 Laravel Tip #39:

Whenever your application allows the user to define a filename to be downloaded, make sure you strip out the directory from the input to protect against directory traversal attacks.

Learn more: laravel-enlightn.com/docs/security/…

🔥 Laravel Tip #40:

Always remember to be extra cautious with file uploads.

Validate everything!

🗃️File size: Helps avoid storage DOS attacks
📦File type: Avoid XML and ZIP files if you can
📃MIME type: Helps avoid arbitrary executables

Learn more: laravel-enlightn.com/docs/security/…

🔥 Laravel Tip #41:

If you use third-party auth packages to authorize or authenticate views that contain Livewire components, make sure to add them as persistent middleware to protect against replay attacks.

Learn more: laravel-livewire.com/docs/2.x/secur…

🔥 Laravel Tip #42:

What does a PHP developer always forget to fine tune? PHP configurations! 😂

Remember to fine tune your opcache and realpath cache configurations in production to enhance performance!

🔥 Laravel Tip #43:

Make sure to scan your PHP dependencies for known vulnerabilities as part of your CI.

If you're already using Enlightn in your CI/CD pipeline, this is taken care of. Under the hood, we use our own open source vulnerability scanner.

github.com/enlightn/secur…

🔥 Laravel Tip #44:

For enhanced performance, remember to remove your unused CSS with libraries such as PurgeCSS.

This can have a huge impact if you're using utility CSS frameworks such as @tailwindcss, where development builds are large.

Learn more: tailwindcss.com/docs/optimizin…

@tailwindcss 🔥 Laravel Tip #45:

For security reasons, avoid performing any state-changing operations in your GET requests.

Examples of state changing operations include DB inserts, updates and deletes.

Other HTTP methods are better suited for these and are secure with CSRF protection.

🔥 Laravel Tip #46:

To enhance performance, make sure to cache your configuration as part of your production deployment process.

The config:cache command caches all your configuration in a single file enabling your config to load faster.

Learn more: laravel-enlightn.com/docs/performan…

🔥 Laravel Tip #47:

Images account for more than half of the page size and image optimization can make a huge performance impact.

Use a plugin such as image-webpack-loader or imagemin to optimize images during your build process.

Learn more: developers.google.com/web/fundamenta…

🔥 Laravel Tip #48:

If you use raw SQL queries, always make sure to use parameter bindings for untrusted user input data.

Without parameter bindings, your application may be vulnerable to SQL injection attacks.

Learn more: laravel-enlightn.com/docs/security/…

🔥 Laravel Tip #49:

Do you share the same server(s) for your queue workers and web/DB/cache services?

If you do, it's a good practice to set a high nice value so that HTTP/DB/cache requests are prioritized over queue workers.

Check out @themsaid's post: divinglaravel.com/rationing-your…

🔥 Laravel Tip #50:

Do you use cache or database locks when dealing with financial transactions, rewards or vouchers?

If not, your application may be vulnerable to race condition attacks.

Learn more on how Starbucks was hacked in 2015 using this exploit
businessinsider.com/hackers-are-at…

🔥 Laravel Tip #51:

If you use packages that have their own frontend assets, it's a good practice to have composer scripts setup to keep your assets in sync.

Composer's post-update-cmd scripts are well suited for this.

Learn more: laravel-enlightn.com/docs/reliabili…

🔥 Laravel Tip #52:

Never trust user data. User data can take many forms:
⌨️ User input data (request params)
🗃️ User controlled data stored in the database

Always use Laravel Blade's curly brace {{ }} syntax to escape untrusted user data and avoid XSS attacks.

🔥 Laravel Tip #53:

Did you know that the file session driver does garbage collection within web requests? If there are many session files, this may cause CPU spikes.

A good way to boost performance is to run GC using a scheduled console command rather than web requests.

🔥 Laravel Tip #54:

You should prefer using Laravel's chunkById over chunk, unless you need sorting by a custom column.

ChunkById uses the primary key index (~60X better performance) and is also more reliable when you need to update records while iterating over results.

🔥 Laravel Tip #55:

Do you have DB tables that store "fixture" data like states or currencies?

To improve performance, consider using in-memory queries for fixture data.

Two great packages for this are github.com/calebporzio/su… and github.com/GeneaLabs/lara….

🔥 Laravel Tip #56:

It's a good security practice to have admin panels (e.g. Nova, Horizon, etc.) hosted on a separate subdomain from your main app.

This way, XSS and cookie stealing attacks on your main app won't be escalated to your admin panel.

🔥 Laravel Tip #57:

Do you use long polling on your app to push frequent updates to the UI?

For improved performance, consider using Laravel's broadcasting (websockets), allowing continuous connections and low latency/overhead.

Learn more: laravel.com/docs/8.x/broad…

🔥 Laravel Tip #58:

It's generally a good practice to set the max jobs and/or max time options on your queue workers.

This helps mitigate memory leaks in your Laravel jobs (if any).

Learn more: divinglaravel.com/avoiding-memor…

🔥 Laravel Tip #59:

Choosing the right database indexes can make a huge performance impact.

Do you have a query that you'd like to optimize? Try using the explain statement to analyze query execution plans. Pay special attention to the keys/indexes used.

🔥 Laravel Tip #60:

It's a good security practice to ask for password confirmation on sensitive routes such as rotating API keys, changing roles of team members, etc.

Luckily, Laravel provides a RequirePassword middleware right out-of-the-box (even includes a 3 hour timeout)!

🔥 Laravel Tip #61:

If you're still using gzip compression in 2021, you're missing out on a lot!

Today, Brotli is supported by all the major browsers. It provides a 15-20% reduction in file size (over gzip) with similar decompression speeds.

Learn more: tech.oyorooms.com/how-brotli-com…

🔥 Laravel Tip #62:

Do you serve dynamic content from cache that needs to be revalidated automatically?

For such use cases, Laravel has an in-built SetCacheHeaders middleware that automatically generates and compares ETags based on the response.

🔥 Laravel Tip #63:

This may sound obvious but isn't always that simple.

To improve performance, you should prefer bulk queries over multiple individual queries.

🔥 Laravel Tip #64:

If you use object caching, be mindful of memory usage (on serialization) based on the data structure you're caching.

For instance, you can cache arrays instead of Collection objects to save memory.

🔥 Laravel Tip #65:

If search engine ranking matters for your application, don't serve 200 response status codes for page not found!

It's common to use a catch-all route for SPA routing. Don't fall into that trap if search rank matters! 😜

Learn more: laravel-enlightn.com/docs/performan…

🔥 Laravel Tip #66:

Since we ❤️ @LaravelLivewire, here's a tip to improve performance of Livewire apps.

When using Livewire's data binding, you should pay special attention to the number of network calls. Livewire offers a wide variety of ways to reduce these network calls.

🔥 Laravel Tip #67:

Whenever possible, break down your Laravel jobs into smaller jobs.

This has many benefits:
🚀 Smaller jobs can run in parallel and finish sooner.
⏲️ Long running jobs may timeout or exceed max execution time (serverless).
🔁 Retrying smaller jobs is easier.

🔥 Laravel Tip #68:

It's a good practice to set password strength rules and also ensure that the password hasn't been compromised in data leaks.

Thanks to @enunomaduro, today's Laravel release will include a Password rule right out-of-the-box!

🔥 Laravel Tip #69:

If your app is on HTTPS, it's a good practice to regularly check for mixed content.

Not only does mixed content pose a security risk but could also be blocked by browsers.

@spatie_be has an amazing package for this!

Check it out: github.com/spatie/mixed-c…

🔥 Laravel Tip #70:

It's tempting to add webhook routes to your web.php file.

However, webhook routes don't need to start or authenticate sessions. For improved performance, it might be better to register a separate routes file for webhooks.

🔥 Laravel Tip #71:

For improved performance, try to sort your queries by an indexed column rather than a non-indexed column, whenever you can.

Here's a classical example of this:

🔥 Laravel Tip #72:

WebP images can improve performance by quite a bit as they're about 25-30% smaller.

However, browsers like Safari have only added WebP support to their recent versions.

A way around this is to detect browser support and serve content accordingly.

🔥 Laravel Tip #73:

If you retrieve multiple items from the cache in a single request, you can use the "many" method to retrieve all of them with a single network call.

🔥 Laravel Tip #74:

Try to use indexes whenever you can.

Check out this example where @barryvdh improves query performance of "whereDate" using the index on that column rather than the database's date function.

🔥 Laravel Tip #75:

If you have some routes and jobs that hit the same rate limited API, Laravel provides you the ability to share rate limits!

🔥 Laravel Tip #76:

Don't write your own code for security features unless you can afford penetration testing it.

Consider the following code that allows user enumeration through timing attacks. It's very hard to detect these in a code review, so don't risk it!

🔥 Laravel Tip #77:

If you use "simplePaginate" in Laravel, consider switching to "cursorPaginate" (releasing today!) for improved performance, especially if you work with large or frequently changing data-sets.

Learn more: laravel-enlightn.com/blog/laravel-o…

🔥 Laravel Tip #78:

Controversial tip but heck let's do this! There are many ways to "scale" your application and the "best" way depends on your "biggest" problem:

🤖 Server load: Horizontal / vertical scaling
🔂 Concurrency: Async / Octane
🖥️ Provisioning: Serverless / Vapor

🔥 Laravel Tip #79:

To avoid render blocking JS, consider using async or defer attributes.

Use async for independent scripts that require early loading (e.g. analytics).

Use defer for scripts that need the DOM or need to execute in order.

Learn more: web.dev/efficiently-lo…

🔥 Laravel Tip #80:

If you invoke multiple Redis commands in the same request, you should use pipelining to increase query throughput and reduce network round-trip time.

Laravel Horizon extensively uses pipelining to improve performance.

Learn more: laravel.com/docs/8.x/redis…

🔥 Laravel Tip #81:

It's generally a good idea to check if your dependencies are compatible with your project in terms of licensing.

Composer has a command to do this easily. Enlightn also takes care of this for you! 😎

Learn more: laravel-enlightn.com/docs/security/…

🔥 Laravel Tip #82:

If you have multiple Laravel apps running on the same server, make sure to configure a unique APP_NAME in your .env file.

This will immediately help you avoid cache, session and Redis collisions.

🔥 Laravel Tip #83:

With Laravel 8.43.0 and above, you can turn on strict loading in development environments to identify N+1 query problems in your app code.

Learn more: github.com/laravel/framew…

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling