SlideShare a Scribd company logo
1
6 tips to build6 tips to build
Fast WebFast Web
ApplicationsApplications
-
Luciano Mammino (@loige)
PHP Dublin 22/03/2016
2
About me
Integrations Engineer at Smartbox
Php developer since *.php3
I Tweet as @loige
I Blog on loige.co
3
PreamblePreamble
Only 6 tips (not exhaustive)
Focused on backend
Many generic advices (not just Php)
... Tools and examples (mostly) for Php :)
4
Tip 1.Tip 1.
Avoid prematureAvoid premature
optimisation!optimisation!
5
"Premature"Premature
optimisation is theoptimisation is the
root of all evil"root of all evil"
β€” Donald Knuth
(not an excuse to write πŸ’© code!)
6
Do you really have a problem?
How big the problem is?
Measure before questioning
Set (realistic) goals
Improve only where needed!
The right mindsetThe right mindset
7
The performance
lifecycle
8
BenchmarkingBenchmarking
Command line:
(ab)
Graphical:
(for APIs)
Apache Bench
Siege
Apache JMeter
Soap UI
9
10
ProfilingProfiling
Active or Passive?
(Active)
Gives a lot of data
Slows down the execution
Good in development
Easy to integrate with IDEs
Also a debugger
Xdebug (Passive)
Minimal impact
Less data
Good in production
Dedicated Web GUI ( )
Supported by Facebook...
xhprof
xhgui
11
LibrariesLibraries
Symfony componentstopwatch
<?php
use SymfonyComponentStopwatchStopwatch;
$stopwatch = new Stopwatch();
// Start event named 'eventName'
$stopwatch->start('eventName');
// ... some code goes here
$event = $stopwatch->stop('eventName');
echo $event->getDuration(); // xxx milliseconds
12
Cloud toolsCloud tools
&Blackfire.io Tideways
13
Tip 2.Tip 2.
Do just what you need toDo just what you need to
14
15
A.k.a.A.k.a.
"Don't do things that you"Don't do things that you
don't need to"don't need to"
E.g.
Load classes that you are not using
Open a connection to a database for every
request
Parse a huge XML config file for every
request
16
AutoloadingAutoloading
Syntetic Namespaces, Classmaps, PSR-0, PSR-4
You get it for free with !Composer
<?php
require __DIR__ . '/vendor/autoload.php'; // generated by Composer
use MarioCharactersMario;
use MarioPowerupsMushroom;
// Mario & Mushroom classes not loaded yet...
$mario = new Mario();
// Mario class is loaded!
$mushroom = new Mushroom();
// Mushroom class is loaded!
$mario->eat($mushroom); // Tasty!
17
Other patternsOther patterns
(& Dependency Injection Container)
Simplifies the loading of classes and the resolution of
dependencies
&&
Access resources only when you are about to use them
Dependency InjectionDependency Injection
Lazy loadingLazy loading ProxyProxy
18
Tip 3.Tip 3.
If you really need to do it,If you really need to do it,
do itdo it tomorrowtomorrow!!
19
20
Defer tasks when possibleDefer tasks when possible
E.g.
Send an email to a user to confirm an order
Resize an image after the upload
Aggregate metrics
(Serve the response as soon as it's ready!)
21
Queues to the rescueQueues to the rescue
A PHP library (Redis as data store).
Laravel/Lumen built-in solution (multiple data storages).
Generic job server that supports many languages.
Work queue originally written to speed up Facebook
Resque
Laravel Queues
Gearman
Beanstalkd
22
Tip 4.Tip 4.
23
Use cache to avoid repetitiveUse cache to avoid repetitive
computations and roundtripscomputations and roundtrips
Different Caching layers:
Byte code Cache (APC, OpCache)
Application Cache (Redis, Memcache, )
HTTP Cache (E-tag, Cache-control headers)
Proxy Cache (Varnish, Squid, Nginx)
Gibson
24
"There are only two hard"There are only two hard
things in Computerthings in Computer
Science: cacheScience: cache
invalidation and naminginvalidation and naming
things"things"
β€” Phil Karltonβ€” Phil Karlton
25
Tip 5.Tip 5.
Beware of the N+1 queryBeware of the N+1 query
problem!problem!
26
<?php
function getUsers() {
//... retrieve the users from the database (1 query)
return $users;
}
function loadLastLoginsForUsers($users) {
foreach ($users as $user) {
$lastLogins = ... // load the last logins
// for the user (1 query, executed n times)
$user->setLastLogins($lastLogins);
}
return $users;
}
$users = getUsers();
loadLastLoginsForUsers($users);
27
SELECT id FROM Users; -- ids: 1, 2, 3, 4, 5, 6...
SELECT * FROM Logins WHERE user_id = 1;
SELECT * FROM Logins WHERE user_id = 2;
SELECT * FROM Logins WHERE user_id = 3;
SELECT * FROM Logins WHERE user_id = 4;
SELECT * FROM Logins WHERE user_id = 5;
SELECT * FROM Logins WHERE user_id = 6;
-- ...
N+1 Queries! πŸ˜“πŸ˜“
28
Better solutionBetter solution
or use JOINS...or use JOINS...
SELECT id FROM Users; -- ids: 1, 2, 3, 4, 5, 6...
SELECT * FROM Logins
WHERE user_id IN (1, 2, 3, 4, 5, 6, ...);
Don't trust the ORM
Check the queries generated by your code!
29
Tip 6.Tip 6.
Plan for horizontalPlan for horizontal
scalabilityscalability
30
Build your app to beBuild your app to be
replicated across manyreplicated across many
serversservers
Sessions:
Don't use the default file based engine
Be as much stateless as possible
User files:
CDN, Cloud Storage (S3, Cloudfiles), Sync (NFS, Gluster)
Consider Microservices...
31
BONUS Tip.BONUS Tip.
Update to PHP7Update to PHP7
(Rasmus approves)
php.net/migration70
32
Let's RecapLet's Recap
1. Avoid premature optimisation!
2. Do just what you need to
3. If you really need to do it, do it tomorrow!
4. Cache me if you can
5. Beware of the N+1 query problem!
6. Plan for horizontal scalability
7. Bonus: Update to Php 7
8. :Super Secret Bonus bit.ly/php-perf
33
Thank you!Thank you!
Let's keep in touch:
-http://loige.co @loige

More Related Content

PPTX
Jvm a brief introduction
PDF
파이썬 ν”ŒλΌμŠ€ν¬λ‘œ λ°°μš°λŠ” μ›Ήν”„λ‘œκ·Έλž˜λ° #4 (ABCD)
PDF
2019 StartIT - Boosting your performance with Blackfire
PDF
Top ten-list
PPT
scale_perf_best_practices
PDF
2019 PHP Serbia - Boosting your performance with Blackfire
PDF
2013 - Dustin whittle - Escalando PHP en la vida real
PDF
Php go vrooom!
Jvm a brief introduction
파이썬 ν”ŒλΌμŠ€ν¬λ‘œ λ°°μš°λŠ” μ›Ήν”„λ‘œκ·Έλž˜λ° #4 (ABCD)
2019 StartIT - Boosting your performance with Blackfire
Top ten-list
scale_perf_best_practices
2019 PHP Serbia - Boosting your performance with Blackfire
2013 - Dustin whittle - Escalando PHP en la vida real
Php go vrooom!

Similar to 6tips web-perf (20)

PPT
Scaling Web Apps P Falcone
Β 
PPTX
Northeast PHP - High Performance PHP
PPTX
Web Performance, Scalability, and Testing Techniques - Boston PHP Meetup
PDF
Optimizing CakePHP 2.x Apps
PDF
Dutch php conference_2010_opm
Β 
PPTX
Profiling and Tuning a Web Application - The Dirty Details
ODP
Clug 2011 March web server optimisation
PPTX
BTV PHP - Building Fast Websites
PDF
Performance and optimization CakeFest 2014
PPT
Scaling 101 test
PPT
Scaling 101
PDF
Clug 2012 March web server optimisation
PDF
You Were Lied To About Optimization
PPT
Web Speed And Scalability
PPTX
High performance PHP: Scaling and getting the most out of your infrastructure
PDF
Tech meetup: Web Applications Performance
ODP
Caching and tuning fun for high scalability @ PHPTour
PPT
Top 10 Scalability Mistakes
PPT
Heavy Web Optimization: Backend
PPT
Tips for a Faster Website
Scaling Web Apps P Falcone
Β 
Northeast PHP - High Performance PHP
Web Performance, Scalability, and Testing Techniques - Boston PHP Meetup
Optimizing CakePHP 2.x Apps
Dutch php conference_2010_opm
Β 
Profiling and Tuning a Web Application - The Dirty Details
Clug 2011 March web server optimisation
BTV PHP - Building Fast Websites
Performance and optimization CakeFest 2014
Scaling 101 test
Scaling 101
Clug 2012 March web server optimisation
You Were Lied To About Optimization
Web Speed And Scalability
High performance PHP: Scaling and getting the most out of your infrastructure
Tech meetup: Web Applications Performance
Caching and tuning fun for high scalability @ PHPTour
Top 10 Scalability Mistakes
Heavy Web Optimization: Backend
Tips for a Faster Website
Ad

More from Luciano Mammino (20)

PDF
Serverless Rust: Your Low-Risk Entry Point to Rust in Production (and the ben...
PDF
Did you know JavaScript has iterators? DublinJS
PDF
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
PDF
Building an invite-only microsite with Next.js & Airtable - ReactJS Milano
PDF
From Node.js to Design Patterns - BuildPiper
PDF
Let's build a 0-cost invite-only website with Next.js and Airtable!
PDF
Everything I know about S3 pre-signed URLs
PDF
Serverless for High Performance Computing
PDF
Serverless for High Performance Computing
PDF
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
PDF
Building an invite-only microsite with Next.js & Airtable
PDF
Let's take the monolith to the cloud πŸš€
PDF
A look inside the European Covid Green Certificate - Rust Dublin
PDF
Monoliths to the cloud!
PDF
The senior dev
PDF
Node.js: scalability tips - Azure Dev Community Vijayawada
PDF
A look inside the European Covid Green Certificate (Codemotion 2021)
PDF
AWS Observability Made Simple
PDF
Semplificare l'observability per progetti Serverless
PDF
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021
Serverless Rust: Your Low-Risk Entry Point to Rust in Production (and the ben...
Did you know JavaScript has iterators? DublinJS
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
Building an invite-only microsite with Next.js & Airtable - ReactJS Milano
From Node.js to Design Patterns - BuildPiper
Let's build a 0-cost invite-only website with Next.js and Airtable!
Everything I know about S3 pre-signed URLs
Serverless for High Performance Computing
Serverless for High Performance Computing
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
Building an invite-only microsite with Next.js & Airtable
Let's take the monolith to the cloud πŸš€
A look inside the European Covid Green Certificate - Rust Dublin
Monoliths to the cloud!
The senior dev
Node.js: scalability tips - Azure Dev Community Vijayawada
A look inside the European Covid Green Certificate (Codemotion 2021)
AWS Observability Made Simple
Semplificare l'observability per progetti Serverless
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021
Ad

Recently uploaded (20)

PPTX
artificial intelligence overview of it and more
PPT
tcp ip networks nd ip layering assotred slides
PDF
How to Ensure Data Integrity During Shopify Migration_ Best Practices for Sec...
PPTX
innovation process that make everything different.pptx
PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PPTX
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
PPTX
Introduction to Information and Communication Technology
PDF
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
PDF
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PDF
An introduction to the IFRS (ISSB) Stndards.pdf
PPTX
Digital Literacy And Online Safety on internet
PPTX
Funds Management Learning Material for Beg
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PPTX
522797556-Unit-2-Temperature-measurement-1-1.pptx
PPTX
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
PDF
Paper PDF World Game (s) Great Redesign.pdf
PDF
Decoding a Decade: 10 Years of Applied CTI Discipline
PPTX
introduction about ICD -10 & ICD-11 ppt.pptx
DOCX
Unit-3 cyber security network security of internet system
artificial intelligence overview of it and more
tcp ip networks nd ip layering assotred slides
How to Ensure Data Integrity During Shopify Migration_ Best Practices for Sec...
innovation process that make everything different.pptx
Slides PPTX World Game (s) Eco Economic Epochs.pptx
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
Introduction to Information and Communication Technology
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
πŸ’° π”πŠπ“πˆ πŠπ„πŒπ„ππ€ππ†π€π πŠπˆππ„π‘πŸ’πƒ π‡π€π‘πˆ 𝐈𝐍𝐈 πŸπŸŽπŸπŸ“ πŸ’°
Β 
Design_with_Watersergyerge45hrbgre4top (1).ppt
An introduction to the IFRS (ISSB) Stndards.pdf
Digital Literacy And Online Safety on internet
Funds Management Learning Material for Beg
Job_Card_System_Styled_lorem_ipsum_.pptx
522797556-Unit-2-Temperature-measurement-1-1.pptx
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
Paper PDF World Game (s) Great Redesign.pdf
Decoding a Decade: 10 Years of Applied CTI Discipline
introduction about ICD -10 & ICD-11 ppt.pptx
Unit-3 cyber security network security of internet system

6tips web-perf

  • 1. 1 6 tips to build6 tips to build Fast WebFast Web ApplicationsApplications - Luciano Mammino (@loige) PHP Dublin 22/03/2016
  • 2. 2 About me Integrations Engineer at Smartbox Php developer since *.php3 I Tweet as @loige I Blog on loige.co
  • 3. 3 PreamblePreamble Only 6 tips (not exhaustive) Focused on backend Many generic advices (not just Php) ... Tools and examples (mostly) for Php :)
  • 4. 4 Tip 1.Tip 1. Avoid prematureAvoid premature optimisation!optimisation!
  • 5. 5 "Premature"Premature optimisation is theoptimisation is the root of all evil"root of all evil" β€” Donald Knuth (not an excuse to write πŸ’© code!)
  • 6. 6 Do you really have a problem? How big the problem is? Measure before questioning Set (realistic) goals Improve only where needed! The right mindsetThe right mindset
  • 9. 9
  • 10. 10 ProfilingProfiling Active or Passive? (Active) Gives a lot of data Slows down the execution Good in development Easy to integrate with IDEs Also a debugger Xdebug (Passive) Minimal impact Less data Good in production Dedicated Web GUI ( ) Supported by Facebook... xhprof xhgui
  • 11. 11 LibrariesLibraries Symfony componentstopwatch <?php use SymfonyComponentStopwatchStopwatch; $stopwatch = new Stopwatch(); // Start event named 'eventName' $stopwatch->start('eventName'); // ... some code goes here $event = $stopwatch->stop('eventName'); echo $event->getDuration(); // xxx milliseconds
  • 13. 13 Tip 2.Tip 2. Do just what you need toDo just what you need to
  • 14. 14
  • 15. 15 A.k.a.A.k.a. "Don't do things that you"Don't do things that you don't need to"don't need to" E.g. Load classes that you are not using Open a connection to a database for every request Parse a huge XML config file for every request
  • 16. 16 AutoloadingAutoloading Syntetic Namespaces, Classmaps, PSR-0, PSR-4 You get it for free with !Composer <?php require __DIR__ . '/vendor/autoload.php'; // generated by Composer use MarioCharactersMario; use MarioPowerupsMushroom; // Mario & Mushroom classes not loaded yet... $mario = new Mario(); // Mario class is loaded! $mushroom = new Mushroom(); // Mushroom class is loaded! $mario->eat($mushroom); // Tasty!
  • 17. 17 Other patternsOther patterns (& Dependency Injection Container) Simplifies the loading of classes and the resolution of dependencies && Access resources only when you are about to use them Dependency InjectionDependency Injection Lazy loadingLazy loading ProxyProxy
  • 18. 18 Tip 3.Tip 3. If you really need to do it,If you really need to do it, do itdo it tomorrowtomorrow!!
  • 19. 19
  • 20. 20 Defer tasks when possibleDefer tasks when possible E.g. Send an email to a user to confirm an order Resize an image after the upload Aggregate metrics (Serve the response as soon as it's ready!)
  • 21. 21 Queues to the rescueQueues to the rescue A PHP library (Redis as data store). Laravel/Lumen built-in solution (multiple data storages). Generic job server that supports many languages. Work queue originally written to speed up Facebook Resque Laravel Queues Gearman Beanstalkd
  • 23. 23 Use cache to avoid repetitiveUse cache to avoid repetitive computations and roundtripscomputations and roundtrips Different Caching layers: Byte code Cache (APC, OpCache) Application Cache (Redis, Memcache, ) HTTP Cache (E-tag, Cache-control headers) Proxy Cache (Varnish, Squid, Nginx) Gibson
  • 24. 24 "There are only two hard"There are only two hard things in Computerthings in Computer Science: cacheScience: cache invalidation and naminginvalidation and naming things"things" β€” Phil Karltonβ€” Phil Karlton
  • 25. 25 Tip 5.Tip 5. Beware of the N+1 queryBeware of the N+1 query problem!problem!
  • 26. 26 <?php function getUsers() { //... retrieve the users from the database (1 query) return $users; } function loadLastLoginsForUsers($users) { foreach ($users as $user) { $lastLogins = ... // load the last logins // for the user (1 query, executed n times) $user->setLastLogins($lastLogins); } return $users; } $users = getUsers(); loadLastLoginsForUsers($users);
  • 27. 27 SELECT id FROM Users; -- ids: 1, 2, 3, 4, 5, 6... SELECT * FROM Logins WHERE user_id = 1; SELECT * FROM Logins WHERE user_id = 2; SELECT * FROM Logins WHERE user_id = 3; SELECT * FROM Logins WHERE user_id = 4; SELECT * FROM Logins WHERE user_id = 5; SELECT * FROM Logins WHERE user_id = 6; -- ... N+1 Queries! πŸ˜“πŸ˜“
  • 28. 28 Better solutionBetter solution or use JOINS...or use JOINS... SELECT id FROM Users; -- ids: 1, 2, 3, 4, 5, 6... SELECT * FROM Logins WHERE user_id IN (1, 2, 3, 4, 5, 6, ...); Don't trust the ORM Check the queries generated by your code!
  • 29. 29 Tip 6.Tip 6. Plan for horizontalPlan for horizontal scalabilityscalability
  • 30. 30 Build your app to beBuild your app to be replicated across manyreplicated across many serversservers Sessions: Don't use the default file based engine Be as much stateless as possible User files: CDN, Cloud Storage (S3, Cloudfiles), Sync (NFS, Gluster) Consider Microservices...
  • 31. 31 BONUS Tip.BONUS Tip. Update to PHP7Update to PHP7 (Rasmus approves) php.net/migration70
  • 32. 32 Let's RecapLet's Recap 1. Avoid premature optimisation! 2. Do just what you need to 3. If you really need to do it, do it tomorrow! 4. Cache me if you can 5. Beware of the N+1 query problem! 6. Plan for horizontal scalability 7. Bonus: Update to Php 7 8. :Super Secret Bonus bit.ly/php-perf
  • 33. 33 Thank you!Thank you! Let's keep in touch: -http://loige.co @loige