Massively Scaled High Performance Web Services with PHP

Demin Yin
Demin YinSoftware Engineer at Electronic Arts
Massively Scaled High Performance Web Services
with PHP
Demin Yin
https://joind.in/talk/e81e7
• Staff Engineer and Technical Lead on Glu Mobile’s Design Home team.
• Playing with PHP since 2000.
• Worked for a diverse group of companies in China and US, including eBay, Visa and Glu.
• Focus on building high performance, secure web services.
• Born in China, worked in U.S., live in Canada.
• On twitter: @deminy
• On Github: https://github.com/deminy
About Me
2
● An Overview on Design Home and the Inbox Service
● The Inbox Service: Key Improvements Made
1. Web Server: Dockerized PHP 7 containers
2. HTTP Processing: Background processing, HTTP compression, and more
3. Data Storage: Doing NoSQL with Redis and Couchbase
4. Hardware and Network: Migrating to Amazon Web Services
● Next
● Q&A
Agenda
3
● An Overview on Design Home and the Inbox Service
● The Inbox Service: Key Improvements Made
1. Web Server: Dockerized PHP 7 containers
2. HTTP Processing: Background processing, HTTP compression, and more
3. Data Storage: Doing NoSQL with Redis and Couchbase
4. Hardware and Network: Migrating to Amazon Web Services
● Next
● Q&A
Agenda
4
• Launched in Q4 2016.
• #1 Top Free and #7 Top Grossing game in the U.S. App Store for iPhone.
• #1 Top Free and #23 Top Grossing game in the U.S. Google Play Store.
• 1M+ daily active users; 40M votes daily; 1 billion designs to date.
• 100,000 API calls per minute; 60 56 ms response time on average.
Design Home:
Top-ranked Mobile Game with PHP Backend
5
Inbox
Localization
Receipt Validation
Moderation
Email
E-commerce
Event Logging
Main
Service
……
Database
Client
Client
Client
Client
Client
Client
Client
Design Home: List of Backend Services
6
● REST APIs with different CRUD endpoints to manage inbox messages.
● PHP 7, Nginx, Composer, NoSQL, Docker, AWS, Development Tools, ……
● NoSQL: Redis + Couchbase.
● One of the busiest microservices.
Average Requests: 14k rpm
Peak Requests: 34k rpm
Response Time: less than 9ms
The Inbox Service: Technical Overview
7
The Inbox Service: Technical Overview (cont.)
● PHP 7.
● Composer.
● Opcache.
● Data cache: APCu, distributed cache and chained cache.
● Tests in place.
● Unit tests.
● Blackbox tests, or feature tests, or functional tests.
● PHP The Right Way: Follow good coding practices including design patterns.
8
● An Overview on Design Home and the Inbox Service
● The Inbox Service: Key Improvements Made
1. Web Server: Dockerized PHP 7 containers
2. HTTP Processing: Background processing, HTTP compression, and more
3. Data Storage: Doing NoSQL with Redis and Couchbase
4. Hardware and Network: Migrating to Amazon Web Services
● Next
● Q&A
Agenda
9
Hardware & Network
● Migrate to Amazon ECS.
● Hardware upgrade.
● Move everything into VPC.
The Inbox Service: Key Improvements Made
HTTP Processing
● Use background processing.
● Use HTTP compression (gzip).
● Dynamic content caching.
Web Server Instances
● Decouple microservices.
● Dockerize the microservices.
● Development Tools Integration.
Data Storage
● NoSQL solutions.
● Fight against IO and disk space.
● Faster PHP drivers.
10
● An Overview on Design Home and the Inbox Service
● The Inbox Service: Key Improvements Made
1. Web Server: Dockerized PHP 7 containers
2. HTTP Processing: Background processing, HTTP compression, and more
3. Data Storage: Doing NoSQL with Redis and Couchbase
4. Hardware and Network: Migrating to Amazon Web Services
● Next
● Q&A
Agenda
11
1.1. Decouple Microservices
Inbox
Localization
Receipt Validation
Moderation
Email
E-commerce
Event Logging
Main
Service
……
Database
Client
Client
Client
Client
Client
Client
Client
12
• Improved and simplified development environments.
• Easier to upgrade web server and PHP environments.
• Easier to troubleshoot and debug issues.
1.2. Dockerized Microservices
13
1.2. Dockerized Microservices (cont.)
14
Base Images
HTTP/REST microservices
asynchronous microservices
job worker instances
1.2. Dockerized Microservices (cont.)
Specification:
1. Tags match with PHP versions.
2. Tag latest is never used.
3. Freeze tagged images once
used.
4. Images are built and tagged
manually.
Benefits:
1. Less efforts to build images for
different microservices.
2. Easy and safe to upgrade to
new versions of PHP.
3. Easier to fix security
vulnerabilities.
4. Easier to make improvements
across different microservices.
15
Base Images
● Error Handling, Error Reporting and System Monitoring
○ New Relic
○ Bugsnag
○ Amazon CloudWatch
● Security Check
○ SonarQube
○ SensioLabs Security Checker
● Debugging and Profiling: Blackfire, Xdebug, etc.
1.3. Development Tools Integration
16
● An Overview on Design Home and the Inbox Service
● The Inbox Service: Key Improvements Made
1. Web Server: Dockerized PHP 7 containers
2. HTTP Processing: Background processing, HTTP compression, and more
3. Data Storage: Doing NoSQL with Redis and Couchbase
4. Hardware and Network: Migrating to Amazon Web Services
● Next
● Q&A
Agenda
17
● Use cases: error handling, data reporting, outgoing emails, push notifications, etc.
● Common approaches:
● Execute external program.
● Register shutdown functions.
● Job server (Gearman, Resque, RabbitMQ, etc.).
● Function fastcgi_finish_request() under PHP-FPM.
● …...
2.1. Background Processing
exec("nohup ./http.sh > /dev/null &");
18
2.1. Background Processing (cont.)
Output: 1234 Output: 1
19
2.1. Background Processing (cont.)
Average Response Time
Without background processing: 13 ms
With background processing: 9 ms
20
How to prevent and address failed operations properly?
● Basic data validation first.
● Exponential backoff.
● https://github.com/Crowdstar/exponential-backoff
● Proper error reporting.
2.1. Background Processing (cont.)
21
For more details, please check
• Background Processing: https://github.com/Crowdstar/background-processing
• Technical Discussion: https://github.com/deminy/background-processing-in-php
2.1. Background Processing (cont.)
22
2.2. HTTP Compression
23
2.2. HTTP Compression
gzip on;
24
2.2. HTTP Compression (cont.)
gzip on;
gzip_types text/plain text/css application/json text/xml application/xml application/xml+rss
text/javascript;
25
2.2. HTTP Compression (cont.)
gzip on;
gzip_types text/plain text/css application/json text/xml application/xml application/xml+rss
text/javascript;
gzip_proxied any;
26
2.2. HTTP Compression (cont.)
gzip on;
gzip_types text/plain text/css application/json text/xml application/xml application/xml+rss
text/javascript;
gzip_proxied any;
gzip_comp_level 5;
gzip_min_length 1280;
27
2.2. HTTP Compression (cont.)
If HTTP header ‘Content-Length’ is not set in a PHP response, Nginx will always compress the
response even its length is less than the minimum length.
• Slim 3 always has HTTP header ‘Content-Length’ set by default.
• Laravel and Lumen don’t have HTTP header ‘Content-Length’ set.
28
2.2. HTTP Compression (cont.)
A Lumen Middleware to Make HTTP Compression Work as Should
29
2.3. Dynamic Content Caching
Challenge: feed new data to the client.
Possible Solutions:
● Server push, but it’s not supported in HTTP 1 (It’s supported under HTTP 2 and the WebSocket API).
● HTTP Clients built on top of HTTP 1 have to hit servers again and again to check and fetch new data.
Our Approach:
● Data cache on the server side if OK.
● Use the Last-Modified and If-Modified-Since headers, and return HTTP 304 "Not Modified" if no need to
retransmit the requested resources.
30
2.3. Dynamic Content Caching (cont.)
Related HTTP headers:
● If-None-Match, If-Unmodified-Since
● Cache-Control
● Content-Location
● ETag
● Expires
● Vary
● …...
31
● An Overview on Design Home and the Inbox Service
● The Inbox Service: Key Improvements Made
1. Web Server: Dockerized PHP 7 containers
2. HTTP Processing: Background processing, HTTP compression, and more
3. Data Storage: Doing NoSQL with Redis and Couchbase
4. Hardware and Network: Migrating to Amazon Web Services
● Next
● Q&A
Agenda
32
● Lots of choices: Redis, Couchbase, Aerospike, MongoDB, …
● Our selection and implementation: Redis and Couchbase.
● Redis.
● Couchbase.
● Concerns with NoSQL
○ limitations on queries.
○ indexes.
○ serialization and compression.
3.1. NoSQL
33
• Data compression to reduce network IO and save disk space.
• Compress larger messages before saving.
• Couchbase encoder (serialization).
• Use message templates.
• Shorten field names.
• Add ttl (time to live) on certain messages (to expire messages).
3.2. Fight Against IO and Disk Space
34
• PhpRedis: the PHP extension for Redis.
• Predis: the Redis client written in PHP.
• Other drivers
• Package predis/predis-async: asynchronous (non-blocking) version of Predis built on
top of ReactPHP.
• Class SwooleCoroutineRedis: the asynchronous Redis Client from Swoole.
3.3. Faster PHP Drivers (Redis)
35
3.3. Faster PHP Drivers (Redis)
Before and after switching from Predis to PhpRedis
Average request time reduced from 16 ms to 11 ms
36
● An Overview on Design Home and the Inbox Service
● The Inbox Service: Key Improvements Made
1. Web Server: Dockerized PHP 7 containers
2. HTTP Processing: Background processing, HTTP compression, and more
3. Data Storage: Doing NoSQL with Redis and Couchbase
4. Hardware and Network: Migrating to Amazon Web Services
● Next
● Q&A
Agenda
37
4.1. Deployment with Amazon ECS
How did we do code deployment before?
38
Benefits:
• Zero downtime deployments.
• Quick rollback.
• ELB health checks.
• Autoscaling.
4.1. Deployment with Amazon ECS (cont.)
39
• Multiple deployment environments in AWS: test, dev, RC, staging, and production.
• Staging environment is helpful.
• to do some final tests before major production deployments.
• to reproduce and identify production issues.
4.1. Deployment with Amazon ECS (cont.)
40
4.2. Hardware Upgrade
Feb 2018: upgraded API servers with faster ones
(c5.xlarge: 4 vCPU, 8GB memory; Enhanced networking enabled)
41
• Place instances closer to each other.
• Move instances to same locations (Availability Zones).
• Use internal network instead of Internet to communicate.
4.3. Move Everything into VPC
42
4.3. Move Everything into VPC (cont.)
Jan 2019: upgraded API servers with faster ones that were closer to the database nodes (same zone)
In the main service, Couchbase operation time decreased to 5 ms
43
● An Overview on Design Home and the Inbox Service
● The Inbox Service: Key Improvements Made
1. Web Server: Dockerized PHP 7 containers
2. HTTP Processing: Background processing, HTTP compression, and more
3. Data Storage: Doing NoSQL with Redis and Couchbase
4. Hardware and Network: Migrating to Amazon Web Services
● Next
● Q&A
Agenda
44
There are always rooms to
push the limit of PHP
45
• PHP-FPM
• Asynchronous I/O
• Swoole
• Network Protocols
• HTTP/2
• Tars
Next
46
● An Overview on Design Home and the Inbox Service
● The Inbox Service: Key Improvements Made
1. Web Server: Dockerized PHP 7 containers
2. HTTP Processing: Background processing, HTTP compression, and more
3. Data Storage: Doing NoSQL with Redis and Couchbase
4. Hardware and Network: Migrating to Amazon Web Services
● Next
● Q&A
Agenda
47
https://joind.in/talk/e81e7
Questions?
48
Thanks
https://joind.in/talk/e81e7
49
1 of 49

Recommended

NginX - good practices, tips and advanced techniques by
NginX - good practices, tips and advanced techniquesNginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniquesClaudio Borges
1.7K views26 slides
Nginx Internals by
Nginx InternalsNginx Internals
Nginx InternalsJoshua Zhu
59.7K views61 slides
Node js by
Node jsNode js
Node jsRohan Chandane
3K views29 slides
Extending functionality in nginx, with modules! by
Extending functionality in nginx, with modules!Extending functionality in nginx, with modules!
Extending functionality in nginx, with modules!Trygve Vea
10.5K views61 slides
MongoDB backup service overview Boston MUG by
MongoDB backup service overview Boston MUGMongoDB backup service overview Boston MUG
MongoDB backup service overview Boston MUGMongoDB
1.7K views20 slides
MySQL Replication — Advanced Features / Петр Зайцев (Percona) by
MySQL Replication — Advanced Features / Петр Зайцев (Percona)MySQL Replication — Advanced Features / Петр Зайцев (Percona)
MySQL Replication — Advanced Features / Петр Зайцев (Percona)Ontico
429 views64 slides

More Related Content

What's hot

[245] presto 내부구조 파헤치기 by
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
10.1K views50 slides
Elephant Roads: a tour of Postgres forks by
Elephant Roads: a tour of Postgres forksElephant Roads: a tour of Postgres forks
Elephant Roads: a tour of Postgres forksCommand Prompt., Inc
5.9K views53 slides
Spilo, отказоустойчивый PostgreSQL кластер / Oleksii Kliukin (Zalando SE) by
Spilo, отказоустойчивый PostgreSQL кластер / Oleksii Kliukin (Zalando SE)Spilo, отказоустойчивый PostgreSQL кластер / Oleksii Kliukin (Zalando SE)
Spilo, отказоустойчивый PostgreSQL кластер / Oleksii Kliukin (Zalando SE)Ontico
3.8K views55 slides
Automating Complex Setups with Puppet by
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with PuppetKris Buytaert
1.2K views39 slides
Integrated Cache on Netscaler by
Integrated Cache on NetscalerIntegrated Cache on Netscaler
Integrated Cache on NetscalerMark Hillick
15.6K views49 slides
Shootout at the AWS Corral by
Shootout at the AWS CorralShootout at the AWS Corral
Shootout at the AWS CorralPostgreSQL Experts, Inc.
3.3K views90 slides

What's hot(20)

[245] presto 내부구조 파헤치기 by NAVER D2
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
NAVER D210.1K views
Spilo, отказоустойчивый PostgreSQL кластер / Oleksii Kliukin (Zalando SE) by Ontico
Spilo, отказоустойчивый PostgreSQL кластер / Oleksii Kliukin (Zalando SE)Spilo, отказоустойчивый PostgreSQL кластер / Oleksii Kliukin (Zalando SE)
Spilo, отказоустойчивый PostgreSQL кластер / Oleksii Kliukin (Zalando SE)
Ontico3.8K views
Automating Complex Setups with Puppet by Kris Buytaert
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with Puppet
Kris Buytaert1.2K views
Integrated Cache on Netscaler by Mark Hillick
Integrated Cache on NetscalerIntegrated Cache on Netscaler
Integrated Cache on Netscaler
Mark Hillick15.6K views
Large Scale Log collection using LogStash & mongoDB by Gaurav Bhardwaj
Large Scale Log collection using LogStash & mongoDB Large Scale Log collection using LogStash & mongoDB
Large Scale Log collection using LogStash & mongoDB
Gaurav Bhardwaj4.9K views
Pragmatic Monolith-First, easy to decompose, clean architecture by Piotr Pelczar
Pragmatic Monolith-First, easy to decompose, clean architecturePragmatic Monolith-First, easy to decompose, clean architecture
Pragmatic Monolith-First, easy to decompose, clean architecture
Piotr Pelczar4K views
Testing applications with traffic control in containers / Alban Crequy (Kinvolk) by Ontico
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)Testing applications with traffic control in containers / Alban Crequy (Kinvolk)
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)
Ontico986 views
How to monitor NGINX by Server Density
How to monitor NGINXHow to monitor NGINX
How to monitor NGINX
Server Density170.8K views
plProxy, pgBouncer, pgBalancer by elliando dias
plProxy, pgBouncer, pgBalancerplProxy, pgBouncer, pgBalancer
plProxy, pgBouncer, pgBalancer
elliando dias7.1K views
vert.x 소개 및 개발 실습 by John Kim
vert.x 소개 및 개발 실습vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습
John Kim2.8K views
Apache Traffic Server by supertom
Apache Traffic ServerApache Traffic Server
Apache Traffic Server
supertom20.8K views
SaltConf 2014: Safety with powertools by Thomas Jackson
SaltConf 2014: Safety with powertoolsSaltConf 2014: Safety with powertools
SaltConf 2014: Safety with powertools
Thomas Jackson1.4K views
High Concurrency Architecture and Laravel Performance Tuning by Albert Chen
High Concurrency Architecture and Laravel Performance TuningHigh Concurrency Architecture and Laravel Performance Tuning
High Concurrency Architecture and Laravel Performance Tuning
Albert Chen20K views

Similar to Massively Scaled High Performance Web Services with PHP

Dockerizing Aurea - Docker Con EU 2017 by
Dockerizing Aurea - Docker Con EU 2017Dockerizing Aurea - Docker Con EU 2017
Dockerizing Aurea - Docker Con EU 2017Matias Lespiau
533 views32 slides
Criteo Labs Infrastructure Tech Talk Meetup Nov. 7 by
Criteo Labs Infrastructure Tech Talk Meetup Nov. 7Criteo Labs Infrastructure Tech Talk Meetup Nov. 7
Criteo Labs Infrastructure Tech Talk Meetup Nov. 7Shuo LI
230 views100 slides
Scaling 100PB Data Warehouse in Cloud by
Scaling 100PB Data Warehouse in CloudScaling 100PB Data Warehouse in Cloud
Scaling 100PB Data Warehouse in CloudChangshu Liu
368 views38 slides
Monkey Server by
Monkey ServerMonkey Server
Monkey ServerEduardo Silva Pereira
1.7K views63 slides
#RADC4L16: An API-First Archives Approach at NPR by
#RADC4L16: An API-First Archives Approach at NPR#RADC4L16: An API-First Archives Approach at NPR
#RADC4L16: An API-First Archives Approach at NPRCamille Salas
1.2K views27 slides
MySQL X protocol - Talking to MySQL Directly over the Wire by
MySQL X protocol - Talking to MySQL Directly over the WireMySQL X protocol - Talking to MySQL Directly over the Wire
MySQL X protocol - Talking to MySQL Directly over the WireSimon J Mudd
3.3K views60 slides

Similar to Massively Scaled High Performance Web Services with PHP(20)

Dockerizing Aurea - Docker Con EU 2017 by Matias Lespiau
Dockerizing Aurea - Docker Con EU 2017Dockerizing Aurea - Docker Con EU 2017
Dockerizing Aurea - Docker Con EU 2017
Matias Lespiau533 views
Criteo Labs Infrastructure Tech Talk Meetup Nov. 7 by Shuo LI
Criteo Labs Infrastructure Tech Talk Meetup Nov. 7Criteo Labs Infrastructure Tech Talk Meetup Nov. 7
Criteo Labs Infrastructure Tech Talk Meetup Nov. 7
Shuo LI230 views
Scaling 100PB Data Warehouse in Cloud by Changshu Liu
Scaling 100PB Data Warehouse in CloudScaling 100PB Data Warehouse in Cloud
Scaling 100PB Data Warehouse in Cloud
Changshu Liu368 views
#RADC4L16: An API-First Archives Approach at NPR by Camille Salas
#RADC4L16: An API-First Archives Approach at NPR#RADC4L16: An API-First Archives Approach at NPR
#RADC4L16: An API-First Archives Approach at NPR
Camille Salas1.2K views
MySQL X protocol - Talking to MySQL Directly over the Wire by Simon J Mudd
MySQL X protocol - Talking to MySQL Directly over the WireMySQL X protocol - Talking to MySQL Directly over the Wire
MySQL X protocol - Talking to MySQL Directly over the Wire
Simon J Mudd3.3K views
Maximizing PHP Performance with NGINX by NGINX, Inc.
Maximizing PHP Performance with NGINXMaximizing PHP Performance with NGINX
Maximizing PHP Performance with NGINX
NGINX, Inc.1.8K views
PAC 2019 virtual Mark Tomlinson by Neotys
PAC 2019 virtual Mark TomlinsonPAC 2019 virtual Mark Tomlinson
PAC 2019 virtual Mark Tomlinson
Neotys188 views
12-Step Program for Scaling Web Applications on PostgreSQL by Konstantin Gredeskoul
12-Step Program for Scaling Web Applications on PostgreSQL12-Step Program for Scaling Web Applications on PostgreSQL
12-Step Program for Scaling Web Applications on PostgreSQL
Konstantin Gredeskoul69.1K views
AOUG_11Nov2016_Challenges_with_EBS12_2 by Sean Braymen
AOUG_11Nov2016_Challenges_with_EBS12_2AOUG_11Nov2016_Challenges_with_EBS12_2
AOUG_11Nov2016_Challenges_with_EBS12_2
Sean Braymen1.2K views
Website & Internet + Performance testing by Roman Ananev
Website & Internet + Performance testingWebsite & Internet + Performance testing
Website & Internet + Performance testing
Roman Ananev44 views
Netflix Open Source Meetup Season 4 Episode 2 by aspyker
Netflix Open Source Meetup Season 4 Episode 2Netflix Open Source Meetup Season 4 Episode 2
Netflix Open Source Meetup Season 4 Episode 2
aspyker19.4K views
Meteor Day Athens (2014-11-07) by svub
Meteor Day Athens (2014-11-07)Meteor Day Athens (2014-11-07)
Meteor Day Athens (2014-11-07)
svub336 views
1049: Best and Worst Practices for Deploying IBM Connections - IBM Connect 2016 by panagenda
1049: Best and Worst Practices for Deploying IBM Connections - IBM Connect 20161049: Best and Worst Practices for Deploying IBM Connections - IBM Connect 2016
1049: Best and Worst Practices for Deploying IBM Connections - IBM Connect 2016
panagenda893 views
Profiling and Tuning a Web Application - The Dirty Details by Achievers Tech
Profiling and Tuning a Web Application - The Dirty DetailsProfiling and Tuning a Web Application - The Dirty Details
Profiling and Tuning a Web Application - The Dirty Details
Achievers Tech8K views
The 5 most common reasons for a slow WordPress site and how to fix them – ext... by Otto Kekäläinen
The 5 most common reasons for a slow WordPress site and how to fix them – ext...The 5 most common reasons for a slow WordPress site and how to fix them – ext...
The 5 most common reasons for a slow WordPress site and how to fix them – ext...
Otto Kekäläinen1.8K views
RedisConf18 - Redis on Flash by Redis Labs
RedisConf18 - Redis on FlashRedisConf18 - Redis on Flash
RedisConf18 - Redis on Flash
Redis Labs458 views
Supporting Digital Media Workflows in the Cloud with Perforce Helix by Perforce
Supporting Digital Media Workflows in the Cloud with Perforce HelixSupporting Digital Media Workflows in the Cloud with Perforce Helix
Supporting Digital Media Workflows in the Cloud with Perforce Helix
Perforce466 views
PyConIE 2017 Writing and deploying serverless python applications by Cesar Cardenas Desales
PyConIE 2017 Writing and deploying serverless python applicationsPyConIE 2017 Writing and deploying serverless python applications
PyConIE 2017 Writing and deploying serverless python applications

Recently uploaded

Affiliate Marketing by
Affiliate MarketingAffiliate Marketing
Affiliate MarketingNavin Dhanuka
20 views30 slides
Amine el bouzalimi by
Amine el bouzalimiAmine el bouzalimi
Amine el bouzalimiAmine EL BOUZALIMI
5 views38 slides
How to think like a threat actor for Kubernetes.pptx by
How to think like a threat actor for Kubernetes.pptxHow to think like a threat actor for Kubernetes.pptx
How to think like a threat actor for Kubernetes.pptxLibbySchulze1
7 views33 slides
Marketing and Community Building in Web3 by
Marketing and Community Building in Web3Marketing and Community Building in Web3
Marketing and Community Building in Web3Federico Ast
15 views64 slides
hamro digital logics.pptx by
hamro digital logics.pptxhamro digital logics.pptx
hamro digital logics.pptxtupeshghimire
11 views36 slides
ARNAB12.pdf by
ARNAB12.pdfARNAB12.pdf
ARNAB12.pdfArnabChakraborty499766
5 views83 slides

Recently uploaded(10)

Massively Scaled High Performance Web Services with PHP

  • 1. Massively Scaled High Performance Web Services with PHP Demin Yin https://joind.in/talk/e81e7
  • 2. • Staff Engineer and Technical Lead on Glu Mobile’s Design Home team. • Playing with PHP since 2000. • Worked for a diverse group of companies in China and US, including eBay, Visa and Glu. • Focus on building high performance, secure web services. • Born in China, worked in U.S., live in Canada. • On twitter: @deminy • On Github: https://github.com/deminy About Me 2
  • 3. ● An Overview on Design Home and the Inbox Service ● The Inbox Service: Key Improvements Made 1. Web Server: Dockerized PHP 7 containers 2. HTTP Processing: Background processing, HTTP compression, and more 3. Data Storage: Doing NoSQL with Redis and Couchbase 4. Hardware and Network: Migrating to Amazon Web Services ● Next ● Q&A Agenda 3
  • 4. ● An Overview on Design Home and the Inbox Service ● The Inbox Service: Key Improvements Made 1. Web Server: Dockerized PHP 7 containers 2. HTTP Processing: Background processing, HTTP compression, and more 3. Data Storage: Doing NoSQL with Redis and Couchbase 4. Hardware and Network: Migrating to Amazon Web Services ● Next ● Q&A Agenda 4
  • 5. • Launched in Q4 2016. • #1 Top Free and #7 Top Grossing game in the U.S. App Store for iPhone. • #1 Top Free and #23 Top Grossing game in the U.S. Google Play Store. • 1M+ daily active users; 40M votes daily; 1 billion designs to date. • 100,000 API calls per minute; 60 56 ms response time on average. Design Home: Top-ranked Mobile Game with PHP Backend 5
  • 7. ● REST APIs with different CRUD endpoints to manage inbox messages. ● PHP 7, Nginx, Composer, NoSQL, Docker, AWS, Development Tools, …… ● NoSQL: Redis + Couchbase. ● One of the busiest microservices. Average Requests: 14k rpm Peak Requests: 34k rpm Response Time: less than 9ms The Inbox Service: Technical Overview 7
  • 8. The Inbox Service: Technical Overview (cont.) ● PHP 7. ● Composer. ● Opcache. ● Data cache: APCu, distributed cache and chained cache. ● Tests in place. ● Unit tests. ● Blackbox tests, or feature tests, or functional tests. ● PHP The Right Way: Follow good coding practices including design patterns. 8
  • 9. ● An Overview on Design Home and the Inbox Service ● The Inbox Service: Key Improvements Made 1. Web Server: Dockerized PHP 7 containers 2. HTTP Processing: Background processing, HTTP compression, and more 3. Data Storage: Doing NoSQL with Redis and Couchbase 4. Hardware and Network: Migrating to Amazon Web Services ● Next ● Q&A Agenda 9
  • 10. Hardware & Network ● Migrate to Amazon ECS. ● Hardware upgrade. ● Move everything into VPC. The Inbox Service: Key Improvements Made HTTP Processing ● Use background processing. ● Use HTTP compression (gzip). ● Dynamic content caching. Web Server Instances ● Decouple microservices. ● Dockerize the microservices. ● Development Tools Integration. Data Storage ● NoSQL solutions. ● Fight against IO and disk space. ● Faster PHP drivers. 10
  • 11. ● An Overview on Design Home and the Inbox Service ● The Inbox Service: Key Improvements Made 1. Web Server: Dockerized PHP 7 containers 2. HTTP Processing: Background processing, HTTP compression, and more 3. Data Storage: Doing NoSQL with Redis and Couchbase 4. Hardware and Network: Migrating to Amazon Web Services ● Next ● Q&A Agenda 11
  • 12. 1.1. Decouple Microservices Inbox Localization Receipt Validation Moderation Email E-commerce Event Logging Main Service …… Database Client Client Client Client Client Client Client 12
  • 13. • Improved and simplified development environments. • Easier to upgrade web server and PHP environments. • Easier to troubleshoot and debug issues. 1.2. Dockerized Microservices 13
  • 14. 1.2. Dockerized Microservices (cont.) 14 Base Images HTTP/REST microservices asynchronous microservices job worker instances
  • 15. 1.2. Dockerized Microservices (cont.) Specification: 1. Tags match with PHP versions. 2. Tag latest is never used. 3. Freeze tagged images once used. 4. Images are built and tagged manually. Benefits: 1. Less efforts to build images for different microservices. 2. Easy and safe to upgrade to new versions of PHP. 3. Easier to fix security vulnerabilities. 4. Easier to make improvements across different microservices. 15 Base Images
  • 16. ● Error Handling, Error Reporting and System Monitoring ○ New Relic ○ Bugsnag ○ Amazon CloudWatch ● Security Check ○ SonarQube ○ SensioLabs Security Checker ● Debugging and Profiling: Blackfire, Xdebug, etc. 1.3. Development Tools Integration 16
  • 17. ● An Overview on Design Home and the Inbox Service ● The Inbox Service: Key Improvements Made 1. Web Server: Dockerized PHP 7 containers 2. HTTP Processing: Background processing, HTTP compression, and more 3. Data Storage: Doing NoSQL with Redis and Couchbase 4. Hardware and Network: Migrating to Amazon Web Services ● Next ● Q&A Agenda 17
  • 18. ● Use cases: error handling, data reporting, outgoing emails, push notifications, etc. ● Common approaches: ● Execute external program. ● Register shutdown functions. ● Job server (Gearman, Resque, RabbitMQ, etc.). ● Function fastcgi_finish_request() under PHP-FPM. ● …... 2.1. Background Processing exec("nohup ./http.sh > /dev/null &"); 18
  • 19. 2.1. Background Processing (cont.) Output: 1234 Output: 1 19
  • 20. 2.1. Background Processing (cont.) Average Response Time Without background processing: 13 ms With background processing: 9 ms 20
  • 21. How to prevent and address failed operations properly? ● Basic data validation first. ● Exponential backoff. ● https://github.com/Crowdstar/exponential-backoff ● Proper error reporting. 2.1. Background Processing (cont.) 21
  • 22. For more details, please check • Background Processing: https://github.com/Crowdstar/background-processing • Technical Discussion: https://github.com/deminy/background-processing-in-php 2.1. Background Processing (cont.) 22
  • 25. 2.2. HTTP Compression (cont.) gzip on; gzip_types text/plain text/css application/json text/xml application/xml application/xml+rss text/javascript; 25
  • 26. 2.2. HTTP Compression (cont.) gzip on; gzip_types text/plain text/css application/json text/xml application/xml application/xml+rss text/javascript; gzip_proxied any; 26
  • 27. 2.2. HTTP Compression (cont.) gzip on; gzip_types text/plain text/css application/json text/xml application/xml application/xml+rss text/javascript; gzip_proxied any; gzip_comp_level 5; gzip_min_length 1280; 27
  • 28. 2.2. HTTP Compression (cont.) If HTTP header ‘Content-Length’ is not set in a PHP response, Nginx will always compress the response even its length is less than the minimum length. • Slim 3 always has HTTP header ‘Content-Length’ set by default. • Laravel and Lumen don’t have HTTP header ‘Content-Length’ set. 28
  • 29. 2.2. HTTP Compression (cont.) A Lumen Middleware to Make HTTP Compression Work as Should 29
  • 30. 2.3. Dynamic Content Caching Challenge: feed new data to the client. Possible Solutions: ● Server push, but it’s not supported in HTTP 1 (It’s supported under HTTP 2 and the WebSocket API). ● HTTP Clients built on top of HTTP 1 have to hit servers again and again to check and fetch new data. Our Approach: ● Data cache on the server side if OK. ● Use the Last-Modified and If-Modified-Since headers, and return HTTP 304 "Not Modified" if no need to retransmit the requested resources. 30
  • 31. 2.3. Dynamic Content Caching (cont.) Related HTTP headers: ● If-None-Match, If-Unmodified-Since ● Cache-Control ● Content-Location ● ETag ● Expires ● Vary ● …... 31
  • 32. ● An Overview on Design Home and the Inbox Service ● The Inbox Service: Key Improvements Made 1. Web Server: Dockerized PHP 7 containers 2. HTTP Processing: Background processing, HTTP compression, and more 3. Data Storage: Doing NoSQL with Redis and Couchbase 4. Hardware and Network: Migrating to Amazon Web Services ● Next ● Q&A Agenda 32
  • 33. ● Lots of choices: Redis, Couchbase, Aerospike, MongoDB, … ● Our selection and implementation: Redis and Couchbase. ● Redis. ● Couchbase. ● Concerns with NoSQL ○ limitations on queries. ○ indexes. ○ serialization and compression. 3.1. NoSQL 33
  • 34. • Data compression to reduce network IO and save disk space. • Compress larger messages before saving. • Couchbase encoder (serialization). • Use message templates. • Shorten field names. • Add ttl (time to live) on certain messages (to expire messages). 3.2. Fight Against IO and Disk Space 34
  • 35. • PhpRedis: the PHP extension for Redis. • Predis: the Redis client written in PHP. • Other drivers • Package predis/predis-async: asynchronous (non-blocking) version of Predis built on top of ReactPHP. • Class SwooleCoroutineRedis: the asynchronous Redis Client from Swoole. 3.3. Faster PHP Drivers (Redis) 35
  • 36. 3.3. Faster PHP Drivers (Redis) Before and after switching from Predis to PhpRedis Average request time reduced from 16 ms to 11 ms 36
  • 37. ● An Overview on Design Home and the Inbox Service ● The Inbox Service: Key Improvements Made 1. Web Server: Dockerized PHP 7 containers 2. HTTP Processing: Background processing, HTTP compression, and more 3. Data Storage: Doing NoSQL with Redis and Couchbase 4. Hardware and Network: Migrating to Amazon Web Services ● Next ● Q&A Agenda 37
  • 38. 4.1. Deployment with Amazon ECS How did we do code deployment before? 38
  • 39. Benefits: • Zero downtime deployments. • Quick rollback. • ELB health checks. • Autoscaling. 4.1. Deployment with Amazon ECS (cont.) 39
  • 40. • Multiple deployment environments in AWS: test, dev, RC, staging, and production. • Staging environment is helpful. • to do some final tests before major production deployments. • to reproduce and identify production issues. 4.1. Deployment with Amazon ECS (cont.) 40
  • 41. 4.2. Hardware Upgrade Feb 2018: upgraded API servers with faster ones (c5.xlarge: 4 vCPU, 8GB memory; Enhanced networking enabled) 41
  • 42. • Place instances closer to each other. • Move instances to same locations (Availability Zones). • Use internal network instead of Internet to communicate. 4.3. Move Everything into VPC 42
  • 43. 4.3. Move Everything into VPC (cont.) Jan 2019: upgraded API servers with faster ones that were closer to the database nodes (same zone) In the main service, Couchbase operation time decreased to 5 ms 43
  • 44. ● An Overview on Design Home and the Inbox Service ● The Inbox Service: Key Improvements Made 1. Web Server: Dockerized PHP 7 containers 2. HTTP Processing: Background processing, HTTP compression, and more 3. Data Storage: Doing NoSQL with Redis and Couchbase 4. Hardware and Network: Migrating to Amazon Web Services ● Next ● Q&A Agenda 44
  • 45. There are always rooms to push the limit of PHP 45
  • 46. • PHP-FPM • Asynchronous I/O • Swoole • Network Protocols • HTTP/2 • Tars Next 46
  • 47. ● An Overview on Design Home and the Inbox Service ● The Inbox Service: Key Improvements Made 1. Web Server: Dockerized PHP 7 containers 2. HTTP Processing: Background processing, HTTP compression, and more 3. Data Storage: Doing NoSQL with Redis and Couchbase 4. Hardware and Network: Migrating to Amazon Web Services ● Next ● Q&A Agenda 47