SlideShare uma empresa Scribd logo
1 de 13
Baixar para ler offline
Document Locking
with Redis
Tom Corrigan
rostercloud.com
!

@thetommygnr

Melbourne PHP Users Group
November 2013
•

Cloud hosted SaaS product

•

Provide staff rostering primarily for hospitality companies

•

Focus on rostering staff to ad hoc events, not regular schedules

•

3 founders - I’m the IT guy
The problem
•

Multiple users editing an event at the same time

•

Resulting in:
•

Lost work

•

Unhappy customers
Solutions
•

Do nothing, let our customers figure it out
•

•

we might not have any customers

Store locks in our mysql database
•

edge cases are ugly
Redis - A better way

Redis is an open source, BSD licensed, advanced
key-value store. It is often referred to as a data
structure server since keys can contain strings,
hashes, lists, sets and sorted sets.
Redis…
•

Developed by Salvatore Sanfilippo (@antirez)

•

An in-memory data store with optional disk persistence

•

Clusters easily

•

Documentation is amazing!

•

Has myriad uses beyond what I am discussing today

•

Take a look, it will open your eyes to new solutions to age old problems
Using Redis
•

predis is the de facto standard library for PHP

•

can be further accelerated with a C extension

•

As a key value store Redis has a very simple
command set

•

We will be focusing on a handful of commands
today
How did we do it?

•

Create a set using the event id to form a key name

•

Populate the set with the ids of users who have
opened a read lock
Edit action
<?php	
class EventController extends Controller {	
!

	
	

public function editAction($event){	
	 //...	

!

	
	
	
	
	
	
	
	

	
	
	
	
	
	
	
	

//Check for an existing lock and redirect if one exists	
$redisKey = 'event_edit_'.$event->getId();	
$redis = $this->container->get('snc_redis.default');	
if ($redis->exists($redisKey)) {	
	 if (!$redis->sismember($redisKey, $this->getUser()->getId())){	
	 	 return $this->redirect($this->generateUrl(‘event_edit_conflict’, array('id' => $id)));	
	 }	
}	

	
	
	
	
	
	

	 //Create a lock for this user	
	 $redis->sadd($redisKey, $this->getUser()->getId());	
	 $redis->expire($redisKey, 120);	
}	
//...
Releasing a lock
public function updateAction(Request $request, $id)	
{	
	 //$businessLogic->doStuff($event)	
	 //etc...	
!

	 //Once the changes have been flushed to the database release the lock	
	 $redis = $this->container->get('snc_redis.default');	
	 $redis->srem('event_edit_'.$event->getId(), $this->getUser()->getId());	
!

	 //...	
}
Maintaining a lock while editing
Client Side
!

function pollEditLock() {	
	 	 $.get(	
	 	 	 '{{ path(‘event_edit_lock’,	
	 	 	 { 'id': entity.id })}}’,	
	 	 	 function(data) {	
	 	 	 	 	 	 //Do something	
	 	 	 }	
	 	 );	
}	
!
setInterval(pollEditLock, 30 * 1000);	
!

Server Side
!

<?php	
//...	
public function editLockAction(Event $event)	
{	
	 	 //...	
	 	 $redisKey = 'event_edit_'.$event->getId();	
	 	 $redis = $this->container->get('snc_redis.default');	
!
	 	 $redis->sadd($redisKey, $this->getUser()->getId());	
	 	 $redis->expire($redisKey, self::LOCK_TIME);	
!
	 	 return new JsonResponse(array('ok'));	
}	
//...
Sometimes users want to edit concurrently
public function editConflictAction(Request $request, $id)	
{	
	 //...	
!
	 $redisKey = 'event_edit_'.$entity->getId();	
	 $redis = $this->container->get('snc_redis.default');	
!
	 if ($request->query->get('force')) {	
	 	 $redis->sadd($redisKey, $this->getUser()->getId());	
	 	 $redis->expire($redisKey, self::LOCK_TIME);	
!
	 	 return $this->redirect($this->generateUrl('event_edit', array('id' => $id)));	
	 }	
	 	
	 $users = array();	
	 $client = $this->get('context.client');	
	 foreach ($redis->smembers($redisKey) as $userId){	
	 	 $users[] = $em->getRepository(‚ÀòRCRosterBundle:User‚ÀÙ)->find($userId);	
	 }	
!
	 //...	
}
Thankyou
Further Reading:
•

http://redis.io/

•

Slides available at https://speakerdeck.com/u/
tommygnr or from http://phpmelb.org

Mais conteúdo relacionado

Mais procurados

MySQL Monitoring with Zabbix
MySQL Monitoring with ZabbixMySQL Monitoring with Zabbix
MySQL Monitoring with ZabbixFromDual GmbH
 
Cassandra vs. Redis
Cassandra vs. RedisCassandra vs. Redis
Cassandra vs. RedisTim Lossen
 
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...Ontico
 
Open Source Logging and Metric Tools
Open Source Logging and Metric ToolsOpen Source Logging and Metric Tools
Open Source Logging and Metric ToolsPhase2
 
The Wix Microservice Stack
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice StackTomer Gabel
 
Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More!
Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More! Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More!
Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More! Redis Labs
 
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
Leonid Vasilyev  "Building, deploying and running production code at Dropbox"Leonid Vasilyev  "Building, deploying and running production code at Dropbox"
Leonid Vasilyev "Building, deploying and running production code at Dropbox"IT Event
 
Redis Developers Day 2014 - Redis Labs Talks
Redis Developers Day 2014 - Redis Labs TalksRedis Developers Day 2014 - Redis Labs Talks
Redis Developers Day 2014 - Redis Labs TalksRedis Labs
 
Redis Day Keynote Salvatore Sanfillipo Redis Labs
Redis Day Keynote Salvatore Sanfillipo Redis LabsRedis Day Keynote Salvatore Sanfillipo Redis Labs
Redis Day Keynote Salvatore Sanfillipo Redis LabsRedis Labs
 
Supercharging Content Delivery with Varnish
Supercharging Content Delivery with VarnishSupercharging Content Delivery with Varnish
Supercharging Content Delivery with VarnishSamantha Quiñones
 
Lessons Learned From Running Spark On Docker
Lessons Learned From Running Spark On DockerLessons Learned From Running Spark On Docker
Lessons Learned From Running Spark On DockerSpark Summit
 
Best practices for MySQL High Availability
Best practices for MySQL High AvailabilityBest practices for MySQL High Availability
Best practices for MySQL High AvailabilityColin Charles
 
Scaling Social Games
Scaling Social GamesScaling Social Games
Scaling Social GamesPaolo Negri
 
Modern MySQL Monitoring and Dashboards.
Modern MySQL Monitoring and Dashboards.Modern MySQL Monitoring and Dashboards.
Modern MySQL Monitoring and Dashboards.Mydbops
 
Mongrel2, a short introduction
Mongrel2, a short introductionMongrel2, a short introduction
Mongrel2, a short introductionPaolo Negri
 
Freebsd, the unknown giant
Freebsd, the unknown giantFreebsd, the unknown giant
Freebsd, the unknown giantGLC Networks
 
Ansible for large scale deployment
Ansible for large scale deploymentAnsible for large scale deployment
Ansible for large scale deploymentKarthik .P.R
 

Mais procurados (20)

MySQL Monitoring with Zabbix
MySQL Monitoring with ZabbixMySQL Monitoring with Zabbix
MySQL Monitoring with Zabbix
 
Cassandra vs. Redis
Cassandra vs. RedisCassandra vs. Redis
Cassandra vs. Redis
 
Automating Zabbix with Puppet (Werner Dijkerman / 26-11-2015)
Automating Zabbix with Puppet (Werner Dijkerman / 26-11-2015)Automating Zabbix with Puppet (Werner Dijkerman / 26-11-2015)
Automating Zabbix with Puppet (Werner Dijkerman / 26-11-2015)
 
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
Efficient cluster resource management by using Cook and Mesos / Li Jin (Two S...
 
Open Source Logging and Metric Tools
Open Source Logging and Metric ToolsOpen Source Logging and Metric Tools
Open Source Logging and Metric Tools
 
The Wix Microservice Stack
The Wix Microservice StackThe Wix Microservice Stack
The Wix Microservice Stack
 
Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More!
Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More! Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More!
Redis in a Multi Tenant Environment–High Availability, Monitoring & Much More!
 
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
Leonid Vasilyev  "Building, deploying and running production code at Dropbox"Leonid Vasilyev  "Building, deploying and running production code at Dropbox"
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
 
Redis Developers Day 2014 - Redis Labs Talks
Redis Developers Day 2014 - Redis Labs TalksRedis Developers Day 2014 - Redis Labs Talks
Redis Developers Day 2014 - Redis Labs Talks
 
Redis Day Keynote Salvatore Sanfillipo Redis Labs
Redis Day Keynote Salvatore Sanfillipo Redis LabsRedis Day Keynote Salvatore Sanfillipo Redis Labs
Redis Day Keynote Salvatore Sanfillipo Redis Labs
 
Supercharging Content Delivery with Varnish
Supercharging Content Delivery with VarnishSupercharging Content Delivery with Varnish
Supercharging Content Delivery with Varnish
 
Lessons Learned From Running Spark On Docker
Lessons Learned From Running Spark On DockerLessons Learned From Running Spark On Docker
Lessons Learned From Running Spark On Docker
 
Best practices for MySQL High Availability
Best practices for MySQL High AvailabilityBest practices for MySQL High Availability
Best practices for MySQL High Availability
 
Scaling Social Games
Scaling Social GamesScaling Social Games
Scaling Social Games
 
Modern MySQL Monitoring and Dashboards.
Modern MySQL Monitoring and Dashboards.Modern MySQL Monitoring and Dashboards.
Modern MySQL Monitoring and Dashboards.
 
Mongrel2, a short introduction
Mongrel2, a short introductionMongrel2, a short introduction
Mongrel2, a short introduction
 
Redis at LINE
Redis at LINERedis at LINE
Redis at LINE
 
Freebsd, the unknown giant
Freebsd, the unknown giantFreebsd, the unknown giant
Freebsd, the unknown giant
 
Ansible for large scale deployment
Ansible for large scale deploymentAnsible for large scale deployment
Ansible for large scale deployment
 
Memcached
MemcachedMemcached
Memcached
 

Destaque

Redis in Practice
Redis in PracticeRedis in Practice
Redis in PracticeNoah Davis
 
2013 presentation naca_engaging your leadership- exploring and defining your ...
2013 presentation naca_engaging your leadership- exploring and defining your ...2013 presentation naca_engaging your leadership- exploring and defining your ...
2013 presentation naca_engaging your leadership- exploring and defining your ...Brian LeDuc
 
Bảng báo giá hình tool
Bảng báo giá hình toolBảng báo giá hình tool
Bảng báo giá hình toolsy_thanh2001
 
Project 1
Project 1Project 1
Project 1e156160
 
Violéncia de génere
Violéncia de génereVioléncia de génere
Violéncia de génereyatusaeh
 
Eqf iserve jobs-descriptions
Eqf iserve jobs-descriptionsEqf iserve jobs-descriptions
Eqf iserve jobs-descriptionsEMFeExcellence
 
Cfo act of 1990 driving the transformation of federal financial management
Cfo act of 1990 driving the transformation of federal financial managementCfo act of 1990 driving the transformation of federal financial management
Cfo act of 1990 driving the transformation of federal financial managementxiguaatsumi
 
Present rec 04_tor
Present rec 04_torPresent rec 04_tor
Present rec 04_torchibook
 
Employment status key points
Employment status key pointsEmployment status key points
Employment status key pointseleanordeem
 
Symfony - A baptism of fire
Symfony - A baptism of fireSymfony - A baptism of fire
Symfony - A baptism of fireTom Corrigan
 
Yb5500 pg
Yb5500  pgYb5500  pg
Yb5500 pggrin787
 
Tnu ariungerel
Tnu ariungerelTnu ariungerel
Tnu ariungerelsayjargal
 
Танино хобби
Танино хоббиТанино хобби
Танино хоббиAkuJIa
 
[PyConTW 2013] Write Sublime Text 2 Packages with Python
[PyConTW 2013] Write Sublime Text 2 Packages with Python[PyConTW 2013] Write Sublime Text 2 Packages with Python
[PyConTW 2013] Write Sublime Text 2 Packages with PythonJenny Liang
 

Destaque (20)

Redis in Practice
Redis in PracticeRedis in Practice
Redis in Practice
 
2013 presentation naca_engaging your leadership- exploring and defining your ...
2013 presentation naca_engaging your leadership- exploring and defining your ...2013 presentation naca_engaging your leadership- exploring and defining your ...
2013 presentation naca_engaging your leadership- exploring and defining your ...
 
Egiptopp
EgiptoppEgiptopp
Egiptopp
 
Bảng báo giá hình tool
Bảng báo giá hình toolBảng báo giá hình tool
Bảng báo giá hình tool
 
Project 1
Project 1Project 1
Project 1
 
Violéncia de génere
Violéncia de génereVioléncia de génere
Violéncia de génere
 
המעצבים עבודות חוץ
המעצבים עבודות חוץהמעצבים עבודות חוץ
המעצבים עבודות חוץ
 
Eqf iserve jobs-descriptions
Eqf iserve jobs-descriptionsEqf iserve jobs-descriptions
Eqf iserve jobs-descriptions
 
Cfo act of 1990 driving the transformation of federal financial management
Cfo act of 1990 driving the transformation of federal financial managementCfo act of 1990 driving the transformation of federal financial management
Cfo act of 1990 driving the transformation of federal financial management
 
Present rec 04_tor
Present rec 04_torPresent rec 04_tor
Present rec 04_tor
 
Employment status key points
Employment status key pointsEmployment status key points
Employment status key points
 
Symfony - A baptism of fire
Symfony - A baptism of fireSymfony - A baptism of fire
Symfony - A baptism of fire
 
O señor mago
O señor magoO señor mago
O señor mago
 
Yb5500 pg
Yb5500  pgYb5500  pg
Yb5500 pg
 
Tnu ariungerel
Tnu ariungerelTnu ariungerel
Tnu ariungerel
 
Танино хобби
Танино хоббиТанино хобби
Танино хобби
 
good mood in bags
good mood in bagsgood mood in bags
good mood in bags
 
All about managing college environment dr. s. swapna kumar
All about managing college environment  dr. s. swapna kumarAll about managing college environment  dr. s. swapna kumar
All about managing college environment dr. s. swapna kumar
 
Presentación1
Presentación1Presentación1
Presentación1
 
[PyConTW 2013] Write Sublime Text 2 Packages with Python
[PyConTW 2013] Write Sublime Text 2 Packages with Python[PyConTW 2013] Write Sublime Text 2 Packages with Python
[PyConTW 2013] Write Sublime Text 2 Packages with Python
 

Semelhante a Document Locking with Redis in Symfony2

Craft CMS: Beyond the Small Business; Advanced tools and configurations
Craft CMS: Beyond the Small Business; Advanced tools and configurationsCraft CMS: Beyond the Small Business; Advanced tools and configurations
Craft CMS: Beyond the Small Business; Advanced tools and configurationsNate Iler
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and DesktopElizabeth Smith
 
Midgard2 - Content Repository for mobile applications
Midgard2 - Content Repository for mobile applicationsMidgard2 - Content Repository for mobile applications
Midgard2 - Content Repository for mobile applicationsHenri Bergius
 
Drupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp BratislavaDrupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp BratislavaGábor Hojtsy
 
RedisConf18 - Writing modular & encapsulated Redis code
RedisConf18 - Writing modular & encapsulated Redis codeRedisConf18 - Writing modular & encapsulated Redis code
RedisConf18 - Writing modular & encapsulated Redis codeRedis Labs
 
Drupal as a web framework
Drupal as a web frameworkDrupal as a web framework
Drupal as a web frameworkAdam Kalsey
 
S3 & Glacier - The only backup solution you'll ever need
S3 & Glacier - The only backup solution you'll ever needS3 & Glacier - The only backup solution you'll ever need
S3 & Glacier - The only backup solution you'll ever needMatthew Boeckman
 
Building the Enterprise infrastructure with PostgreSQL as the basis for stori...
Building the Enterprise infrastructure with PostgreSQL as the basis for stori...Building the Enterprise infrastructure with PostgreSQL as the basis for stori...
Building the Enterprise infrastructure with PostgreSQL as the basis for stori...PavelKonotopov
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowKarsten Dambekalns
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbMongoDB APAC
 
Redis the better NoSQL
Redis the better NoSQLRedis the better NoSQL
Redis the better NoSQLOpenFest team
 
Does my DIV look big in this?
Does my DIV look big in this?Does my DIV look big in this?
Does my DIV look big in this?glen_a_smith
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperJonathan Wage
 
Render Caching for Drupal 8
Render Caching for Drupal 8Render Caching for Drupal 8
Render Caching for Drupal 8John Doyle
 
Redispresentation apac2012
Redispresentation apac2012Redispresentation apac2012
Redispresentation apac2012Ankur Gupta
 

Semelhante a Document Locking with Redis in Symfony2 (20)

Redis At 6Wunderkinder
Redis At 6WunderkinderRedis At 6Wunderkinder
Redis At 6Wunderkinder
 
Craft CMS: Beyond the Small Business; Advanced tools and configurations
Craft CMS: Beyond the Small Business; Advanced tools and configurationsCraft CMS: Beyond the Small Business; Advanced tools and configurations
Craft CMS: Beyond the Small Business; Advanced tools and configurations
 
What is DDD and how could it help you
What is DDD and how could it help youWhat is DDD and how could it help you
What is DDD and how could it help you
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
 
Midgard2 - Content Repository for mobile applications
Midgard2 - Content Repository for mobile applicationsMidgard2 - Content Repository for mobile applications
Midgard2 - Content Repository for mobile applications
 
Drupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp BratislavaDrupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp Bratislava
 
RedisConf18 - Writing modular & encapsulated Redis code
RedisConf18 - Writing modular & encapsulated Redis codeRedisConf18 - Writing modular & encapsulated Redis code
RedisConf18 - Writing modular & encapsulated Redis code
 
Drupal as a web framework
Drupal as a web frameworkDrupal as a web framework
Drupal as a web framework
 
Fatc
FatcFatc
Fatc
 
S3 & Glacier - The only backup solution you'll ever need
S3 & Glacier - The only backup solution you'll ever needS3 & Glacier - The only backup solution you'll ever need
S3 & Glacier - The only backup solution you'll ever need
 
Building the Enterprise infrastructure with PostgreSQL as the basis for stori...
Building the Enterprise infrastructure with PostgreSQL as the basis for stori...Building the Enterprise infrastructure with PostgreSQL as the basis for stori...
Building the Enterprise infrastructure with PostgreSQL as the basis for stori...
 
Drupal 8 Render Cache
Drupal 8 Render CacheDrupal 8 Render Cache
Drupal 8 Render Cache
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 Flow
 
Buildingsocialanalyticstoolwithmongodb
BuildingsocialanalyticstoolwithmongodbBuildingsocialanalyticstoolwithmongodb
Buildingsocialanalyticstoolwithmongodb
 
Redis the better NoSQL
Redis the better NoSQLRedis the better NoSQL
Redis the better NoSQL
 
Does my DIV look big in this?
Does my DIV look big in this?Does my DIV look big in this?
Does my DIV look big in this?
 
Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
Render Caching for Drupal 8
Render Caching for Drupal 8Render Caching for Drupal 8
Render Caching for Drupal 8
 
Redispresentation apac2012
Redispresentation apac2012Redispresentation apac2012
Redispresentation apac2012
 

Último

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Último (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Document Locking with Redis in Symfony2

  • 1. Document Locking with Redis Tom Corrigan rostercloud.com ! @thetommygnr Melbourne PHP Users Group November 2013
  • 2. • Cloud hosted SaaS product • Provide staff rostering primarily for hospitality companies • Focus on rostering staff to ad hoc events, not regular schedules • 3 founders - I’m the IT guy
  • 3. The problem • Multiple users editing an event at the same time • Resulting in: • Lost work • Unhappy customers
  • 4. Solutions • Do nothing, let our customers figure it out • • we might not have any customers Store locks in our mysql database • edge cases are ugly
  • 5. Redis - A better way Redis is an open source, BSD licensed, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.
  • 6. Redis… • Developed by Salvatore Sanfilippo (@antirez) • An in-memory data store with optional disk persistence • Clusters easily • Documentation is amazing! • Has myriad uses beyond what I am discussing today • Take a look, it will open your eyes to new solutions to age old problems
  • 7. Using Redis • predis is the de facto standard library for PHP • can be further accelerated with a C extension • As a key value store Redis has a very simple command set • We will be focusing on a handful of commands today
  • 8. How did we do it? • Create a set using the event id to form a key name • Populate the set with the ids of users who have opened a read lock
  • 9. Edit action <?php class EventController extends Controller { ! public function editAction($event){ //... ! //Check for an existing lock and redirect if one exists $redisKey = 'event_edit_'.$event->getId(); $redis = $this->container->get('snc_redis.default'); if ($redis->exists($redisKey)) { if (!$redis->sismember($redisKey, $this->getUser()->getId())){ return $this->redirect($this->generateUrl(‘event_edit_conflict’, array('id' => $id))); } } //Create a lock for this user $redis->sadd($redisKey, $this->getUser()->getId()); $redis->expire($redisKey, 120); } //...
  • 10. Releasing a lock public function updateAction(Request $request, $id) { //$businessLogic->doStuff($event) //etc... ! //Once the changes have been flushed to the database release the lock $redis = $this->container->get('snc_redis.default'); $redis->srem('event_edit_'.$event->getId(), $this->getUser()->getId()); ! //... }
  • 11. Maintaining a lock while editing Client Side ! function pollEditLock() { $.get( '{{ path(‘event_edit_lock’, { 'id': entity.id })}}’, function(data) { //Do something } ); } ! setInterval(pollEditLock, 30 * 1000); ! Server Side ! <?php //... public function editLockAction(Event $event) { //... $redisKey = 'event_edit_'.$event->getId(); $redis = $this->container->get('snc_redis.default'); ! $redis->sadd($redisKey, $this->getUser()->getId()); $redis->expire($redisKey, self::LOCK_TIME); ! return new JsonResponse(array('ok')); } //...
  • 12. Sometimes users want to edit concurrently public function editConflictAction(Request $request, $id) { //... ! $redisKey = 'event_edit_'.$entity->getId(); $redis = $this->container->get('snc_redis.default'); ! if ($request->query->get('force')) { $redis->sadd($redisKey, $this->getUser()->getId()); $redis->expire($redisKey, self::LOCK_TIME); ! return $this->redirect($this->generateUrl('event_edit', array('id' => $id))); } $users = array(); $client = $this->get('context.client'); foreach ($redis->smembers($redisKey) as $userId){ $users[] = $em->getRepository(‚ÀòRCRosterBundle:User‚ÀÙ)->find($userId); } ! //... }
  • 13. Thankyou Further Reading: • http://redis.io/ • Slides available at https://speakerdeck.com/u/ tommygnr or from http://phpmelb.org