SlideShare une entreprise Scribd logo
QUEUES & WORKERS
FASTER PHP APPS USING
PHP DORSET 6/6/16
RICHARD BAKER
twitter.com/r_bake_r
github.com/rjbaker
uk.linkedin.com/in/richjbaker
We’re hiring!
BACKGROUND
MOBILE API
▸ 140+ apps
▸ ~4.5m users
▸ REST/JSON
▸ Apache + PHP + ElasticSearch
▸ 20+ servers / various tasks
▸ Hosted on AWS
THE PROBLEM
TRAFFIC
THE PROBLEM
LATENCY GROWS
ELIMINATE EXPENSIVE, TIME
CONSUMING OPERATIONS AND
CALLS TO EXTERNAL SERVICES
USE MYSQL
WHAT TO QUEUE
MYSQL AS A QUEUE
job_id job_name data status
1 sendEmail {payload} completed
2 sendPush {payload} processing
3 requestThing {payload} waiting
4 resizeSelfie {payload} waiting
WHAT TO QUEUE
WHY NOT USE TRANSACTIONS TO OBTAIN A LOCK?
THE DATABASE IS NOT A
QUEUE. THE DATABASE IS
NOT A QUEUE.
Stephen Corona
WHAT TO QUEUE
https://www.scalingphpbook.com
USE A QUEUE!
QUEUES & WORKERS
MESSAGE QUEUES VS JOB QUEUES
▸ Kind of similar
▸ Most job queues built upon some kind of message queue
▸ Broker messages between systems
▸ Provide transport, storage and protocol
▸ Job queues abstract the lower level message component
▸ Integrate with most applications fairly easily
QUEUES & WORKERS
JOBS VS SCHEDULED TASKS
▸ Run at a predefined point in time ⏰
▸ May repeat at regular intervals or according to
calendar 📅
▸ Typically triggered by cron or other scheduler 🔫
▸ Scheduled tasks can trigger jobs! 💥
CHOOSE A QUEUE WITH
FEATURES BEST SUITED TO
YOUR APPLICATION
CHOOSING A JOB QUEUE
CONSIDERATIONS
▸ Job priority & time sensitivity
▸ Job ordering and consistency (FIFO)
▸ Payload size limits
▸ Message data type & protocol
▸ Support for other languages / client libraries
▸ Failure management / retry policy
▸ Fault tolerance & redundancy
▸ One-time delivery guarantee
▸ Monitoring & statistics
▸ Distribution by task to specific workers e.g. Video encoding
CHOOSING A JOB QUEUE
BEANSTALKD
▸ Protocol similar to Memcached
▸ Clients need to know about all Beanstalkd servers (like memcached!)
▸ Beanstalkd servers can persist jobs, handle restarts without losing jobs
▸ Uses “tubes” to differentiate different queues
▸ Supports job TTR. Failed/hung jobs get put back into queue.
▸ Supports blocking. Client connects and waits for a new job.
▸ Requires setup and maintenance
▸ Loads of client libraries
http://kr.github.io/beanstalkd/
CHOOSING A JOB QUEUE
AMAZON SQS
▸ SAAS - Already using AWS, literally no setup
▸ Massively redundant, cheap, maintenance free
▸ HTTP/JSON under the hood, simple
▸ Supports long-polling.
▸ Best effort FIFO (no guarantees)
▸ No concept of job priority. Use different queues.
▸ Retry policy allows jobs to reappear in queue if not completed in specified time
▸ Configurable number of retries
▸ Queue stats and alarms integrate with autoscaling
▸ Scale worker instances based on queue length/backlog/rate
https://aws.amazon.com/sqs/
CHOOSING A JOB QUEUE
OTHER POPULAR QUEUES
▸ Celery (backed by RabbitMQ) - http://www.celeryproject.org
▸ php-resque (backed by Redis) -https://github.com/
chrisboulton/php-resque
▸ Kafka - http://kafka.apache.org
▸ Gearman - http://gearman.org
▸ Iron.io (SAAS) - https://www.iron.io
▸ Loads more - www.queues.io
PROCESSING
JOBS
PROCESSING JOBS
WORKER PROCESS
▸ Essentially an infinite loop
▸ Executed on command line
▸ Asks queue for new job
▸ Resolves job method
▸ Execute with payload
▸ Delete job from queue
▸ Repeat
PROCESSING JOBS
<?php
$queue = new Queue();
while(true) {
$job = $queue->pop('queue-name');
try {
if ($job->execute()) {
$job->delete();
} else {
$job->release();
}
} catch (Exception $e) {
$job->release();
}
}
IMPROVING THE
WORKER
pcntl_signal_dispatch();
PROCESSING JOBS
PROCESS CONTROL EXTENSIONS (PCNTL)
▸ Respond to unix process signals
▸ Gracefully stop worker processes
▸ Complete current job before exiting
▸ Careful if using Apache mod_php on same
server
▸ http://php.net/manual/en/book.pcntl.php
IMPROVED WORKER
<?php
namespace Demo;
use DemoQueueQueueInterface;
class Worker
{
protected $shouldRun = true;
protected $queue;
public function __construct(QueueInterface $queue)
{
declare(ticks = 1);
$this->queue = $queue;
pcntl_signal(SIGTERM, [$this, 'signalHandler']);
pcntl_signal(SIGINT, [$this, 'signalHandler']);
pcntl_signal(SIGQUIT, [$this, 'signalHandler']);
}
public function run($queueName)
{
echo "Starting worker on queue '{$queueName}' n";
while ($this->shouldRun) {
$job = $this->queue->pop($queueName);
try {
if ($job->execute()) {
$job->delete();
} else {
$job->release();
}
} catch (Exception $e) {
$job->release();
error_log($e->getTraceAsString());
}
pcntl_signal_dispatch();
}
}
public function signalHandler($signal)
{
switch ($signal) {
case SIGTERM:
case SIGINT:
case SIGQUIT:
echo "Job completed. Exiting... n";
$this->shouldRun = false;
break;
}
}
}
IMPROVED WORKER
WTF IS DECLARE(TICKS = 1);?
▸ Officially deprecated
▸ Triggered after php has executed a certain
number of statements
▸ Interacts with pcntl_signal_dispatch()
▸ I admit i’ve not fully tested this with PHP7.0
PROCESSING JOBS
KEEPING WORKERS RUNNING
PROCESSING JOBS
SUPERVISOR
▸ Process manager in similar vein to forever, pm2, php-fpm
▸ Runs as service
▸ Starts and restarts php worker processes
▸ Has CLI client (supervisorctl)
▸ Web interface
▸ Easy to install and configure
http://supervisord.org
PROCESSING JOBS
SUPERVISOR CONFIG [program:alertworker]
command = /usr/bin/php /path/to/queueRunner.php -q=prod-alerts
autorestart = true
autostart = true
directory = /path/to/scripts
environment = DEPLOYMENT='production'
exitcodes = 0,2
numprocs = 1
numprocs_start = 0
priority = 999
startretries = 3
startsecs = 4
stderr_capture_maxbytes = 1MB
stderr_events_enabled = false
stderr_logfile = AUTO
stderr_logfile_backups = 10
stderr_logfile_maxbytes = 50MB
stderr_syslog = false
stdout_capture_maxbytes = 1MB
stdout_events_enabled = true
stdout_logfile = AUTO
stdout_logfile_backups = 10
stdout_logfile_maxbytes = 40MB
stdout_syslog = false
stopsignal = TERM
stopwaitsecs = 10
umask = 022
user = worker
DEMO TIME
THANKS FOR LISTENING!
twitter.com/r_bake_r
github.com/rjbaker
uk.linkedin.com/in/richjbaker

Contenu connexe

Tendances (20)

PDF
Nest.js Introduction
Takuya Tejima
 
PDF
Domain Driven Design
Pascal Larocque
 
PDF
Atelier Python 2eme partie par Achraf Kacimi El Hassani
Shellmates
 
PDF
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Lauren Yew
 
PDF
Control your service resources with systemd
Marian Marinov
 
PPT
Wrapper class (130240116056)
Akshay soni
 
PDF
4.2 PHP Function
Jalpesh Vasa
 
PPTX
polymorphism
Imtiaz Hussain
 
PPT
Création et Gestion de Tables | SQL Oracle
webreaker
 
PDF
Programmation Fonctionnelle
François Sarradin
 
PDF
Correction Examen 2016-2017 POO .pdf
slimyaich3
 
PDF
Use Symfony Messenger Component and CQRS!
Žilvinas Kuusas
 
PPTX
Multithreading
Ghazouani Mahdi
 
PDF
Kubernetes University, Cap sur l’orchestration Docker
Jean-Baptiste Claramonte
 
PDF
A real-world example of Functional Programming with fp-ts - no experience req...
Frederick Fogerty
 
PDF
WebAssembly Fundamentals
Knoldus Inc.
 
PDF
Cours java
Zakaria Mouammin
 
PDF
Chapitre 3 elements de base de java
Amir Souissi
 
PPT
Java IO Package and Streams
babak danyal
 
PDF
OOP in PHP
Alena Holligan
 
Nest.js Introduction
Takuya Tejima
 
Domain Driven Design
Pascal Larocque
 
Atelier Python 2eme partie par Achraf Kacimi El Hassani
Shellmates
 
Threading Made Easy! A Busy Developer’s Guide to Kotlin Coroutines
Lauren Yew
 
Control your service resources with systemd
Marian Marinov
 
Wrapper class (130240116056)
Akshay soni
 
4.2 PHP Function
Jalpesh Vasa
 
polymorphism
Imtiaz Hussain
 
Création et Gestion de Tables | SQL Oracle
webreaker
 
Programmation Fonctionnelle
François Sarradin
 
Correction Examen 2016-2017 POO .pdf
slimyaich3
 
Use Symfony Messenger Component and CQRS!
Žilvinas Kuusas
 
Multithreading
Ghazouani Mahdi
 
Kubernetes University, Cap sur l’orchestration Docker
Jean-Baptiste Claramonte
 
A real-world example of Functional Programming with fp-ts - no experience req...
Frederick Fogerty
 
WebAssembly Fundamentals
Knoldus Inc.
 
Cours java
Zakaria Mouammin
 
Chapitre 3 elements de base de java
Amir Souissi
 
Java IO Package and Streams
babak danyal
 
OOP in PHP
Alena Holligan
 

En vedette (20)

PDF
Queue your work
Jurian Sluiman
 
PDF
Distributed Queue System using Gearman
Eric Cho
 
KEY
CakePHP REST Plugin
Kevin van Zonneveld
 
PDF
Gearman for MySQL
Giuseppe Maxia
 
ODP
CouchDB @ PoliMi
Giorgio Sironi
 
ODP
Case study: iTunes for K-12
Giorgio Sironi
 
ODP
Case study: Insegnalo
Giorgio Sironi
 
ODP
Chansonnier: web application for multimedia search on song videos
Giorgio Sironi
 
PPTX
Queue System and Zend\Queue implementation
Gianluca Arbezzano
 
ODP
Blind detection of image manipulation @ PoliMi
Giorgio Sironi
 
PPTX
PHP and node.js Together
Chris Tankersley
 
PDF
VLANs in the Linux Kernel
Kernel TLV
 
KEY
Distributed app development with nodejs and zeromq
Ruben Tan
 
PDF
Crypto With OpenSSL
Zhi Guan
 
ODP
Case study: Khan Academy
Giorgio Sironi
 
PPTX
Navigation system for blind using GPS & GSM
Prateek Anand
 
PPTX
Map Projections, Datums, GIS and GPS for Everyone
Dr. Geophysics
 
PDF
Gearman: A Job Server made for Scale
Mike Willbanks
 
PDF
Smart blind stick book
Ahmed Moawad
 
PPTX
Vehicle tracking system using gps and google map
sanchit bhargava
 
Queue your work
Jurian Sluiman
 
Distributed Queue System using Gearman
Eric Cho
 
CakePHP REST Plugin
Kevin van Zonneveld
 
Gearman for MySQL
Giuseppe Maxia
 
CouchDB @ PoliMi
Giorgio Sironi
 
Case study: iTunes for K-12
Giorgio Sironi
 
Case study: Insegnalo
Giorgio Sironi
 
Chansonnier: web application for multimedia search on song videos
Giorgio Sironi
 
Queue System and Zend\Queue implementation
Gianluca Arbezzano
 
Blind detection of image manipulation @ PoliMi
Giorgio Sironi
 
PHP and node.js Together
Chris Tankersley
 
VLANs in the Linux Kernel
Kernel TLV
 
Distributed app development with nodejs and zeromq
Ruben Tan
 
Crypto With OpenSSL
Zhi Guan
 
Case study: Khan Academy
Giorgio Sironi
 
Navigation system for blind using GPS & GSM
Prateek Anand
 
Map Projections, Datums, GIS and GPS for Everyone
Dr. Geophysics
 
Gearman: A Job Server made for Scale
Mike Willbanks
 
Smart blind stick book
Ahmed Moawad
 
Vehicle tracking system using gps and google map
sanchit bhargava
 
Publicité

Similaire à Faster PHP apps using Queues and Workers (20)

ODP
Introduction to Python Celery
Mahendra M
 
PPT
Gearman and asynchronous processing in PHP applications
Teamskunkworks
 
PPT
Gearman and asynchronous processing in PHP applications
Dinh Pham
 
PPT
Job Queue - web is more than request and response
Abhinav Lal
 
PPTX
Do you queue (updated)
10n Software, LLC
 
PPTX
Message Queues & Offline Processing with PHP
marcelesser
 
PDF
2015 ZendCon - Do you queue
Mike Willbanks
 
PDF
Delayed operations with queues for website performance
OSInet
 
KEY
Work Queues
ciconf
 
PPT
Task Scheduling and Asynchronous Processing Evolved. Zend Server Job Queue
Sam Hennessy
 
PDF
Khanh-Nguyen - Gearman - distributed process solution
JavaScript Meetup HCMC
 
PDF
Gearman - Northeast PHP 2012
Mike Willbanks
 
PPT
Job_Queues
Abhinav Lal
 
PDF
Work Queue Systems
David Butler
 
PDF
Developer-friendly task queues: what we learned building MRQ, Sylvain Zimmer
Pôle Systematic Paris-Region
 
PDF
Developer-friendly taskqueues: What you should ask yourself before choosing one
Sylvain Zimmer
 
PPTX
Gearman, Supervisor and PHP - Job Management with Sanity!
Abu Ashraf Masnun
 
KEY
Gearman and CodeIgniter
Erik Giberti
 
PPTX
Get queued
Chad Windnagle
 
KEY
Cooking a rabbit pie
Tomas Doran
 
Introduction to Python Celery
Mahendra M
 
Gearman and asynchronous processing in PHP applications
Teamskunkworks
 
Gearman and asynchronous processing in PHP applications
Dinh Pham
 
Job Queue - web is more than request and response
Abhinav Lal
 
Do you queue (updated)
10n Software, LLC
 
Message Queues & Offline Processing with PHP
marcelesser
 
2015 ZendCon - Do you queue
Mike Willbanks
 
Delayed operations with queues for website performance
OSInet
 
Work Queues
ciconf
 
Task Scheduling and Asynchronous Processing Evolved. Zend Server Job Queue
Sam Hennessy
 
Khanh-Nguyen - Gearman - distributed process solution
JavaScript Meetup HCMC
 
Gearman - Northeast PHP 2012
Mike Willbanks
 
Job_Queues
Abhinav Lal
 
Work Queue Systems
David Butler
 
Developer-friendly task queues: what we learned building MRQ, Sylvain Zimmer
Pôle Systematic Paris-Region
 
Developer-friendly taskqueues: What you should ask yourself before choosing one
Sylvain Zimmer
 
Gearman, Supervisor and PHP - Job Management with Sanity!
Abu Ashraf Masnun
 
Gearman and CodeIgniter
Erik Giberti
 
Get queued
Chad Windnagle
 
Cooking a rabbit pie
Tomas Doran
 
Publicité

Dernier (20)

PPTX
Random Presentation By Fuhran Khalil uio
maniieiish
 
PDF
World Game (s) Great Redesign via ZPE - QFS pdf
Steven McGee
 
PPTX
ZARA-Case.pptx djdkkdjnddkdoodkdxjidjdnhdjjdjx
RonnelPineda2
 
PDF
How to Fix Error Code 16 in Adobe Photoshop A Step-by-Step Guide.pdf
Becky Lean
 
PPT
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
PPTX
Research Design - Report on seminar in thesis writing. PPTX
arvielobos1
 
PPTX
1.10-Ruta=1st Term------------------------------1st.pptx
zk7304860098
 
PPTX
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
PPTX
02 IoT Industry Applications and Solutions (1).pptx
abuizzaam
 
PPTX
英国假毕业证诺森比亚大学成绩单GPA修改UNN学生卡网上可查学历成绩单
Taqyea
 
PDF
Web Hosting for Shopify WooCommerce etc.
Harry_Phoneix Harry_Phoneix
 
PDF
The Power and Impact of Promotion most useful
RajaBilal42
 
PPTX
英国学位证(RCM毕业证书)皇家音乐学院毕业证书如何办理
Taqyea
 
PPTX
Internet_of_Things_Presentation_KaifRahaman.pptx
kaifrahaman27593
 
PDF
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
PDF
Technical Guide to Build a Successful Shopify Marketplace from Scratch.pdf
CartCoders
 
PDF
Pas45789-Energs-Efficient-Craigg1ing.pdf
lafinedelcinghiale
 
PPTX
Simplifying and CounFounding in egime.pptx
Ryanto10
 
PDF
The Complete Guide to Chrome Net Internals DNS – 2025
Orage Technologies
 
PDF
Slides PDF: ZPE - QFS Eco Economic Epochs pdf
Steven McGee
 
Random Presentation By Fuhran Khalil uio
maniieiish
 
World Game (s) Great Redesign via ZPE - QFS pdf
Steven McGee
 
ZARA-Case.pptx djdkkdjnddkdoodkdxjidjdnhdjjdjx
RonnelPineda2
 
How to Fix Error Code 16 in Adobe Photoshop A Step-by-Step Guide.pdf
Becky Lean
 
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
Research Design - Report on seminar in thesis writing. PPTX
arvielobos1
 
1.10-Ruta=1st Term------------------------------1st.pptx
zk7304860098
 
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
02 IoT Industry Applications and Solutions (1).pptx
abuizzaam
 
英国假毕业证诺森比亚大学成绩单GPA修改UNN学生卡网上可查学历成绩单
Taqyea
 
Web Hosting for Shopify WooCommerce etc.
Harry_Phoneix Harry_Phoneix
 
The Power and Impact of Promotion most useful
RajaBilal42
 
英国学位证(RCM毕业证书)皇家音乐学院毕业证书如何办理
Taqyea
 
Internet_of_Things_Presentation_KaifRahaman.pptx
kaifrahaman27593
 
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
Technical Guide to Build a Successful Shopify Marketplace from Scratch.pdf
CartCoders
 
Pas45789-Energs-Efficient-Craigg1ing.pdf
lafinedelcinghiale
 
Simplifying and CounFounding in egime.pptx
Ryanto10
 
The Complete Guide to Chrome Net Internals DNS – 2025
Orage Technologies
 
Slides PDF: ZPE - QFS Eco Economic Epochs pdf
Steven McGee
 

Faster PHP apps using Queues and Workers