SlideShare a Scribd company logo
Rome, 28 October 2016
Scaling Symfony apps
WHO AM I?
Matteo Moretti
CTO @
website: madisoft.it
tech blog: labs.madisoft.it
Scalability
It’s from experience.
There are no lessons.
Nuvola
● > 3M HTTP requests / day
● ~ 1000 databases
● ~ 350GB mysql data
● ~ 180M query / day
● ~ 25M of media files
● ~ 4.50TB of medis files
● From ~5k to ~200k sessions in 5 minutes
Scalability
Your app is scalable if it can adapt to
support an increasing amount of data
or a growing number of users.
“But… I don’t have an increasing load”
(http://www.freepik.com/free-photos-vectors/smile - Smile vector designed by Freepik)
“Scalability doesn’t matter to you.”
(http://www.freepik.com/free-photos-vectors/smile - Smile vector designed by Freepik)
Scaling symfony apps
“I do have an increasing load”
(http://www.freepik.com/free-photos-vectors/smile - Smile vector designed by Freepik)
Your app is growing
But… suddenly…
Scaling symfony apps
Scaling symfony apps
Scaling symfony apps
Scaling symfony apps
Ok, we need to scale
Scaling… what?
PHP code?
Database?
Sessions?
Storage?
Async tasks?
Everything?
Can Node.js scale?
Can Symfony scale?
Can PHP scale?
Scaling is about
app architecture
App architecture
How can you scale your web server if
you put everything inside?
Database, user files, sessions, ...
App architecture / Decouple
● Decouple services
● Service: do one thing and do it well
App architecture / Decouple
4 main areas
1. web server
2. sessions
3. database
4. filesystem
There are some more (http caching, frontend, queue systems, etc): next talk!
Web server
Many small webservers
(scale up vs scale out)
Web server
NGINX + php-fpm
PHP 7
Symfony 3
Web server / Cache
PHP CACHE
SYMFONY CACHE
DOCTRINE CACHE
Web server / PHP Cache
Opcache
Bytecode caching
opcache.enable = On
opcache.validate_timestamps = 0
https://tideways.io/profiler/blog/fine-tune-your-opcache-configuration-to-avoid-caching-suprises
PHP code / Symfony cache
● Put Symfony cache in ram
● Use cache warmers during deploy
releaseN/var/cache -> /var/www/project/cache/releaseN
“/etc/fstab”
tmpfs /var/www/project/cache tmpfs size=512m
PHP code / Doctrine cache
● Configure Doctrine to use cache
● Disable Doctrine logging and profiling on prod
doctrine.orm.default_metadata_cache:
type: apc
doctrine.orm.default_query_cache:
type: apc
doctrine.orm.default_result_cache:
type: apc
PHP code / Cache
DISK I/O ~ 0%
Monitor
Measure
Analyze
PHP code / Profiling
XHProf
Blackfire
New Relic
Scaling symfony apps
Scaling symfony apps
PHP code / Recap
● Easy
● No need to change your PHP code
● It’s most configuration and tuning
● You can do one by one and measure how it affects performance
● Need to monitor and profile: New Relic for PHP
● Don’t waste time on micro-optimization
Take away: use cache!
Sessions
● Think session management as a service
● Use centralized Memcached or Redis (Ec2
or ElasticCache on AWS)
● Avoid sticky sessions (load balancer set up)
Session / Memcached
No bundle required
https://labs.madisoft.it/scaling-symfony-sessions-with-memcached/
Session / Redis
https://github.com/snc/SncRedisBundle
https://labs.madisoft.it/scaling-symfony-sessions-with-redis/
Session / Redis
config.yml
framework:
session:
handler_id: snc_redis.session.handler
Session / Redis
Bundle config
snc_redis:
clients:
session_client:
dsn: '%redis_dsn_session%'
logging: false # https://github.com/snc/SncRedisBundle/issues/161
type: phpredis
session:
client: session_client
locking: false
prefix: session_prefix_
ttl: '%session_ttl%'
Session / Redis
parameters.yml
redis_db: 3
redis_dsn_session: 'redis://%redis_ip%/%redis_db%'
redis_ip: redis-cluster.my-lan.com
session_ttl: 86400
Session / Recap
● Very easy
● No need to change your PHP code
● Redis better than Memcached: it has persistence and many other features
● Let AWS scale for you and deal with failover and sysadmin stuff
Take away: use Redis
Database
Aka “The bottleneck”
Database
Relational databases
Database
NOSQL db?
Database
If you need data integrity do
not replace your SQL db with
NOSQL to scale
Database
How to scale SQL db?
Database
When to scale?
Database
If dbsize < 10 GB
dont_worry();
Database / Big db problems
● Very slow backup. High lock time
● If mysql crashes, restart takes time
● It takes time to download and restore in dev
● You need expensive hardware (mostly RAM)
Database / Short-term solutions
Use a managed db service like AWS RDS
● It scales for you
● It handles failover and backup for you
But:
● It’s expensive for big db
● Problems are only mitigated but they are still there
Database / Long-term solutions
Sharding
Database / Sharding
Split a single big db into
many small dbs
(multi-tenant)
Database / Sharding
● Very fast backuo. Low lock time
● If mysql crashes, restart takes little time
● Fast to download and restore in dev
● No need of expensive hardware
● You arrange your dbs on many machines
Database / Sharding
● How can Symfony deal with them?
● How to execute a cli command on one of them?
● How to apply a migration (ie: add column) to 1000 dbs?
● …...
Database / Sharding
Doctrine DBAL & ORM
Database / Sharding
Define a DBAL connection and a ORM
entity manager for each db
https://symfony.com/doc/current/doctrine/multiple_entity_managers.html
Database / Sharding
doctrine:
orm:
entity_managers:
global:
connection: global
shard1:
connection: shard1
shard2:
connection: shard2
doctrine:
dbal:
connections:
global:
…..
shard1:
……
shard2:
…...
default_connection: global
Database / Sharding
This works for few dbs
(~ <5)
Database / Sharding
Doctrine sharding
http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/sharding.html
Database / Doctrine sharding
● Suited for multi-tenant applications
● Global database to store shared data (ie: user data)
● Need to use uuid
http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/sharding.html
Database / Sharding
Configuration
doctrine:
dbal:
default_connection: global
connections:
default:
shard_choser_service: vendor.app.shard_choser
shards:
shard1:
id: 1
host / user / dbname
shard2:
id: 2
host / user / dbname
Database / Sharding
ShardManager Interface
$shardManager = new PoolingShardManager();
$currentCustomerId = 3;
$shardManager->selectShard($currentCustomerId);
// all queries after this call hit the shard where customer
// with id 3 is on
$shardManager->selectGlobal();
// the global db is selected
Database / Sharding
● It works but it’s complex to be managed
● No documentation everywhere
● Need to manage shard configuration: adding a new
shard?
● Need to parallelize shard migrations: Gearman?
● Deal with sharding in test environment
Database / Recap
● NOSQL is not used to scale SQL: they have different purposes. You can
use both.
● Sharding is difficult to implement
● Need to change your code
● Short-term solution is to use AWS to leverage some maintenance
● Doctrine ORM sharding works well but you need to write code and
wrappers. Best suited for multi-tenant apps
● When it’s done, you can scale without any limit
Take away: do sharding if your REALLY need it
Filesystem
Users upload files: documents, media, etc
How to handle them?
Filesystem
● Need of filesystem abstraction
● Use external object storage like S3
● Avoid using NAS: it’s tricky to be set-up correctly
Filesystem / Abstraction
● FlysystemBundle
● KnpGaufretteBundle
https://github.com/1up-lab/OneupFlysystemBundle
Filesystem / Abstraction
https://github.com/1up-lab/OneupFlysystemBundle
● AWS S3
● Dropbox
● FTP
● Local filesystem
● ...
Filesystem / Abstraction
Configuration
oneup_flysystem:
adapters:
s3_adapter:
awss3v3:
client: s3_client
bucket: "%s3_bucket%"
oneup_flysystem:
adapters:
local_adapater:
local:
directory: ‘myLocalDir’
Filesystem / Abstraction
Configuration
prod.yml
oneup_flysystem:
filesystems:
my_filesystem:
adapter: s3_adapter
dev.yml
oneup_flysystem:
filesystems:
my_filesystem:
adapter: local_adapter
Filesystem / Abstraction
Usage
// LeagueFlysystemFilesystemInterface
$filesystem = $container->get(‘oneup_flysystem.my_filesystem’);
$path = ‘myFilePath’;
$filesystem->has($path);
$filesystem->read($path);
$filesystem->write($path, $contents);
Filesystem / Recap
● Easy
● Need to change your PHP code
● Ready-made bundles
● Avoid local filesystem and NAS
Take away: use FlystemBundle with S3
Scaling / Recap
● Sessions and filesystem: easy. Do it
● PHP code: not difficult. Think of it. Save money.
● Database: very hard. Think a lot
● Queue systems, http cache and some other stuff: next
talk but think of them as services
THANK YOU
WE ARE HIRING!
(wanna join? ask us or visit our website)
QUESTIONS?

More Related Content

PDF
Compute shader
PPTX
게임프로젝트에 적용하는 GPGPU
PDF
Design Patterns in React
PPTX
[Unite2015 박민근] 유니티 최적화 테크닉 총정리
PDF
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
PDF
webpack 101 slides
PDF
Ndc2010 전형규 마비노기2 캐릭터 렌더링 기술
PDF
Managing secrets at scale
Compute shader
게임프로젝트에 적용하는 GPGPU
Design Patterns in React
[Unite2015 박민근] 유니티 최적화 테크닉 총정리
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
webpack 101 slides
Ndc2010 전형규 마비노기2 캐릭터 렌더링 기술
Managing secrets at scale

What's hot (20)

PDF
Puppeteer can automate that! - Frontmania
PDF
[KubeCon EU 2020] containerd Deep Dive
PDF
Docker Security and Content Trust
PPTX
마른 하늘에 날구름 넣기
PDF
NDC 2015 삼시세끼 빌드만들기
PDF
Securing Prometheus exporters using HashiCorp Vault
PPTX
WebAssembly WASM Introduction Presentation
PDF
Intro to react native
PDF
Introduction to rust: a low-level language with high-level abstractions
PPTX
Webpack Introduction
PDF
MMOG Server-Side 충돌 및 이동처리 설계와 구현
PDF
Raphael.js로 SVG 차트 만들기
PDF
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기
PDF
DBI-Assisted Android Application Reverse Engineering
PPTX
Hierachical z Map Occlusion Culling
PDF
Hexagonal architecture - message-oriented software design
PDF
Implements BIOS emulation support for BHyVe
PPT
Shadow mapping 정리
PPTX
Compute shader DX11
PPTX
Ue4 에서의 환경변화 구현
Puppeteer can automate that! - Frontmania
[KubeCon EU 2020] containerd Deep Dive
Docker Security and Content Trust
마른 하늘에 날구름 넣기
NDC 2015 삼시세끼 빌드만들기
Securing Prometheus exporters using HashiCorp Vault
WebAssembly WASM Introduction Presentation
Intro to react native
Introduction to rust: a low-level language with high-level abstractions
Webpack Introduction
MMOG Server-Side 충돌 및 이동처리 설계와 구현
Raphael.js로 SVG 차트 만들기
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기
DBI-Assisted Android Application Reverse Engineering
Hierachical z Map Occlusion Culling
Hexagonal architecture - message-oriented software design
Implements BIOS emulation support for BHyVe
Shadow mapping 정리
Compute shader DX11
Ue4 에서의 환경변화 구현
Ad

Viewers also liked (20)

PDF
Speed up your Symfony2 application and build awesome features with Redis
PDF
SaaS con Symfony2
PDF
Nuvola: a tale of migration to AWS
PDF
Filesystem Abstraction with Flysystem
ODP
How to Clear Cache in a Symfony Cross Application
PDF
Multi kernelowa aplikacja w oparciu o Symfony 3 i microkernele
PPTX
Créer une API GraphQL avec Symfony
PDF
(micro)services avec Symfony et Tolerance
PPS
Lets see the reality around us
DOCX
Excel trick
PDF
พีระมิด
PPTX
Gross u11a3
PDF
กรวย
PDF
ทรงกลม
PPTX
Prolog (present)
PPTX
Demo: How to make air refreshener ? (Powder form & Spray form)
PPT
Diapositivas
PPTX
Презентация слайды2
DOCX
Research 2
PPT
Speed up your Symfony2 application and build awesome features with Redis
SaaS con Symfony2
Nuvola: a tale of migration to AWS
Filesystem Abstraction with Flysystem
How to Clear Cache in a Symfony Cross Application
Multi kernelowa aplikacja w oparciu o Symfony 3 i microkernele
Créer une API GraphQL avec Symfony
(micro)services avec Symfony et Tolerance
Lets see the reality around us
Excel trick
พีระมิด
Gross u11a3
กรวย
ทรงกลม
Prolog (present)
Demo: How to make air refreshener ? (Powder form & Spray form)
Diapositivas
Презентация слайды2
Research 2
Ad

Similar to Scaling symfony apps (20)

PDF
Scaling PHP apps
PDF
Scaling with Symfony - PHP UK
PDF
Symfony Live San Francisco 2017 - Symfony @ OpenSky
PDF
meetPHP#8 - PHP startups prototypes
PPTX
Scalability
PPTX
A soa approximation on symfony
PPTX
A SOA approximation on symfony
PPTX
Black Friday and Cyber Monday- Best Practices for Your E-Commerce Database
KEY
Mongo db bangalore 2012
KEY
Developing Web Apps with Symfony2, Doctrine and MongoDB
PPTX
Models in symfony
PPTX
SOA with PHP and Symfony
PPTX
PHP Symfony MicroServices Migration @MeeticTech
PDF
SymfonyCon Cluj 2017 - Symfony at OpenSky
PDF
Optimera STHLM 2011 - Mikael Berggren, Spotify
PDF
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
PDF
2019 StartIT - Boosting your performance with Blackfire
PDF
Develop and deploy using Hybrid Cloud Strategies confoo2012
PDF
Improve your web and app development with the Symfony3 framework.
PDF
Scaling PHP apps
Scaling with Symfony - PHP UK
Symfony Live San Francisco 2017 - Symfony @ OpenSky
meetPHP#8 - PHP startups prototypes
Scalability
A soa approximation on symfony
A SOA approximation on symfony
Black Friday and Cyber Monday- Best Practices for Your E-Commerce Database
Mongo db bangalore 2012
Developing Web Apps with Symfony2, Doctrine and MongoDB
Models in symfony
SOA with PHP and Symfony
PHP Symfony MicroServices Migration @MeeticTech
SymfonyCon Cluj 2017 - Symfony at OpenSky
Optimera STHLM 2011 - Mikael Berggren, Spotify
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
2019 StartIT - Boosting your performance with Blackfire
Develop and deploy using Hybrid Cloud Strategies confoo2012
Improve your web and app development with the Symfony3 framework.

Recently uploaded (20)

PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
System and Network Administraation Chapter 3
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Online Work Permit System for Fast Permit Processing
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Understanding Forklifts - TECH EHS Solution
PDF
top salesforce developer skills in 2025.pdf
PTS Company Brochure 2025 (1).pdf.......
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
How to Choose the Right IT Partner for Your Business in Malaysia
2025 Textile ERP Trends: SAP, Odoo & Oracle
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Design an Analysis of Algorithms II-SECS-1021-03
How Creative Agencies Leverage Project Management Software.pdf
System and Network Administraation Chapter 3
Wondershare Filmora 15 Crack With Activation Key [2025
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Odoo POS Development Services by CandidRoot Solutions
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
ISO 45001 Occupational Health and Safety Management System
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Online Work Permit System for Fast Permit Processing
Softaken Excel to vCard Converter Software.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Understanding Forklifts - TECH EHS Solution
top salesforce developer skills in 2025.pdf

Scaling symfony apps