SlideShare a Scribd company logo
1 of 31
Scaling python webapps from 0 to 50 million users - A top-down approach JinalJhaveri Systems Architect jinal@lolapps.com
Social Games!!
Agenda Why is performance a big issue for social games? Architecture Bottlenecks and solutions Performance strategy Questions
Why is performance a big issue for social games?
Why is performance a big issue for social games?  Extremely high virality installs, notifications, emails, feeds, events Amount of time spent is high http://www.bestfacebookapplications.com
Game Architecture
Bottlenecks and Solutions Load Balancer Web Server Web Application Browser
Load Balancer HAProxy Roundrobin No gzip / no file serving Supports ipbased / regex based load balancing
Bottlenecks and Solutions Load Balancer Web Server Web Application Browser
Webserver Paster n instances (n = no.ofcpu) (10 threads each) Timeout (10 seconds) Disable Nagles optimization
Bottlenecks and Solutions Load Balancer Web Server Web Application Browser
Web Application Memcached to avoid DB trips ORM integration Compression Caching non-existence Lists cache
Memcache / ORM integration    def get(self, query, ident, *args, **kwargs):     key = query.mapper.identity_key_from_primary_key(ident)     obj = query.session.identity_map.get(key)     if obj:         	return obj       mkey = gen_cache_key(key[0].__name__, key[1], self.version_string)   obj = self.mclient.get(mkey) 	if obj is None: obj = query._get(key, ident, **kwargs)          		if obj is not None:        		query.session.expunge(obj)        		self.mclient.set(mkey, obj)     if obj:     return query.session.merge(obj, dont_load=True)     else:     return None Mike Nelson
Memcached to avoid DB trips ORM integration Compression Caching non-existence Lists cache Best Effort caching
Web Application Local cache PythonSpeed/PerformanceTips (wiki.python.org) Asynchronous Facebookapi calls Log processing Event tracking Partial rendering / json / ajax
Bottlenecks and Solutions Load Balancer Web Server Web Application Browser
Browser – Best practices Gzip CDN Loading images in parallel Ajaxification Client side caching
Gzip from paste.gzipper import make_gzip_middleware app = make_gzip_middleware(app, global_conf, compress_level=1)
Browser – Best practices Gzip CDN Loading images in parallel Ajaxification Client side caching
Performance strategy Profile Improve Profile Improve Profile Improve Measure, Measure, Measure load balancer request time Web server request time Controller request time Rendering time
Profiling - Middleware class TimerMiddleware(object):     """      Simple middleware that logs the time of each request to the provided logger.     @author Brian Rue     """     def __init__(self, app, log, name='outer'):         self.app = app          self.log = log          self.name = name     def __call__(self, environ, start_response):         start_time = time.time()         try:             return self.app(environ, start_response)         finally:             end_time = time.time()             url = environ.get('PATH_INFO', '')              if environ.get('QUERY_STRING'):                 url += '?' + environ['QUERY_STRING']             self.log.debug("%f %s-%s" % ((end_time - start_time), self.name, url))
Profiling 2010-02-07 13:27:07 0.182282 mission/index /app/20/mission user: 100000270498442 2010-02-07 13:27:07 0.105489 outer-/app/20/mission?dummyid=1 2010-02-07 13:27:07 0.287437 battle/attack /app/19/battle/attack user: 501879126 2010-02-07 13:27:07 0.006339 track/record_event /app/21/track/record_event user: 1163511266 2010-02-07 13:27:07 0.032981 outer-/app/21/track/record_event?file_name=base.js&cache_key=2285001264723175 2010-02-07 13:27:07 0.006186 track/record_event /app/19/track/record_event user: 1039662536 2010-02-07 13:27:07 0.072400 outer-/app/19/track/record_event?file_name=base.js&cache_key=2285001265425258
Profiling
Profiling - Repoze  # establish the Registry for this application  app = registry.RegistryManager(app) from repoze.profile.profiler import AccumulatingProfileMiddleware app = AccumulatingProfileMiddleware( app,                                              						log_filename='/tmp/gameprofile.log',                                              				 		cachegrind_filename='/tmp/cachegrind.out.bar',                                              			 discard_first_request=True,                                               flush_at_shutdown=True,          		path='/__profile__')
Profiling - Repoze ncalls: number of calls tottime: time spent in given function and excluding the time spent in sub-functions percall: tottime / ncalls cumtime: total time spent in this and all sub-functions. percall: cumtime / ncalls filename:lineno(function): function info.
Profiling - Dozer from dozer import Dozer, Logview app = Logview(app, config) app = Dozer(app)
Database  Optimistic vs. Pessimistic locking version_id Update table set data = xyz where version = 16. SQLAlchemy(echo, echo_pool and logger) Remove/rollback Process1 Data Val = “abc” Version: 16  Process2 Data Val  = “pqr” Version:16 Data:  Val = xyz Version: 16
Paster vs. Tornado
Tornado Used over WSGI CPU and Memory usage down Didn’t do well for high response size Appropriate for asynchronous / realtime
Acknowledgements Lolapps team Brian Rue, AJ Cantu, Fred Blau, Cory Virok, Justin  Rosenthal, Joseph Estrada, Allen Cheung, Vivek Tatineni, Jason Kim, VikramAdukia Family
Questions

More Related Content

What's hot

Developing High Performance Application with Aerospike & Go
Developing High Performance Application with Aerospike & GoDeveloping High Performance Application with Aerospike & Go
Developing High Performance Application with Aerospike & GoChris Stivers
 
Fluentd - road to v1 -
Fluentd - road to v1 -Fluentd - road to v1 -
Fluentd - road to v1 -N Masahiro
 
Dev8d 2011-pipe2 py
Dev8d 2011-pipe2 pyDev8d 2011-pipe2 py
Dev8d 2011-pipe2 pyTony Hirst
 
Playing with Hadoop (NPW2013)
Playing with Hadoop (NPW2013)Playing with Hadoop (NPW2013)
Playing with Hadoop (NPW2013)Søren Lund
 
Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming Cloudflare
 
Background Jobs with Resque
Background Jobs with ResqueBackground Jobs with Resque
Background Jobs with Resquehomanj
 
Ansible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of PythonAnsible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of Pythontoddmowen
 
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...Willian Molinari
 
Elasticsearch (R)Evolution — You Know, for Search… by Philipp Krenn at Big Da...
Elasticsearch (R)Evolution — You Know, for Search… by Philipp Krenn at Big Da...Elasticsearch (R)Evolution — You Know, for Search… by Philipp Krenn at Big Da...
Elasticsearch (R)Evolution — You Know, for Search… by Philipp Krenn at Big Da...Big Data Spain
 
CPAN 模組二三事
CPAN 模組二三事CPAN 模組二三事
CPAN 模組二三事Lin Yo-An
 
OpenERP Performance Benchmark
OpenERP Performance BenchmarkOpenERP Performance Benchmark
OpenERP Performance BenchmarkAudaxis
 
Background processing with Resque
Background processing with ResqueBackground processing with Resque
Background processing with ResqueNicolas Blanco
 
From zero to hero - Easy log centralization with Logstash and Elasticsearch
From zero to hero - Easy log centralization with Logstash and ElasticsearchFrom zero to hero - Easy log centralization with Logstash and Elasticsearch
From zero to hero - Easy log centralization with Logstash and ElasticsearchRafał Kuć
 
Практический опыт профайлинга и оптимизации производительности Ruby-приложений
Практический опыт профайлинга и оптимизации производительности Ruby-приложенийПрактический опыт профайлинга и оптимизации производительности Ruby-приложений
Практический опыт профайлинга и оптимизации производительности Ruby-приложенийOlga Lavrentieva
 
Go-Couchbase Golang Paris 2015/12/17
Go-Couchbase Golang Paris 2015/12/17Go-Couchbase Golang Paris 2015/12/17
Go-Couchbase Golang Paris 2015/12/17Edouard Buschini
 
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloudfog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the CloudWesley Beary
 
Jak se ^bonami\.(cz|pl|sk)$ vešlo do kontejneru
Jak se ^bonami\.(cz|pl|sk)$ vešlo do kontejneruJak se ^bonami\.(cz|pl|sk)$ vešlo do kontejneru
Jak se ^bonami\.(cz|pl|sk)$ vešlo do kontejneruVašek Boch
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisFastly
 

What's hot (20)

Developing High Performance Application with Aerospike & Go
Developing High Performance Application with Aerospike & GoDeveloping High Performance Application with Aerospike & Go
Developing High Performance Application with Aerospike & Go
 
Fluentd - road to v1 -
Fluentd - road to v1 -Fluentd - road to v1 -
Fluentd - road to v1 -
 
Dev8d 2011-pipe2 py
Dev8d 2011-pipe2 pyDev8d 2011-pipe2 py
Dev8d 2011-pipe2 py
 
Php resque
Php resquePhp resque
Php resque
 
Playing with Hadoop (NPW2013)
Playing with Hadoop (NPW2013)Playing with Hadoop (NPW2013)
Playing with Hadoop (NPW2013)
 
Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming
 
Background Jobs with Resque
Background Jobs with ResqueBackground Jobs with Resque
Background Jobs with Resque
 
Ansible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of PythonAnsible, Simplicity, and the Zen of Python
Ansible, Simplicity, and the Zen of Python
 
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
 
WP HTTP API
WP HTTP APIWP HTTP API
WP HTTP API
 
Elasticsearch (R)Evolution — You Know, for Search… by Philipp Krenn at Big Da...
Elasticsearch (R)Evolution — You Know, for Search… by Philipp Krenn at Big Da...Elasticsearch (R)Evolution — You Know, for Search… by Philipp Krenn at Big Da...
Elasticsearch (R)Evolution — You Know, for Search… by Philipp Krenn at Big Da...
 
CPAN 模組二三事
CPAN 模組二三事CPAN 模組二三事
CPAN 模組二三事
 
OpenERP Performance Benchmark
OpenERP Performance BenchmarkOpenERP Performance Benchmark
OpenERP Performance Benchmark
 
Background processing with Resque
Background processing with ResqueBackground processing with Resque
Background processing with Resque
 
From zero to hero - Easy log centralization with Logstash and Elasticsearch
From zero to hero - Easy log centralization with Logstash and ElasticsearchFrom zero to hero - Easy log centralization with Logstash and Elasticsearch
From zero to hero - Easy log centralization with Logstash and Elasticsearch
 
Практический опыт профайлинга и оптимизации производительности Ruby-приложений
Практический опыт профайлинга и оптимизации производительности Ruby-приложенийПрактический опыт профайлинга и оптимизации производительности Ruby-приложений
Практический опыт профайлинга и оптимизации производительности Ruby-приложений
 
Go-Couchbase Golang Paris 2015/12/17
Go-Couchbase Golang Paris 2015/12/17Go-Couchbase Golang Paris 2015/12/17
Go-Couchbase Golang Paris 2015/12/17
 
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloudfog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloud
 
Jak se ^bonami\.(cz|pl|sk)$ vešlo do kontejneru
Jak se ^bonami\.(cz|pl|sk)$ vešlo do kontejneruJak se ^bonami\.(cz|pl|sk)$ vešlo do kontejneru
Jak se ^bonami\.(cz|pl|sk)$ vešlo do kontejneru
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 

Viewers also liked

Design Patterns for Distributed Non-Relational Databases
Design Patterns for Distributed Non-Relational DatabasesDesign Patterns for Distributed Non-Relational Databases
Design Patterns for Distributed Non-Relational Databasesguestdfd1ec
 
Down the rabbit hole, profiling in Django
Down the rabbit hole, profiling in DjangoDown the rabbit hole, profiling in Django
Down the rabbit hole, profiling in DjangoRemco Wendt
 
Learning Pool Webinar: Creating, editing and using images
Learning Pool Webinar: Creating, editing and using imagesLearning Pool Webinar: Creating, editing and using images
Learning Pool Webinar: Creating, editing and using imagesPaul McElvaney
 
Slide Share Mw
Slide Share MwSlide Share Mw
Slide Share MwLutie
 
Workshop Communitymarketing
Workshop CommunitymarketingWorkshop Communitymarketing
Workshop CommunitymarketingSjef Kerkhofs
 
Il bambino picchiato presentazione 28 febbraio 2013
Il bambino picchiato presentazione 28 febbraio 2013Il bambino picchiato presentazione 28 febbraio 2013
Il bambino picchiato presentazione 28 febbraio 2013Umberto Vitrani
 
Social Media In An Eh World
Social Media In An Eh WorldSocial Media In An Eh World
Social Media In An Eh WorldSteve Lipton
 
Pobedite 10 slabosti u poslu koje EU ne trpi
Pobedite 10 slabosti u poslu koje EU ne trpiPobedite 10 slabosti u poslu koje EU ne trpi
Pobedite 10 slabosti u poslu koje EU ne trpiMaja Vujovic
 
Culto Ferias - 05.07.07
Culto Ferias - 05.07.07Culto Ferias - 05.07.07
Culto Ferias - 05.07.07Jubrac Jacui
 
La ReconstruccióN Del PaíS
La ReconstruccióN Del PaíSLa ReconstruccióN Del PaíS
La ReconstruccióN Del PaíSmichellchd
 
Db tips & tricks django meetup
Db tips & tricks django meetupDb tips & tricks django meetup
Db tips & tricks django meetupzeeg
 
Guillems De La Historia
Guillems De La HistoriaGuillems De La Historia
Guillems De La Historiaguestd0403f
 
Systems engineering leidraad se gww door ms
Systems engineering leidraad se gww door msSystems engineering leidraad se gww door ms
Systems engineering leidraad se gww door msMarcel Seijner
 
Learning Pool: Work/Life Balance 2: Managing Stress Successfully
Learning Pool: Work/Life Balance 2: Managing Stress SuccessfullyLearning Pool: Work/Life Balance 2: Managing Stress Successfully
Learning Pool: Work/Life Balance 2: Managing Stress SuccessfullyPaul McElvaney
 
Describing exercise
Describing exerciseDescribing exercise
Describing exerciseSussan Roo
 

Viewers also liked (20)

Design Patterns for Distributed Non-Relational Databases
Design Patterns for Distributed Non-Relational DatabasesDesign Patterns for Distributed Non-Relational Databases
Design Patterns for Distributed Non-Relational Databases
 
Down the rabbit hole, profiling in Django
Down the rabbit hole, profiling in DjangoDown the rabbit hole, profiling in Django
Down the rabbit hole, profiling in Django
 
Learning Pool Webinar: Creating, editing and using images
Learning Pool Webinar: Creating, editing and using imagesLearning Pool Webinar: Creating, editing and using images
Learning Pool Webinar: Creating, editing and using images
 
Slide Share Mw
Slide Share MwSlide Share Mw
Slide Share Mw
 
Workshop Communitymarketing
Workshop CommunitymarketingWorkshop Communitymarketing
Workshop Communitymarketing
 
Il bambino picchiato presentazione 28 febbraio 2013
Il bambino picchiato presentazione 28 febbraio 2013Il bambino picchiato presentazione 28 febbraio 2013
Il bambino picchiato presentazione 28 febbraio 2013
 
Social Media In An Eh World
Social Media In An Eh WorldSocial Media In An Eh World
Social Media In An Eh World
 
Presentatie avans1
Presentatie avans1Presentatie avans1
Presentatie avans1
 
Pobedite 10 slabosti u poslu koje EU ne trpi
Pobedite 10 slabosti u poslu koje EU ne trpiPobedite 10 slabosti u poslu koje EU ne trpi
Pobedite 10 slabosti u poslu koje EU ne trpi
 
Lecture25
Lecture25Lecture25
Lecture25
 
Lecture 14
Lecture 14Lecture 14
Lecture 14
 
Culto Ferias - 05.07.07
Culto Ferias - 05.07.07Culto Ferias - 05.07.07
Culto Ferias - 05.07.07
 
Divosa v1.3
Divosa v1.3Divosa v1.3
Divosa v1.3
 
La ReconstruccióN Del PaíS
La ReconstruccióN Del PaíSLa ReconstruccióN Del PaíS
La ReconstruccióN Del PaíS
 
Db tips & tricks django meetup
Db tips & tricks django meetupDb tips & tricks django meetup
Db tips & tricks django meetup
 
Guillems De La Historia
Guillems De La HistoriaGuillems De La Historia
Guillems De La Historia
 
Systems engineering leidraad se gww door ms
Systems engineering leidraad se gww door msSystems engineering leidraad se gww door ms
Systems engineering leidraad se gww door ms
 
13.04.08 Batismo
13.04.08   Batismo13.04.08   Batismo
13.04.08 Batismo
 
Learning Pool: Work/Life Balance 2: Managing Stress Successfully
Learning Pool: Work/Life Balance 2: Managing Stress SuccessfullyLearning Pool: Work/Life Balance 2: Managing Stress Successfully
Learning Pool: Work/Life Balance 2: Managing Stress Successfully
 
Describing exercise
Describing exerciseDescribing exercise
Describing exercise
 

Similar to Scaling python webapps from 0 to 50 million users - A top-down approach

Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanizecoreygoldberg
 
Software Project Management
Software Project ManagementSoftware Project Management
Software Project ManagementWidoyo PH
 
Easy Web Project Development & Management with Django & Mercurial
Easy Web Project Development & Management with Django & MercurialEasy Web Project Development & Management with Django & Mercurial
Easy Web Project Development & Management with Django & MercurialWidoyo PH
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsMarcelo Pinheiro
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsGraham Dumpleton
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk PemulaOon Arfiandwi
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimizationxiaojueqq12345
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance毅 吕
 
Heavy Web Optimization: Backend
Heavy Web Optimization: BackendHeavy Web Optimization: Backend
Heavy Web Optimization: BackendVõ Duy Tuấn
 
DevoxxUK: Optimizating Application Performance on Kubernetes
DevoxxUK: Optimizating Application Performance on KubernetesDevoxxUK: Optimizating Application Performance on Kubernetes
DevoxxUK: Optimizating Application Performance on KubernetesDinakar Guniguntala
 
Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesciklum_ods
 
Flink Forward SF 2017: Malo Deniélou - No shard left behind: Dynamic work re...
Flink Forward SF 2017: Malo Deniélou -  No shard left behind: Dynamic work re...Flink Forward SF 2017: Malo Deniélou -  No shard left behind: Dynamic work re...
Flink Forward SF 2017: Malo Deniélou - No shard left behind: Dynamic work re...Flink Forward
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindSam Keen
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTPMustafa TURAN
 
Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2Matthew McCullough
 
Naive application development
Naive application developmentNaive application development
Naive application developmentShaka Huang
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationPrestaShop
 
Azure Functions @ global azure day 2017
Azure Functions  @ global azure day 2017Azure Functions  @ global azure day 2017
Azure Functions @ global azure day 2017Sean Feldman
 
Malo Denielou - No shard left behind: Dynamic work rebalancing in Apache Beam
Malo Denielou - No shard left behind: Dynamic work rebalancing in Apache BeamMalo Denielou - No shard left behind: Dynamic work rebalancing in Apache Beam
Malo Denielou - No shard left behind: Dynamic work rebalancing in Apache BeamFlink Forward
 
Swift profiling middleware and tools
Swift profiling middleware and toolsSwift profiling middleware and tools
Swift profiling middleware and toolszhang hua
 

Similar to Scaling python webapps from 0 to 50 million users - A top-down approach (20)

Performance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-MechanizePerformance and Scalability Testing with Python and Multi-Mechanize
Performance and Scalability Testing with Python and Multi-Mechanize
 
Software Project Management
Software Project ManagementSoftware Project Management
Software Project Management
 
Easy Web Project Development & Management with Django & Mercurial
Easy Web Project Development & Management with Django & MercurialEasy Web Project Development & Management with Django & Mercurial
Easy Web Project Development & Management with Django & Mercurial
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
 
PyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web ApplicationsPyCon AU 2012 - Debugging Live Python Web Applications
PyCon AU 2012 - Debugging Live Python Web Applications
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
Web program-peformance-optimization
Web program-peformance-optimizationWeb program-peformance-optimization
Web program-peformance-optimization
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
 
Heavy Web Optimization: Backend
Heavy Web Optimization: BackendHeavy Web Optimization: Backend
Heavy Web Optimization: Backend
 
DevoxxUK: Optimizating Application Performance on Kubernetes
DevoxxUK: Optimizating Application Performance on KubernetesDevoxxUK: Optimizating Application Performance on Kubernetes
DevoxxUK: Optimizating Application Performance on Kubernetes
 
Rapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devicesRapid java backend and api development for mobile devices
Rapid java backend and api development for mobile devices
 
Flink Forward SF 2017: Malo Deniélou - No shard left behind: Dynamic work re...
Flink Forward SF 2017: Malo Deniélou -  No shard left behind: Dynamic work re...Flink Forward SF 2017: Malo Deniélou -  No shard left behind: Dynamic work re...
Flink Forward SF 2017: Malo Deniélou - No shard left behind: Dynamic work re...
 
Profiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / WebgrindProfiling PHP with Xdebug / Webgrind
Profiling PHP with Xdebug / Webgrind
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
 
Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2Google App Engine for Java v0.0.2
Google App Engine for Java v0.0.2
 
Naive application development
Naive application developmentNaive application development
Naive application development
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimization
 
Azure Functions @ global azure day 2017
Azure Functions  @ global azure day 2017Azure Functions  @ global azure day 2017
Azure Functions @ global azure day 2017
 
Malo Denielou - No shard left behind: Dynamic work rebalancing in Apache Beam
Malo Denielou - No shard left behind: Dynamic work rebalancing in Apache BeamMalo Denielou - No shard left behind: Dynamic work rebalancing in Apache Beam
Malo Denielou - No shard left behind: Dynamic work rebalancing in Apache Beam
 
Swift profiling middleware and tools
Swift profiling middleware and toolsSwift profiling middleware and tools
Swift profiling middleware and tools
 

Recently uploaded

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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 

Recently uploaded (20)

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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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...
 

Scaling python webapps from 0 to 50 million users - A top-down approach

  • 1. Scaling python webapps from 0 to 50 million users - A top-down approach JinalJhaveri Systems Architect jinal@lolapps.com
  • 3. Agenda Why is performance a big issue for social games? Architecture Bottlenecks and solutions Performance strategy Questions
  • 4. Why is performance a big issue for social games?
  • 5. Why is performance a big issue for social games? Extremely high virality installs, notifications, emails, feeds, events Amount of time spent is high http://www.bestfacebookapplications.com
  • 7. Bottlenecks and Solutions Load Balancer Web Server Web Application Browser
  • 8. Load Balancer HAProxy Roundrobin No gzip / no file serving Supports ipbased / regex based load balancing
  • 9. Bottlenecks and Solutions Load Balancer Web Server Web Application Browser
  • 10. Webserver Paster n instances (n = no.ofcpu) (10 threads each) Timeout (10 seconds) Disable Nagles optimization
  • 11. Bottlenecks and Solutions Load Balancer Web Server Web Application Browser
  • 12. Web Application Memcached to avoid DB trips ORM integration Compression Caching non-existence Lists cache
  • 13. Memcache / ORM integration    def get(self, query, ident, *args, **kwargs):     key = query.mapper.identity_key_from_primary_key(ident)     obj = query.session.identity_map.get(key)     if obj:          return obj       mkey = gen_cache_key(key[0].__name__, key[1], self.version_string)   obj = self.mclient.get(mkey) if obj is None: obj = query._get(key, ident, **kwargs)          if obj is not None:        query.session.expunge(obj)        self.mclient.set(mkey, obj)     if obj:     return query.session.merge(obj, dont_load=True)     else:     return None Mike Nelson
  • 14. Memcached to avoid DB trips ORM integration Compression Caching non-existence Lists cache Best Effort caching
  • 15. Web Application Local cache PythonSpeed/PerformanceTips (wiki.python.org) Asynchronous Facebookapi calls Log processing Event tracking Partial rendering / json / ajax
  • 16. Bottlenecks and Solutions Load Balancer Web Server Web Application Browser
  • 17. Browser – Best practices Gzip CDN Loading images in parallel Ajaxification Client side caching
  • 18. Gzip from paste.gzipper import make_gzip_middleware app = make_gzip_middleware(app, global_conf, compress_level=1)
  • 19. Browser – Best practices Gzip CDN Loading images in parallel Ajaxification Client side caching
  • 20. Performance strategy Profile Improve Profile Improve Profile Improve Measure, Measure, Measure load balancer request time Web server request time Controller request time Rendering time
  • 21. Profiling - Middleware class TimerMiddleware(object):     """      Simple middleware that logs the time of each request to the provided logger.     @author Brian Rue     """     def __init__(self, app, log, name='outer'):         self.app = app          self.log = log          self.name = name     def __call__(self, environ, start_response):         start_time = time.time()         try:             return self.app(environ, start_response)         finally:             end_time = time.time()             url = environ.get('PATH_INFO', '')              if environ.get('QUERY_STRING'):                 url += '?' + environ['QUERY_STRING']             self.log.debug("%f %s-%s" % ((end_time - start_time), self.name, url))
  • 22. Profiling 2010-02-07 13:27:07 0.182282 mission/index /app/20/mission user: 100000270498442 2010-02-07 13:27:07 0.105489 outer-/app/20/mission?dummyid=1 2010-02-07 13:27:07 0.287437 battle/attack /app/19/battle/attack user: 501879126 2010-02-07 13:27:07 0.006339 track/record_event /app/21/track/record_event user: 1163511266 2010-02-07 13:27:07 0.032981 outer-/app/21/track/record_event?file_name=base.js&cache_key=2285001264723175 2010-02-07 13:27:07 0.006186 track/record_event /app/19/track/record_event user: 1039662536 2010-02-07 13:27:07 0.072400 outer-/app/19/track/record_event?file_name=base.js&cache_key=2285001265425258
  • 24. Profiling - Repoze # establish the Registry for this application app = registry.RegistryManager(app) from repoze.profile.profiler import AccumulatingProfileMiddleware app = AccumulatingProfileMiddleware( app,                                               log_filename='/tmp/gameprofile.log',                                               cachegrind_filename='/tmp/cachegrind.out.bar',                                               discard_first_request=True,                                               flush_at_shutdown=True,         path='/__profile__')
  • 25. Profiling - Repoze ncalls: number of calls tottime: time spent in given function and excluding the time spent in sub-functions percall: tottime / ncalls cumtime: total time spent in this and all sub-functions. percall: cumtime / ncalls filename:lineno(function): function info.
  • 26. Profiling - Dozer from dozer import Dozer, Logview app = Logview(app, config) app = Dozer(app)
  • 27. Database Optimistic vs. Pessimistic locking version_id Update table set data = xyz where version = 16. SQLAlchemy(echo, echo_pool and logger) Remove/rollback Process1 Data Val = “abc” Version: 16 Process2 Data Val = “pqr” Version:16 Data: Val = xyz Version: 16
  • 29. Tornado Used over WSGI CPU and Memory usage down Didn’t do well for high response size Appropriate for asynchronous / realtime
  • 30. Acknowledgements Lolapps team Brian Rue, AJ Cantu, Fred Blau, Cory Virok, Justin Rosenthal, Joseph Estrada, Allen Cheung, Vivek Tatineni, Jason Kim, VikramAdukia Family